mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-12-06 08:42:32 -08:00
Redo serial logic
This commit is contained in:
1 parent
388bcb33a1
commit
c3391f16c0
29 files changed
+1423
-1149
No files matched your search
@@ -5,19 +5,17 @@ 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.SerialConnection
|
||||
import dev.slimevr.serial.SerialServer
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.filter
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.mapNotNull
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import solarxr_protocol.rpc.FirmwarePart
|
||||
import solarxr_protocol.rpc.FirmwareUpdateStatus
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
fun interface FirmwareFlasher {
|
||||
suspend fun flash(
|
||||
@@ -28,6 +26,8 @@ fun interface FirmwareFlasher {
|
||||
)
|
||||
}
|
||||
|
||||
private val POST_FLASH_PORT_TIMEOUT = 60.seconds
|
||||
|
||||
suspend fun doSerialFlash(
|
||||
portLocation: String,
|
||||
parts: List<FirmwarePart>,
|
||||
@@ -123,22 +123,17 @@ internal suspend fun doSerialFlashPostFlash(
|
||||
0,
|
||||
)
|
||||
|
||||
serialServer.openConnection(portLocation)
|
||||
val serialConn = serialServer.context.state.value.connections[portLocation]
|
||||
// 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) {
|
||||
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 }
|
||||
.first { logLines -> logLines.any { "starting up" in it.lowercase() } }
|
||||
serialConn.lines.first { "starting up" in it.lowercase() }
|
||||
}
|
||||
|
||||
if (rebooted == null) {
|
||||
@@ -148,13 +143,11 @@ internal suspend fun doSerialFlashPostFlash(
|
||||
}
|
||||
|
||||
// get MAC address by sending GET INFO and parsing the response
|
||||
serialConn.handle.writeCommand("GET INFO")
|
||||
serialConn.write("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()
|
||||
}
|
||||
serialConn.lines.mapNotNull { line ->
|
||||
MAC_REGEX.find(line)?.groupValues?.get(1)?.uppercase()
|
||||
}.first()
|
||||
}
|
||||
|
||||
@@ -167,7 +160,7 @@ internal suspend fun doSerialFlashPostFlash(
|
||||
|
||||
// Remove old UDP connection for this MAC before rebooting to prevent false inactivity timeouts
|
||||
val existingDevice = server.context.state.value.devices.values.find { d ->
|
||||
d.context.state.value.macAddress?.uppercase() == macAddress.uppercase()
|
||||
d.context.state.value.macAddress.equals(macAddress, ignoreCase = true)
|
||||
}
|
||||
if (existingDevice != null) {
|
||||
val oldConn = existingDevice.appContext.udpServer.context.state.value.connections.values.find { c ->
|
||||
@@ -186,14 +179,12 @@ internal suspend fun doSerialFlashPostFlash(
|
||||
|
||||
onStatus(FirmwareUpdateStatus.PROVISIONING, 0)
|
||||
val provisionStartTime = System.currentTimeMillis()
|
||||
serialConn.handle.writeCommand("SET WIFI \"$ssid\" \"$password\"\n")
|
||||
serialConn.write("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 }.first { logLines ->
|
||||
logLines.any {
|
||||
"looking for the server" in it.lowercase() || "searching for the server" in it.lowercase()
|
||||
}
|
||||
serialConn.lines.first {
|
||||
"looking for the server" in it.lowercase() || "searching for the server" in it.lowercase()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,9 +5,7 @@ import dev.slimevr.VRServer
|
||||
import dev.slimevr.config.Settings
|
||||
import dev.slimevr.context.Behaviour
|
||||
import dev.slimevr.context.Context
|
||||
import dev.slimevr.serial.SerialConnection
|
||||
import dev.slimevr.serial.SerialServer
|
||||
import dev.slimevr.serial.isKnownSerialBoard
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
@@ -15,19 +13,17 @@ import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.cancelAndJoin
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.flow.collect
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.mapNotNull
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.selects.select
|
||||
import kotlinx.coroutines.supervisorScope
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import solarxr_protocol.rpc.SerialDeviceType
|
||||
import solarxr_protocol.rpc.TrackerProvisioningStatus
|
||||
import solarxr_protocol.rpc.WifiNetwork
|
||||
import solarxr_protocol.rpc.WifiScanStatus
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
data class ScanState(
|
||||
val status: WifiScanStatus,
|
||||
@@ -95,12 +91,10 @@ data class ProvisioningManager(
|
||||
val trackerJobs = mutableMapOf<String, Job>()
|
||||
val startedPorts = mutableSetOf<String>()
|
||||
|
||||
serialServer.context.state.map { it.availablePorts }.collect { ports ->
|
||||
serialServer.context.state.map { it.ports }.collect { ports ->
|
||||
ports.entries
|
||||
.filter { (portLocation, info) ->
|
||||
portLocation !in startedPorts &&
|
||||
isKnownSerialBoard(info.vendorId, info.productId) &&
|
||||
info.toSerialDevice().type == SerialDeviceType.ESP_TRACKER
|
||||
portLocation !in startedPorts && info.type == SerialDeviceType.ESP_TRACKER
|
||||
}
|
||||
.forEach { (portLocation, _) ->
|
||||
startedPorts += portLocation
|
||||
@@ -131,20 +125,14 @@ data class ProvisioningManager(
|
||||
|
||||
suspend fun startWifiScan() {
|
||||
val currentJob = scanJob
|
||||
if (currentJob != null) {
|
||||
currentJob.cancelAndJoin()
|
||||
}
|
||||
currentJob?.cancelAndJoin()
|
||||
context.dispatch(ProvisioningActions.ScanClear)
|
||||
scanJob = scope.launch {
|
||||
while (isActive) {
|
||||
if (!selectAndOpenPort(context, serialServer)) continue
|
||||
if (!selectScanPort(context, serialServer)) continue
|
||||
val portLocation = context.state.value.scan.portLocation ?: return@launch
|
||||
|
||||
val serialConn = withTimeoutOrNull(3_000) {
|
||||
serialServer.context.state
|
||||
.mapNotNull { it.connections[portLocation] as? SerialConnection.Console }
|
||||
.first()
|
||||
}
|
||||
val serialConn = serialServer.awaitConsole(portLocation, 3.seconds)
|
||||
|
||||
if (serialConn == null) {
|
||||
context.dispatch(ProvisioningActions.ScanStatusChanged(WifiScanStatus.NO_SERIAL_DEVICE_FOUND))
|
||||
@@ -159,7 +147,7 @@ data class ProvisioningManager(
|
||||
awaitCancellation()
|
||||
}
|
||||
val disconnect = async {
|
||||
serialServer.context.state.map { it.availablePorts }.first { portLocation !in it }
|
||||
serialServer.context.state.map { it.ports }.first { portLocation !in it }
|
||||
}
|
||||
select {
|
||||
work.onAwait {}
|
||||
|
||||
@@ -5,14 +5,12 @@ import dev.slimevr.config.Settings
|
||||
import dev.slimevr.config.SettingsActions
|
||||
import dev.slimevr.firmware.waitForConnected
|
||||
import dev.slimevr.serial.MAC_REGEX
|
||||
import dev.slimevr.serial.SerialConnection
|
||||
import dev.slimevr.serial.SerialConnectionActions
|
||||
import dev.slimevr.serial.SerialConsole
|
||||
import dev.slimevr.serial.SerialServer
|
||||
import dev.slimevr.serial.isKnownSerialBoard
|
||||
import dev.slimevr.serial.sortPorts
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.mapNotNull
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
@@ -21,11 +19,13 @@ import solarxr_protocol.rpc.TrackerProvisioningStatus
|
||||
import solarxr_protocol.rpc.WifiAuthMode
|
||||
import solarxr_protocol.rpc.WifiNetwork
|
||||
import solarxr_protocol.rpc.WifiScanStatus
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
internal const val MAX_CONNECTION_RETRIES = 3
|
||||
|
||||
private const val WSCAN_FAILED_MARKER = "[WSCAN] Scan failed!"
|
||||
private const val WSCAN_ACK_MARKER = "[WSCAN] Scanning for WiFi networks..."
|
||||
private const val WSCAN_LINE_MARKER = "[WSCAN]"
|
||||
private const val WSCAN_FAILED_MARKER = "$WSCAN_LINE_MARKER Scan failed!"
|
||||
private const val WSCAN_ACK_MARKER = "$WSCAN_LINE_MARKER Scanning for WiFi networks..."
|
||||
|
||||
private val WSCAN_HEADER_REGEX = Regex("""\[WSCAN] Found (\d+) networks:""")
|
||||
private val WSCAN_ENTRY_PREFIX_REGEX = Regex("""\[WSCAN] (\d+):\s+(\d+)\s+(.*)$""")
|
||||
@@ -72,6 +72,19 @@ private fun parseWifiScanOutcome(lines: List<String>): WifiScanOutcome? {
|
||||
return WifiScanOutcome.Results(networks)
|
||||
}
|
||||
|
||||
private suspend fun awaitWifiScanOutcome(console: SerialConsole): WifiScanOutcome {
|
||||
val scanLines = mutableListOf<String>()
|
||||
return console.lines
|
||||
.mapNotNull { line ->
|
||||
if (WSCAN_LINE_MARKER !in line) return@mapNotNull null
|
||||
scanLines += line
|
||||
parseWifiScanOutcome(scanLines)
|
||||
}
|
||||
.first()
|
||||
}
|
||||
|
||||
private fun parseMacAddress(line: String) = MAC_REGEX.find(line)?.groupValues?.get(1)?.uppercase()
|
||||
|
||||
private fun parseAuthMode(raw: String): WifiAuthMode = when (raw) {
|
||||
"OPEN" -> WifiAuthMode.OPEN
|
||||
"WEP" -> WifiAuthMode.WEP
|
||||
@@ -92,7 +105,7 @@ private const val WSCAN_RESULT_TIMEOUT_MS = 15_000L
|
||||
|
||||
internal suspend fun scanWifiNetworks(
|
||||
context: ProvisioningManagerContext,
|
||||
serialConn: SerialConnection.Console,
|
||||
serialConn: SerialConsole,
|
||||
) {
|
||||
context.dispatch(ProvisioningActions.ScanStatusChanged(WifiScanStatus.SCANNING))
|
||||
|
||||
@@ -100,19 +113,18 @@ internal suspend fun scanWifiNetworks(
|
||||
var attempt = 0
|
||||
|
||||
while (attempt < MAX_SCAN_RETRIES) {
|
||||
serialConn.context.dispatch(SerialConnectionActions.ClearLogs)
|
||||
serialConn.handle.writeCommand("GET WIFISCAN")
|
||||
serialConn.clearLog()
|
||||
serialConn.write("GET WIFISCAN")
|
||||
|
||||
val acked = withTimeoutOrNull(WSCAN_ACK_TIMEOUT_MS) {
|
||||
serialConn.context.state.map { it.logLines }
|
||||
.first { lines -> lines.any { WSCAN_ACK_MARKER in it } }
|
||||
serialConn.lines.first { WSCAN_ACK_MARKER in it }
|
||||
}
|
||||
|
||||
if (acked == null) {
|
||||
if (serialConn.context.state.value.logLines.isEmpty()) {
|
||||
if (serialConn.recent.isEmpty()) {
|
||||
context.dispatch(ProvisioningActions.ScanStatusChanged(WifiScanStatus.NO_SERIAL_LOGS_ERROR))
|
||||
// Wait until we get a log line from the device
|
||||
serialConn.context.state.first { it.logLines.isNotEmpty() }
|
||||
serialConn.lines.first()
|
||||
context.dispatch(ProvisioningActions.ScanStatusChanged(WifiScanStatus.SCANNING))
|
||||
continue
|
||||
}
|
||||
@@ -123,9 +135,7 @@ internal suspend fun scanWifiNetworks(
|
||||
everAcked = true
|
||||
|
||||
val outcome = withTimeoutOrNull(WSCAN_RESULT_TIMEOUT_MS) {
|
||||
serialConn.context.state.map { it.logLines }
|
||||
.mapNotNull { lines -> parseWifiScanOutcome(lines) }
|
||||
.first()
|
||||
awaitWifiScanOutcome(serialConn)
|
||||
}
|
||||
|
||||
if (outcome is WifiScanOutcome.Results) {
|
||||
@@ -150,33 +160,27 @@ internal suspend fun scanWifiNetworks(
|
||||
)
|
||||
}
|
||||
|
||||
internal suspend fun selectAndOpenPort(
|
||||
internal suspend fun selectScanPort(
|
||||
context: ProvisioningManagerContext,
|
||||
serialServer: SerialServer,
|
||||
): Boolean {
|
||||
val portEntry = withTimeoutOrNull(15_000) {
|
||||
val portLocation = withTimeoutOrNull(15_000) {
|
||||
serialServer.context.state
|
||||
.mapNotNull { state ->
|
||||
state.availablePorts.entries.firstOrNull { (_, info) ->
|
||||
isKnownSerialBoard(info.vendorId, info.productId) &&
|
||||
info.toSerialDevice().type == SerialDeviceType.ESP_TRACKER
|
||||
}
|
||||
}
|
||||
.mapNotNull { state -> sortPorts(state.ports.values).firstOrNull { it.type == SerialDeviceType.ESP_TRACKER }?.portLocation }
|
||||
.first()
|
||||
}
|
||||
|
||||
if (portEntry == null) {
|
||||
if (portLocation == null) {
|
||||
context.dispatch(ProvisioningActions.ScanStatusChanged(WifiScanStatus.NO_SERIAL_DEVICE_FOUND))
|
||||
delay(2_000)
|
||||
return false
|
||||
}
|
||||
|
||||
val actions = mutableListOf<ProvisioningActions>(ProvisioningActions.ScanPortSelected(portEntry.key))
|
||||
val actions = mutableListOf<ProvisioningActions>(ProvisioningActions.ScanPortSelected(portLocation))
|
||||
if (context.state.value.scan.networks.isEmpty()) {
|
||||
actions += ProvisioningActions.ScanStatusChanged(WifiScanStatus.SERIAL_INIT)
|
||||
}
|
||||
context.dispatchAll(actions)
|
||||
serialServer.openConnection(portEntry.key)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -190,13 +194,8 @@ internal suspend fun runProvisioningForPort(
|
||||
password: String?,
|
||||
) {
|
||||
context.dispatch(ProvisioningActions.TrackerStatusChanged(portLocation, TrackerProvisioningStatus.SERIAL_INIT))
|
||||
serialServer.openConnection(portLocation)
|
||||
|
||||
val serialConn = withTimeoutOrNull(3_000) {
|
||||
serialServer.context.state
|
||||
.mapNotNull { it.connections[portLocation] as? SerialConnection.Console }
|
||||
.first()
|
||||
}
|
||||
val serialConn = serialServer.awaitConsole(portLocation, 3.seconds)
|
||||
|
||||
if (serialConn == null) {
|
||||
context.dispatch(ProvisioningActions.TrackerStatusChanged(portLocation, TrackerProvisioningStatus.CONNECTION_ERROR))
|
||||
@@ -210,27 +209,23 @@ internal suspend fun runProvisioningForPort(
|
||||
// Handles NO_SERIAL_LOGS_ERROR by blocking until logs appear (not counted as a retry).
|
||||
internal suspend fun obtainMacAddress(
|
||||
context: ProvisioningManagerContext,
|
||||
serialConn: SerialConnection.Console,
|
||||
serialConn: SerialConsole,
|
||||
): Boolean {
|
||||
val portLocation = serialConn.handle.portLocation
|
||||
val portLocation = serialConn.portLocation
|
||||
|
||||
// Reboot and clear logs before MAC acquisition
|
||||
serialConn.context.dispatch(SerialConnectionActions.ClearLogs)
|
||||
serialConn.handle.writeCommand("REBOOT")
|
||||
serialConn.clearLog()
|
||||
serialConn.write("REBOOT")
|
||||
delay(2_000)
|
||||
|
||||
var connectRetries = 0
|
||||
|
||||
while (currentCoroutineContext().isActive) {
|
||||
context.dispatch(ProvisioningActions.TrackerStatusChanged(portLocation, TrackerProvisioningStatus.OBTAINING_MAC_ADDRESS))
|
||||
serialConn.handle.writeCommand("GET INFO")
|
||||
serialConn.write("GET INFO")
|
||||
|
||||
val mac = withTimeoutOrNull(5_000) {
|
||||
serialConn.context.state.map { it.logLines }
|
||||
.mapNotNull { lines ->
|
||||
lines.firstNotNullOfOrNull { MAC_REGEX.find(it)?.groupValues?.get(1)?.uppercase() }
|
||||
}
|
||||
.first()
|
||||
serialConn.lines.mapNotNull { parseMacAddress(it) }.first()
|
||||
}
|
||||
|
||||
if (mac != null) {
|
||||
@@ -240,14 +235,13 @@ internal suspend fun obtainMacAddress(
|
||||
|
||||
// If no logs arrived at all, the tracker is connected but silent.
|
||||
// Show the error and block until logs appear, this is not a retry.
|
||||
if (serialConn.context.state.value.logLines.isEmpty()) {
|
||||
if (serialConn.recent.isEmpty()) {
|
||||
context.dispatch(ProvisioningActions.TrackerStatusChanged(portLocation, TrackerProvisioningStatus.NO_SERIAL_LOGS_ERROR))
|
||||
serialConn.context.state.first { it.logLines.isNotEmpty() }
|
||||
serialConn.lines.first()
|
||||
context.dispatch(ProvisioningActions.TrackerStatusChanged(portLocation, TrackerProvisioningStatus.OBTAINING_MAC_ADDRESS))
|
||||
|
||||
// The GET INFO response may have arrived while we were in the error state.
|
||||
val existingMac = serialConn.context.state.value.logLines
|
||||
.firstNotNullOfOrNull { MAC_REGEX.find(it)?.groupValues?.get(1)?.uppercase() }
|
||||
val existingMac = serialConn.recent.firstNotNullOfOrNull { parseMacAddress(it) }
|
||||
if (existingMac != null) {
|
||||
context.dispatch(ProvisioningActions.TrackerMacAddressObtained(portLocation, existingMac))
|
||||
return true
|
||||
@@ -274,19 +268,18 @@ internal suspend fun obtainMacAddress(
|
||||
// Returns false on timeout.
|
||||
internal suspend fun sendCredentials(
|
||||
context: ProvisioningManagerContext,
|
||||
serialConn: SerialConnection.Console,
|
||||
serialConn: SerialConsole,
|
||||
ssid: String,
|
||||
password: String?,
|
||||
): Boolean {
|
||||
val portLocation = serialConn.handle.portLocation
|
||||
val portLocation = serialConn.portLocation
|
||||
|
||||
serialConn.context.dispatch(SerialConnectionActions.ClearLogs)
|
||||
serialConn.clearLog()
|
||||
context.dispatch(ProvisioningActions.TrackerStatusChanged(portLocation, TrackerProvisioningStatus.PROVISIONING))
|
||||
serialConn.handle.writeCommand("SET WIFI \"$ssid\" \"${password ?: ""}\"\n")
|
||||
serialConn.write("SET WIFI \"$ssid\" \"${password ?: ""}\"\n")
|
||||
|
||||
val acked = withTimeoutOrNull(5_000) {
|
||||
serialConn.context.state.map { it.logLines }
|
||||
.first { lines -> lines.any { "new wifi credentials set" in it.lowercase() } }
|
||||
serialConn.lines.first { "new wifi credentials set" in it.lowercase() }
|
||||
}
|
||||
|
||||
if (acked == null) {
|
||||
@@ -301,26 +294,22 @@ internal suspend fun sendCredentials(
|
||||
// Returns false on timeout or exhausted retries.
|
||||
internal suspend fun waitForWifiConnect(
|
||||
context: ProvisioningManagerContext,
|
||||
serialConn: SerialConnection.Console,
|
||||
serialConn: SerialConsole,
|
||||
): Boolean {
|
||||
val portLocation = serialConn.handle.portLocation
|
||||
val portLocation = serialConn.portLocation
|
||||
var connectRetries = 0
|
||||
|
||||
while (currentCoroutineContext().isActive) {
|
||||
serialConn.context.dispatch(SerialConnectionActions.ClearLogs)
|
||||
serialConn.clearLog()
|
||||
context.dispatch(ProvisioningActions.TrackerStatusChanged(portLocation, TrackerProvisioningStatus.CONNECTING))
|
||||
// null = timeout, true = looking for server, false = can't connect
|
||||
val connectResult = withTimeoutOrNull(15_000) {
|
||||
serialConn.context.state.map { it.logLines }
|
||||
.mapNotNull { lines ->
|
||||
serialConn.lines
|
||||
.mapNotNull { line ->
|
||||
val lower = line.lowercase()
|
||||
when {
|
||||
lines.any {
|
||||
"looking for the server" in it.lowercase() ||
|
||||
"searching for the server" in it.lowercase()
|
||||
} -> true
|
||||
|
||||
lines.any { "can't connect from any credentials" in it.lowercase() } -> false
|
||||
|
||||
"looking for the server" in lower || "searching for the server" in lower -> true
|
||||
"can't connect from any credentials" in lower -> false
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
@@ -334,7 +323,7 @@ internal suspend fun waitForWifiConnect(
|
||||
connectRetries++
|
||||
context.dispatch(ProvisioningActions.TrackerStatusChanged(portLocation, TrackerProvisioningStatus.CONNECTION_ERROR))
|
||||
delay(3_000)
|
||||
serialConn.handle.writeCommand("REBOOT")
|
||||
serialConn.write("REBOOT")
|
||||
}
|
||||
|
||||
// connectResult == false with retries exhausted, or connectResult == null (timeout)
|
||||
@@ -354,11 +343,11 @@ internal suspend fun provisionPort(
|
||||
context: ProvisioningManagerContext,
|
||||
server: VRServer,
|
||||
settings: Settings,
|
||||
serialConn: SerialConnection.Console,
|
||||
serialConn: SerialConsole,
|
||||
ssid: String,
|
||||
password: String?,
|
||||
) {
|
||||
val portLocation = serialConn.handle.portLocation
|
||||
val portLocation = serialConn.portLocation
|
||||
|
||||
if (!obtainMacAddress(context, serialConn)) return
|
||||
val macAddress = context.state.value.trackers[portLocation]?.macAddress ?: return
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
package dev.slimevr.serial
|
||||
|
||||
internal const val MAX_LOG_LINES = 500
|
||||
|
||||
fun reduce(state: SerialConnectionState, action: SerialConnectionActions): SerialConnectionState = when (action) {
|
||||
is SerialConnectionActions.LogLine -> {
|
||||
val lines = if (state.logLines.size >= MAX_LOG_LINES) state.logLines.drop(1) else state.logLines
|
||||
state.copy(logLines = lines + action.line)
|
||||
}
|
||||
|
||||
is SerialConnectionActions.ClearLogs -> state.copy(logLines = listOf())
|
||||
|
||||
is SerialConnectionActions.Disconnected -> state.copy(connected = false)
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package dev.slimevr.serial
|
||||
|
||||
import dev.slimevr.context.Behaviour
|
||||
import dev.slimevr.context.Context
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
|
||||
val MAC_REGEX = Regex("mac: (([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2})", RegexOption.IGNORE_CASE)
|
||||
|
||||
data class SerialPortHandle(
|
||||
val portLocation: String,
|
||||
val descriptivePortName: String,
|
||||
val writeCommand: suspend (String) -> Unit,
|
||||
val close: suspend () -> Unit,
|
||||
)
|
||||
|
||||
data class SerialConnectionState(
|
||||
val portLocation: String,
|
||||
val descriptivePortName: String,
|
||||
val connected: Boolean,
|
||||
val logLines: List<String>,
|
||||
)
|
||||
|
||||
sealed interface SerialConnectionActions {
|
||||
data class LogLine(val line: String) : SerialConnectionActions
|
||||
data object ClearLogs : SerialConnectionActions
|
||||
data object Disconnected : SerialConnectionActions
|
||||
}
|
||||
|
||||
typealias SerialConnectionContext = Context<SerialConnectionState, SerialConnectionActions>
|
||||
typealias SerialConnectionBehaviour = Behaviour<SerialConnection.Console>
|
||||
|
||||
sealed interface SerialConnection {
|
||||
class Console(
|
||||
val context: SerialConnectionContext,
|
||||
val handle: SerialPortHandle,
|
||||
) : SerialConnection {
|
||||
fun startObserving() = context.observeAll(this)
|
||||
|
||||
companion object {
|
||||
fun create(handle: SerialPortHandle, scope: CoroutineScope): Console {
|
||||
val behaviours = emptyList<SerialConnectionBehaviour>()
|
||||
val context = Context.create(
|
||||
initialState = SerialConnectionState(
|
||||
portLocation = handle.portLocation,
|
||||
descriptivePortName = handle.descriptivePortName,
|
||||
connected = true,
|
||||
logLines = listOf(),
|
||||
),
|
||||
scope = scope,
|
||||
reducer = ::reduce,
|
||||
behaviours = behaviours,
|
||||
name = "SerialConnection[${handle.descriptivePortName}]",
|
||||
)
|
||||
|
||||
val conn = Console(context = context, handle = handle)
|
||||
conn.startObserving()
|
||||
return conn
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data object Flashing : SerialConnection
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package dev.slimevr.serial
|
||||
|
||||
import kotlinx.coroutines.CompletableJob
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.channels.BufferOverflow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
|
||||
val MAC_REGEX = Regex("mac: (([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2})", RegexOption.IGNORE_CASE)
|
||||
|
||||
internal const val MAX_LOG_LINES = 500
|
||||
private const val LOG_BURST_CAPACITY = 2000
|
||||
|
||||
/**
|
||||
* A line stream from one open port. Emitting never suspends and a slow collector loses its oldest
|
||||
* lines, so a reader thread can't stall. The last [MAX_LOG_LINES] lines replay to new collectors
|
||||
*/
|
||||
class SerialConsole private constructor(
|
||||
private val handle: SerialPortHandle,
|
||||
private val log: MutableSharedFlow<String>,
|
||||
private val closedSignal: CompletableJob,
|
||||
) {
|
||||
val portLocation get() = handle.portLocation
|
||||
val descriptivePortName get() = handle.descriptivePortName
|
||||
val lines: SharedFlow<String> = log.asSharedFlow()
|
||||
|
||||
val recent: List<String> get() = log.replayCache
|
||||
|
||||
val closed: Job get() = closedSignal
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
fun clearLog() = log.resetReplayCache()
|
||||
|
||||
suspend fun write(command: String) = handle.writeCommand(command)
|
||||
|
||||
suspend fun close() {
|
||||
closedSignal.complete()
|
||||
handle.close()
|
||||
}
|
||||
|
||||
companion object {
|
||||
suspend fun open(watcher: SerialPortWatcher, portLocation: String): SerialConsole? {
|
||||
val log = MutableSharedFlow<String>(
|
||||
replay = MAX_LOG_LINES,
|
||||
extraBufferCapacity = LOG_BURST_CAPACITY,
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||
)
|
||||
val closed = Job()
|
||||
val handle = watcher.open(portLocation, { line -> log.tryEmit(line) }, { closed.complete() })
|
||||
?: return null
|
||||
return SerialConsole(handle, log, closed)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package dev.slimevr.serial
|
||||
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import kotlinx.coroutines.FlowPreview
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.debounce
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.flow.onStart
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
||||
private val HOTPLUG_SETTLE = 250.milliseconds
|
||||
|
||||
class PortDetectionBehaviour(private val watcher: SerialPortWatcher) : SerialServerBehaviour {
|
||||
@OptIn(FlowPreview::class)
|
||||
override fun observe(receiver: SerialServer) {
|
||||
watcher.changes
|
||||
.debounce(HOTPLUG_SETTLE)
|
||||
.onStart { emit(Unit) }
|
||||
.onEach { receiver.refresh() }
|
||||
.catch { e -> AppLogger.serial.error(e, "Serial hotplug events stopped") }
|
||||
.launchIn(receiver.context.scope)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package dev.slimevr.serial
|
||||
|
||||
private const val MAX_LINE_BYTES = 4096
|
||||
|
||||
class LineAssembler {
|
||||
private var buffer = ByteArray(256)
|
||||
private var size = 0
|
||||
|
||||
fun feed(data: ByteArray, length: Int, onLine: (String) -> Unit) {
|
||||
for (i in 0 until length) {
|
||||
val byte = data[i]
|
||||
if (byte == NEWLINE) {
|
||||
emit(onLine)
|
||||
continue
|
||||
}
|
||||
if (size == buffer.size) buffer = buffer.copyOf(size * 2)
|
||||
buffer[size++] = byte
|
||||
if (size >= MAX_LINE_BYTES) emit(onLine)
|
||||
}
|
||||
}
|
||||
|
||||
private fun emit(onLine: (String) -> Unit) {
|
||||
val line = String(buffer, 0, size, Charsets.UTF_8).trimEnd()
|
||||
size = 0
|
||||
onLine(line)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val NEWLINE = '\n'.code.toByte()
|
||||
}
|
||||
}
|
||||
@@ -2,52 +2,33 @@ package dev.slimevr.serial
|
||||
|
||||
import dev.slimevr.context.Behaviour
|
||||
import dev.slimevr.context.Context
|
||||
import dev.slimevr.hid.isCompatibleHidReceiver
|
||||
import dev.slimevr.hid.isCompatibleHidTracker
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import solarxr_protocol.rpc.SerialDevice
|
||||
import solarxr_protocol.rpc.SerialDeviceType
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlin.time.Duration
|
||||
|
||||
interface FlashingHandler {
|
||||
fun openSerial(port: Any)
|
||||
fun closeSerial()
|
||||
fun write(data: ByteArray)
|
||||
fun read(length: Int): ByteArray
|
||||
fun setDTR(value: Boolean)
|
||||
fun setRTS(value: Boolean)
|
||||
fun changeBaud(baud: Int)
|
||||
fun setReadTimeout(timeout: Long)
|
||||
fun availableBytes(): Int
|
||||
fun flushIOBuffers()
|
||||
}
|
||||
|
||||
data class SerialPortInfo(
|
||||
val portLocation: String,
|
||||
val descriptivePortName: String,
|
||||
val vendorId: Int,
|
||||
val productId: Int,
|
||||
) {
|
||||
fun toSerialDevice() = SerialDevice(
|
||||
port = portLocation,
|
||||
name = descriptivePortName,
|
||||
type = when {
|
||||
isCompatibleHidReceiver(vendorId, productId) -> SerialDeviceType.HID_RECEIVER
|
||||
isCompatibleHidTracker(vendorId, productId) -> SerialDeviceType.HID_TRACKER
|
||||
else -> SerialDeviceType.ESP_TRACKER
|
||||
},
|
||||
)
|
||||
private sealed interface Claim {
|
||||
class Got(val console: SerialConsole) : Claim
|
||||
data object Retry : Claim
|
||||
data object Failed : Claim
|
||||
}
|
||||
|
||||
data class SerialServerState(
|
||||
val availablePorts: Map<String, SerialPortInfo>,
|
||||
val connections: Map<String, SerialConnection>,
|
||||
val ports: Map<String, SerialPortInfo>,
|
||||
/** Ports a firmware flash holds. A claim outlasts the port re-enumerating mid-flash */
|
||||
val flashing: Set<String>,
|
||||
)
|
||||
|
||||
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
|
||||
data class PortsChanged(val ports: Map<String, SerialPortInfo>) : SerialServerActions
|
||||
data class FlashingStarted(val portLocation: String) : SerialServerActions
|
||||
data class FlashingEnded(val portLocation: String) : SerialServerActions
|
||||
}
|
||||
|
||||
typealias SerialServerContext = Context<SerialServerState, SerialServerActions>
|
||||
@@ -55,98 +36,109 @@ typealias SerialServerBehaviour = Behaviour<SerialServer>
|
||||
|
||||
class SerialServer(
|
||||
val context: SerialServerContext,
|
||||
private val openPortFactory: suspend (
|
||||
portLocation: String,
|
||||
onDataReceived: (portLocation: String, line: String) -> Unit,
|
||||
onPortDisconnected: suspend (portLocation: String) -> Unit,
|
||||
) -> SerialPortHandle?,
|
||||
private val openFlashingPortFactory: () -> FlashingHandler,
|
||||
private val watcher: SerialPortWatcher,
|
||||
) {
|
||||
private val ownership = Mutex()
|
||||
private val consoles = mutableMapOf<String, SerialConsole>()
|
||||
|
||||
fun startObserving() = context.observeAll(this)
|
||||
|
||||
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()
|
||||
suspend fun refresh() {
|
||||
val found = try {
|
||||
watcher.enumerate()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
AppLogger.serial.error(e, "Serial port enumeration failed")
|
||||
return
|
||||
}
|
||||
ownership.withLock {
|
||||
val known = context.state.value.ports.keys
|
||||
if (known != found.keys) {
|
||||
AppLogger.serial.info("Serial ports changed, added ${(found.keys - known).joinToString()} removed ${(known - found.keys).joinToString()}")
|
||||
}
|
||||
for (location in consoles.keys.filter { it !in found }) closeConsole(location)
|
||||
context.dispatch(SerialServerActions.PortsChanged(found))
|
||||
}
|
||||
context.dispatchAll(
|
||||
listOf(
|
||||
SerialServerActions.RemoveConnection(portLocation),
|
||||
SerialServerActions.PortLost(portLocation),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
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 awaitConsole(portLocation: String, timeout: Duration): SerialConsole? = withTimeoutOrNull(timeout) {
|
||||
claimConsole(portLocation)
|
||||
}
|
||||
|
||||
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))
|
||||
private suspend fun claimConsole(portLocation: String): SerialConsole? {
|
||||
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.Failed -> return null
|
||||
is Claim.Retry -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun openConnection(portLocation: String) {
|
||||
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)
|
||||
// this port failed and the cleanup in [watchForClose] hasn't run yet
|
||||
closeConsole(portLocation)
|
||||
}
|
||||
AppLogger.serial.info("Opening serial console on $portLocation")
|
||||
val console = SerialConsole.open(watcher, portLocation) ?: return Claim.Failed
|
||||
consoles[portLocation] = console
|
||||
AppLogger.serial.info("Opened serial console on $portLocation")
|
||||
watchForClose(console)
|
||||
return Claim.Got(console)
|
||||
}
|
||||
|
||||
suspend fun openForFlashing(portLocation: String): FlashingHandler? = ownership.withLock {
|
||||
val state = context.state.value
|
||||
if (!state.availablePorts.containsKey(portLocation) || state.connections.containsKey(portLocation)) return
|
||||
val handle = openPortFactory(portLocation, ::onDataReceived, ::onPortDisconnected) ?: return
|
||||
context.dispatch(SerialServerActions.RegisterConnection(portLocation, SerialConnection.Console.create(handle, context.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)) return null
|
||||
if (state.connections[portLocation] is SerialConnection.Flashing) return null
|
||||
closeConnection(portLocation)
|
||||
val handler = openFlashingPortFactory()
|
||||
context.dispatch(SerialServerActions.RegisterConnection(portLocation, SerialConnection.Flashing))
|
||||
return object : FlashingHandler by handler {
|
||||
if (portLocation !in state.ports || portLocation in state.flashing) return@withLock null
|
||||
closeConsole(portLocation)
|
||||
context.dispatch(SerialServerActions.FlashingStarted(portLocation))
|
||||
val handler = watcher.openForFlashing()
|
||||
object : FlashingHandler by handler {
|
||||
override fun closeSerial() {
|
||||
try {
|
||||
handler.closeSerial()
|
||||
} finally {
|
||||
context.dispatch(SerialServerActions.RemoveConnection(portLocation))
|
||||
context.dispatch(SerialServerActions.FlashingEnded(portLocation))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun closeConsole(portLocation: String) {
|
||||
val console = consoles.remove(portLocation) ?: return
|
||||
AppLogger.serial.info("Closing serial console on $portLocation")
|
||||
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")
|
||||
ownership.withLock {
|
||||
if (consoles[console.portLocation] === console) closeConsole(console.portLocation)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun create(
|
||||
openPort: suspend (portLocation: String, onDataReceived: (String, String) -> Unit, onPortDisconnected: suspend (String) -> Unit) -> SerialPortHandle?,
|
||||
openFlashingPort: () -> FlashingHandler,
|
||||
scope: CoroutineScope,
|
||||
): SerialServer {
|
||||
fun create(watcher: SerialPortWatcher, scope: CoroutineScope): SerialServer {
|
||||
val context = Context.create(
|
||||
initialState = SerialServerState(availablePorts = mapOf(), connections = mapOf()),
|
||||
initialState = SerialServerState(ports = mapOf(), flashing = setOf()),
|
||||
scope = scope,
|
||||
reducer = ::reduce,
|
||||
behaviours = listOf(PortDetectionBehaviour(watcher)),
|
||||
name = "SerialServer",
|
||||
)
|
||||
val server = SerialServer(
|
||||
context = context,
|
||||
openPortFactory = openPort,
|
||||
openFlashingPortFactory = openFlashingPort,
|
||||
)
|
||||
val server = SerialServer(context = context, watcher = watcher)
|
||||
server.startObserving()
|
||||
return server
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun isFree(state: SerialServerState, portLocation: String) = portLocation in state.ports && portLocation !in state.flashing
|
||||
@@ -1,15 +1,7 @@
|
||||
package dev.slimevr.serial
|
||||
|
||||
fun reduce(state: SerialServerState, action: SerialServerActions): SerialServerState = when (action) {
|
||||
is SerialServerActions.PortDetected ->
|
||||
state.copy(availablePorts = state.availablePorts + (action.info.portLocation to action.info))
|
||||
|
||||
is SerialServerActions.PortLost ->
|
||||
state.copy(availablePorts = state.availablePorts - action.portLocation)
|
||||
|
||||
is SerialServerActions.RegisterConnection ->
|
||||
state.copy(connections = state.connections + (action.portLocation to action.connection))
|
||||
|
||||
is SerialServerActions.RemoveConnection ->
|
||||
state.copy(connections = state.connections - action.portLocation)
|
||||
is SerialServerActions.PortsChanged -> state.copy(ports = action.ports)
|
||||
is SerialServerActions.FlashingStarted -> state.copy(flashing = state.flashing + action.portLocation)
|
||||
is SerialServerActions.FlashingEnded -> state.copy(flashing = state.flashing - action.portLocation)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package dev.slimevr.serial
|
||||
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import solarxr_protocol.rpc.SerialDevice
|
||||
|
||||
interface FlashingHandler {
|
||||
fun openSerial(port: Any)
|
||||
fun closeSerial()
|
||||
fun write(data: ByteArray)
|
||||
fun read(length: Int): ByteArray
|
||||
fun setDTR(value: Boolean)
|
||||
fun setRTS(value: Boolean)
|
||||
fun changeBaud(baud: Int)
|
||||
fun setReadTimeout(timeout: Long)
|
||||
fun availableBytes(): Int
|
||||
fun flushIOBuffers()
|
||||
}
|
||||
|
||||
data class SerialPortHandle(
|
||||
val portLocation: String,
|
||||
val descriptivePortName: String,
|
||||
val writeCommand: suspend (String) -> Unit,
|
||||
val close: suspend () -> Unit,
|
||||
)
|
||||
|
||||
data class SerialPortInfo(
|
||||
val portLocation: String,
|
||||
val descriptivePortName: String,
|
||||
val vendorId: Int,
|
||||
val productId: Int,
|
||||
val serialNumber: String? = null,
|
||||
) {
|
||||
val type get() = classifyPort(vendorId, productId)
|
||||
|
||||
fun toSerialDevice() = SerialDevice(
|
||||
port = portLocation,
|
||||
name = descriptivePortName,
|
||||
type = type,
|
||||
vendorId = vendorId.toUShort(),
|
||||
productId = productId.toUShort(),
|
||||
serialNumber = serialNumber,
|
||||
)
|
||||
}
|
||||
|
||||
/** Platform side of the serial server: what is plugged in, when that changes, and how to open it */
|
||||
interface SerialPortWatcher {
|
||||
/** USB serial ports present right now, keyed by port location */
|
||||
suspend fun enumerate(): Map<String, SerialPortInfo>
|
||||
|
||||
/**
|
||||
* Emits when the OS reports a serial port arriving or leaving. If it fails the error is logged and
|
||||
* the port list stops updating
|
||||
*/
|
||||
val changes: Flow<Unit>
|
||||
|
||||
/**
|
||||
* Opens a console on the port. [onLine] receives each received line without blocking. [onClosed] runs
|
||||
* when the port goes away or fails, after which the handle is dead
|
||||
*/
|
||||
suspend fun open(portLocation: String, onLine: (String) -> Unit, onClosed: () -> Unit): SerialPortHandle?
|
||||
|
||||
fun openForFlashing(): FlashingHandler
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package dev.slimevr.serial
|
||||
|
||||
import dev.slimevr.hid.isCompatibleHidDevice
|
||||
import dev.slimevr.hid.isCompatibleHidReceiver
|
||||
import dev.slimevr.hid.isCompatibleHidTracker
|
||||
import solarxr_protocol.rpc.SerialDeviceType
|
||||
|
||||
private val SUPPORTED_BOARDS: Set<Pair<Int, Int>> = setOf(
|
||||
private val ESP_BRIDGES: Set<Pair<Int, Int>> = setOf(
|
||||
Pair(0x1A86, 0x7522), // CH340
|
||||
Pair(0x1A86, 0x7523), // CH340
|
||||
Pair(0x1A86, 0x5523), // CH341
|
||||
@@ -14,4 +16,14 @@ private val SUPPORTED_BOARDS: Set<Pair<Int, Int>> = setOf(
|
||||
Pair(0x0403, 0x6001), // FTDI FT232
|
||||
)
|
||||
|
||||
fun isKnownSerialBoard(vid: Int, pid: Int) = SUPPORTED_BOARDS.contains(vid to pid) || isCompatibleHidDevice(vid, pid)
|
||||
fun classifyPort(vid: Int, pid: Int): SerialDeviceType = when {
|
||||
isCompatibleHidReceiver(vid, pid) -> SerialDeviceType.HID_RECEIVER
|
||||
isCompatibleHidTracker(vid, pid) -> SerialDeviceType.HID_TRACKER
|
||||
(vid to pid) in ESP_BRIDGES -> SerialDeviceType.ESP_TRACKER
|
||||
else -> SerialDeviceType.UNKNOWN
|
||||
}
|
||||
|
||||
/** Recognized devices first, then by location, so the first entry is a stable default pick */
|
||||
fun sortPorts(ports: Collection<SerialPortInfo>): List<SerialPortInfo> = ports.sortedWith(
|
||||
compareBy({ it.type == SerialDeviceType.UNKNOWN }, { it.type.value }, { it.portLocation }),
|
||||
)
|
||||
@@ -1,20 +1,30 @@
|
||||
package dev.slimevr.solarxr.rpc
|
||||
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import dev.slimevr.serial.SerialConnection
|
||||
import dev.slimevr.serial.SerialConsole
|
||||
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.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.channels.BufferOverflow
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.drop
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.first
|
||||
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.SerialConsoleStatus
|
||||
import solarxr_protocol.rpc.SerialDevice
|
||||
import solarxr_protocol.rpc.SerialDevicesRequest
|
||||
import solarxr_protocol.rpc.SerialDevicesResponse
|
||||
import solarxr_protocol.rpc.SerialTrackerCustomCommandRequest
|
||||
@@ -23,119 +33,142 @@ import solarxr_protocol.rpc.SerialTrackerGetInfoRequest
|
||||
import solarxr_protocol.rpc.SerialTrackerGetWifiScanRequest
|
||||
import solarxr_protocol.rpc.SerialTrackerRebootRequest
|
||||
import solarxr_protocol.rpc.SerialUpdateResponse
|
||||
import kotlin.time.Duration
|
||||
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
|
||||
|
||||
private const val LOG_QUEUE_CAPACITY = 2000
|
||||
private const val MAX_BATCH_CHARS = 16_000
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
private suspend fun runConsoleSession(
|
||||
receiver: SolarXRBridge,
|
||||
serialServer: SerialServer,
|
||||
portLocation: String,
|
||||
activeConsole: MutableStateFlow<SerialConsole?>,
|
||||
) = coroutineScope {
|
||||
launch {
|
||||
serialServer.context.state
|
||||
.map { blockedStatus(it, portLocation) }
|
||||
.distinctUntilChanged()
|
||||
.filterNotNull()
|
||||
.collect { status -> receiver.sendRpc(SerialUpdateResponse(status = status)) }
|
||||
}
|
||||
|
||||
while (true) {
|
||||
AppLogger.solarxr.info("Serial session waiting for a console on $portLocation")
|
||||
if (isPortFree(serialServer.context.state.value, portLocation)) {
|
||||
receiver.sendRpc(SerialUpdateResponse(status = SerialConsoleStatus.OPENING))
|
||||
}
|
||||
val console = serialServer.awaitConsole(portLocation, Duration.INFINITE)
|
||||
if (console == 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))
|
||||
serialServer.context.state.first { it != before }
|
||||
continue
|
||||
}
|
||||
|
||||
activeConsole.value = console
|
||||
val device = serialServer.context.state.value.ports[portLocation]?.toSerialDevice()
|
||||
receiver.sendRpc(SerialUpdateResponse(status = SerialConsoleStatus.OPEN, device = device))
|
||||
val stream = launch { streamLines(receiver, console, device) }
|
||||
console.closed.join()
|
||||
AppLogger.solarxr.info("Serial console on $portLocation ended")
|
||||
stream.cancel()
|
||||
activeConsole.value = null
|
||||
|
||||
if (isPortFree(serialServer.context.state.value, portLocation)) delay(REOPEN_DELAY)
|
||||
}
|
||||
}
|
||||
|
||||
private fun blockedStatus(state: SerialServerState, portLocation: String) = when {
|
||||
portLocation in state.flashing -> SerialConsoleStatus.BUSY
|
||||
portLocation !in state.ports -> SerialConsoleStatus.WAITING
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun isPortFree(state: SerialServerState, portLocation: String) = blockedStatus(state, portLocation) == null
|
||||
|
||||
// Lines that arrive while a send is in flight go out together, so a burst costs a few messages
|
||||
private suspend fun streamLines(
|
||||
receiver: SolarXRBridge,
|
||||
console: SerialConsole,
|
||||
device: SerialDevice?,
|
||||
) = coroutineScope {
|
||||
val queue = Channel<String>(LOG_QUEUE_CAPACITY, BufferOverflow.DROP_OLDEST)
|
||||
launch { console.lines.collect { queue.trySend(it) } }
|
||||
|
||||
for (first in queue) {
|
||||
val batch = StringBuilder().append(first).append('\n')
|
||||
while (batch.length < MAX_BATCH_CHARS) {
|
||||
val next = queue.tryReceive().getOrNull() ?: break
|
||||
batch.append(next).append('\n')
|
||||
}
|
||||
receiver.sendRpc(SerialUpdateResponse(log = batch.toString(), device = device, status = SerialConsoleStatus.OPEN))
|
||||
}
|
||||
}
|
||||
|
||||
class SerialBehaviour(private val serialServer: SerialServer) : SolarXRBridgeBehaviour {
|
||||
override fun observe(receiver: SolarXRBridge) {
|
||||
val scope = receiver.context.scope
|
||||
|
||||
// We assume that you can only subscribe to one serial console at a time
|
||||
var logSubscription: Job? = null
|
||||
var activePortLocation: String? = null
|
||||
// A client has one console open at a time
|
||||
var session: Job? = null
|
||||
val activeConsole = MutableStateFlow<SerialConsole?>(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()
|
||||
// The full list goes out on every change. Clients replace their list, so removals need no event
|
||||
serialServer.context.state
|
||||
.map { it.availablePorts }
|
||||
.map { sortPorts(it.ports.values) }
|
||||
.distinctUntilChanged()
|
||||
.onEach { ports ->
|
||||
(ports.keys - prevPortKeys).forEach { key ->
|
||||
receiver.sendRpc(NewSerialDeviceResponse(device = ports.getValue(key).toSerialDevice()))
|
||||
}
|
||||
prevPortKeys = ports.keys.toSet()
|
||||
}
|
||||
.drop(1)
|
||||
.onEach { ports -> receiver.sendRpc(SerialDevicesResponse(devices = ports.map { it.toSerialDevice() })) }
|
||||
.launchIn(scope)
|
||||
|
||||
receiver.rpcDispatcher.on<SerialDevicesRequest> {
|
||||
receiver.sendRpc(
|
||||
SerialDevicesResponse(
|
||||
devices = serialServer.context.state.value.availablePorts.values
|
||||
.map { it.toSerialDevice() },
|
||||
),
|
||||
SerialDevicesResponse(devices = sortPorts(serialServer.context.state.value.ports.values).map { it.toSerialDevice() }),
|
||||
)
|
||||
}.launchIn(scope)
|
||||
|
||||
receiver.rpcDispatcher.on<OpenSerialRequest> { req ->
|
||||
val portLocation = if (req.auto) {
|
||||
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
|
||||
try {
|
||||
connection.context.state.collect { connState ->
|
||||
if (disconnected) return@collect
|
||||
|
||||
val device = serialServer.context.state.value.availablePorts[portLocation]?.toSerialDevice()
|
||||
connState.logLines.drop(lastSentCount).forEach { line ->
|
||||
receiver.sendRpc(SerialUpdateResponse(log = line + "\n", device = device))
|
||||
}
|
||||
lastSentCount = connState.logLines.size
|
||||
|
||||
if (!connState.connected) {
|
||||
disconnected = true
|
||||
activePortLocation = null
|
||||
receiver.sendRpc(SerialUpdateResponse(closed = true))
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
AppLogger.solarxr.error(e, "Error streaming serial log")
|
||||
}
|
||||
}
|
||||
val portLocation = req.port ?: return@on
|
||||
AppLogger.solarxr.info("Serial console requested on $portLocation")
|
||||
session?.cancel()
|
||||
activeConsole.value = null
|
||||
session = scope.launch { runConsoleSession(receiver, serialServer, portLocation, activeConsole) }
|
||||
}.launchIn(scope)
|
||||
|
||||
receiver.rpcDispatcher.on<CloseSerialRequest> {
|
||||
logSubscription?.cancel()
|
||||
logSubscription = null
|
||||
activePortLocation = null
|
||||
session?.cancel()
|
||||
session = null
|
||||
activeConsole.value = null
|
||||
}.launchIn(scope)
|
||||
|
||||
receiver.rpcDispatcher.on<SerialTrackerRebootRequest> {
|
||||
val portLocation = activePortLocation ?: return@on
|
||||
val c = serialServer.context.state.value.connections[portLocation]
|
||||
if (c is SerialConnection.Console) c.handle.writeCommand("REBOOT")
|
||||
activeConsole.value?.write("REBOOT")
|
||||
}.launchIn(scope)
|
||||
|
||||
receiver.rpcDispatcher.on<SerialTrackerGetInfoRequest> {
|
||||
val portLocation = activePortLocation ?: return@on
|
||||
val c = serialServer.context.state.value.connections[portLocation]
|
||||
if (c is SerialConnection.Console) c.handle.writeCommand("GET INFO")
|
||||
activeConsole.value?.write("GET INFO")
|
||||
}.launchIn(scope)
|
||||
|
||||
receiver.rpcDispatcher.on<SerialTrackerFactoryResetRequest> {
|
||||
val portLocation = activePortLocation ?: return@on
|
||||
val c = serialServer.context.state.value.connections[portLocation]
|
||||
if (c is SerialConnection.Console) c.handle.writeCommand("FRST")
|
||||
activeConsole.value?.write("FRST")
|
||||
}.launchIn(scope)
|
||||
|
||||
receiver.rpcDispatcher.on<SerialTrackerGetWifiScanRequest> {
|
||||
val portLocation = activePortLocation ?: return@on
|
||||
val c = serialServer.context.state.value.connections[portLocation]
|
||||
if (c is SerialConnection.Console) c.handle.writeCommand("GET WIFISCAN")
|
||||
activeConsole.value?.write("GET WIFISCAN")
|
||||
}.launchIn(scope)
|
||||
|
||||
receiver.rpcDispatcher.on<SerialTrackerCustomCommandRequest> { 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)
|
||||
activeConsole.value?.write(command)
|
||||
}.launchIn(scope)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user