fix: wait for server HELLO event before CONNECTED, add on-screen connection log
- CONNECTED now requires receiving server hello event (not just sending client hello) - 15s handshake timeout: if auth/hello never arrives, show timeout reason - On-screen log shows last 3 connection events (ws open, auth ok, hello, closed, timeout) - Generation guard covers early/duplicate auth and stale socket callbacks Version 0.2.2-m5-fix3
This commit is contained in:
@@ -26,6 +26,7 @@ import androidx.compose.ui.Alignment
|
|||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import com.gorios.lanvoice.audio.AecAvailability
|
import com.gorios.lanvoice.audio.AecAvailability
|
||||||
@@ -40,6 +41,7 @@ import com.gorios.lanvoice.expression.ExpressionUiState
|
|||||||
|
|
||||||
class MainActivity : ComponentActivity() {
|
class MainActivity : ComponentActivity() {
|
||||||
private var state by mutableStateOf(VoiceUiState())
|
private var state by mutableStateOf(VoiceUiState())
|
||||||
|
private var connectionLogs by mutableStateOf<List<String>>(emptyList())
|
||||||
private lateinit var session: VoiceSession
|
private lateinit var session: VoiceSession
|
||||||
private var pendingStart = false
|
private var pendingStart = false
|
||||||
private var expressionState by mutableStateOf(ExpressionUiState())
|
private var expressionState by mutableStateOf(ExpressionUiState())
|
||||||
@@ -64,9 +66,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
session = VoiceSession(
|
session = VoiceSession(
|
||||||
getString(R.string.voice_server_host), resources.getInteger(R.integer.voice_server_port),
|
getString(R.string.voice_server_host), resources.getInteger(R.integer.voice_server_port),
|
||||||
onState = { state = it },
|
onState = { state = it },
|
||||||
|
onConnectionLog = { connectionLogs = (connectionLogs + it).takeLast(3) },
|
||||||
)
|
)
|
||||||
expressions = ExpressionController(this, this) { expressionState = it }
|
expressions = ExpressionController(this, this) { expressionState = it }
|
||||||
setContent { Home(state, ::toggleVoice, session::interrupt, expressionState, ::toggleExpressions) }
|
setContent { Home(state, ::toggleVoice, session::interrupt, expressionState, ::toggleExpressions, connectionLogs) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun toggleExpressions() {
|
private fun toggleExpressions() {
|
||||||
@@ -97,6 +100,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
override fun onStart() {
|
override fun onStart() {
|
||||||
super.onStart()
|
super.onStart()
|
||||||
inForeground = true
|
inForeground = true
|
||||||
|
connectionLogs = emptyList()
|
||||||
session.foreground()
|
session.foreground()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,6 +124,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
fun Home(
|
fun Home(
|
||||||
state: VoiceUiState, onToggleVoice: () -> Unit, onInterrupt: () -> Unit,
|
state: VoiceUiState, onToggleVoice: () -> Unit, onInterrupt: () -> Unit,
|
||||||
expressionState: ExpressionUiState, onToggleExpressions: () -> Unit,
|
expressionState: ExpressionUiState, onToggleExpressions: () -> Unit,
|
||||||
|
connectionLogs: List<String> = emptyList(),
|
||||||
) {
|
) {
|
||||||
val gold = Color(0xFFE8C884)
|
val gold = Color(0xFFE8C884)
|
||||||
val muted = Color(0xFF9CA3AF)
|
val muted = Color(0xFF9CA3AF)
|
||||||
@@ -146,6 +151,14 @@ fun Home(
|
|||||||
modifier = Modifier.background(Color(0xFF242433), RoundedCornerShape(50))
|
modifier = Modifier.background(Color(0xFF242433), RoundedCornerShape(50))
|
||||||
.padding(horizontal = 20.dp, vertical = 10.dp)
|
.padding(horizontal = 20.dp, vertical = 10.dp)
|
||||||
)
|
)
|
||||||
|
if (connectionLogs.isNotEmpty()) {
|
||||||
|
Text(
|
||||||
|
text = connectionLogs.takeLast(3).joinToString("\n"),
|
||||||
|
color = muted, fontSize = 12.sp, textAlign = TextAlign.Center,
|
||||||
|
maxLines = 3, softWrap = false, overflow = TextOverflow.Ellipsis,
|
||||||
|
modifier = Modifier.padding(top = 6.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
ExpressionControls(expressionState, onToggleExpressions)
|
ExpressionControls(expressionState, onToggleExpressions)
|
||||||
}
|
}
|
||||||
Column(
|
Column(
|
||||||
|
|||||||
@@ -20,7 +20,10 @@ data class VoiceUiState(
|
|||||||
)
|
)
|
||||||
|
|
||||||
/** Main-thread coordinator; both audio workers add their own epochs to the socket's fence. */
|
/** Main-thread coordinator; both audio workers add their own epochs to the socket's fence. */
|
||||||
class VoiceSession(host: String, port: Int, private val onState: (VoiceUiState) -> Unit) {
|
class VoiceSession(
|
||||||
|
host: String, port: Int, private val onState: (VoiceUiState) -> Unit,
|
||||||
|
onConnectionLog: (String) -> Unit = {},
|
||||||
|
) {
|
||||||
private val main = Handler(Looper.getMainLooper())
|
private val main = Handler(Looper.getMainLooper())
|
||||||
private var state = VoiceUiState()
|
private var state = VoiceUiState()
|
||||||
private var foreground = false
|
private var foreground = false
|
||||||
@@ -56,6 +59,7 @@ class VoiceSession(host: String, port: Int, private val onState: (VoiceUiState)
|
|||||||
onEvent = ::onEvent,
|
onEvent = ::onEvent,
|
||||||
onFrame = ::onFrame,
|
onFrame = ::onFrame,
|
||||||
onProtocolError = { Log.w(TAG, it) },
|
onProtocolError = { Log.w(TAG, it) },
|
||||||
|
onConnectionLog = onConnectionLog,
|
||||||
)
|
)
|
||||||
|
|
||||||
fun foreground() {
|
fun foreground() {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import okhttp3.Response
|
|||||||
import okhttp3.WebSocket
|
import okhttp3.WebSocket
|
||||||
import okhttp3.WebSocketListener
|
import okhttp3.WebSocketListener
|
||||||
import okio.ByteString
|
import okio.ByteString
|
||||||
|
import java.net.SocketTimeoutException
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
enum class ConnectionStatus { CONNECTED, DISCONNECTED, BUSY }
|
enum class ConnectionStatus { CONNECTED, DISCONNECTED, BUSY }
|
||||||
@@ -25,6 +26,7 @@ class DialogueClient(
|
|||||||
private val onEvent: (ServerEvent) -> Unit = {},
|
private val onEvent: (ServerEvent) -> Unit = {},
|
||||||
private val onFrame: (DownlinkFrame) -> Unit = {},
|
private val onFrame: (DownlinkFrame) -> Unit = {},
|
||||||
private val onProtocolError: (String) -> Unit = {},
|
private val onProtocolError: (String) -> Unit = {},
|
||||||
|
private val onConnectionLog: (String) -> Unit = {},
|
||||||
) {
|
) {
|
||||||
private val main = Handler(Looper.getMainLooper())
|
private val main = Handler(Looper.getMainLooper())
|
||||||
private val endpoint = HttpUrl.Builder()
|
private val endpoint = HttpUrl.Builder()
|
||||||
@@ -47,26 +49,43 @@ class DialogueClient(
|
|||||||
private var released = false
|
private var released = false
|
||||||
private var ready = false
|
private var ready = false
|
||||||
private var authReceived = false
|
private var authReceived = false
|
||||||
|
private var helloSent = false
|
||||||
|
private var handshakeTimeout: Runnable? = null
|
||||||
|
|
||||||
fun connect() {
|
fun connect() {
|
||||||
checkMainThread()
|
checkMainThread()
|
||||||
check(!released) { "DialogueClient has been released" }
|
check(!released) { "DialogueClient has been released" }
|
||||||
generation++
|
generation++
|
||||||
|
cancelHandshakeTimeout()
|
||||||
ready = false
|
ready = false
|
||||||
authReceived = false
|
authReceived = false
|
||||||
|
helloSent = false
|
||||||
socket?.cancel()
|
socket?.cancel()
|
||||||
socket = null
|
socket = null
|
||||||
onStatus(ConnectionStatus.DISCONNECTED)
|
onStatus(ConnectionStatus.DISCONNECTED)
|
||||||
socket = client.newWebSocket(request, listener(generation))
|
onConnectionLog("ws connecting")
|
||||||
|
val attempt = generation
|
||||||
|
val current = client.newWebSocket(request, listener(attempt))
|
||||||
|
socket = current
|
||||||
|
// onOpen is not a prerequisite for AUTH handling. All callbacks are queued on main,
|
||||||
|
// so even an early AUTH sees the assigned socket and can send hello exactly once.
|
||||||
|
handshakeTimeout = Runnable {
|
||||||
|
if (generation == attempt && socket === current && !released && !ready) {
|
||||||
|
onConnectionLog("连接超时:" + if (helloSent) "等待 hello" else "等待 auth / WS")
|
||||||
|
finish(current, ConnectionStatus.DISCONNECTED)
|
||||||
|
}
|
||||||
|
}.also { main.postDelayed(it, 15_000L) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun disconnect() {
|
fun disconnect() {
|
||||||
checkMainThread()
|
checkMainThread()
|
||||||
generation++ // Invalidate before cancellation can trigger onFailure.
|
generation++ // Invalidate before cancellation can trigger onFailure.
|
||||||
|
cancelHandshakeTimeout()
|
||||||
ready = false
|
ready = false
|
||||||
val previous = socket
|
val previous = socket
|
||||||
socket = null
|
socket = null
|
||||||
previous?.cancel()
|
previous?.cancel()
|
||||||
|
if (previous != null) onConnectionLog("ws disconnected")
|
||||||
onStatus(ConnectionStatus.DISCONNECTED)
|
onStatus(ConnectionStatus.DISCONNECTED)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,6 +111,7 @@ class DialogueClient(
|
|||||||
// Bound microphone latency rather than silently buffering many seconds of stale speech.
|
// Bound microphone latency rather than silently buffering many seconds of stale speech.
|
||||||
if (current.queueSize() > 64 * 1024 ||
|
if (current.queueSize() > 64 * 1024 ||
|
||||||
!current.send(ByteString.of(*DialogueProtocol.uplink(pcm16, turnId, sequence)))) {
|
!current.send(ByteString.of(*DialogueProtocol.uplink(pcm16, turnId, sequence)))) {
|
||||||
|
onConnectionLog("ws audio send failed")
|
||||||
finish(current, ConnectionStatus.DISCONNECTED)
|
finish(current, ConnectionStatus.DISCONNECTED)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -103,33 +123,59 @@ class DialogueClient(
|
|||||||
val current = socket ?: return false
|
val current = socket ?: return false
|
||||||
if (!ready || released) return false
|
if (!ready || released) return false
|
||||||
if (current.send(text)) return true
|
if (current.send(text)) return true
|
||||||
|
onConnectionLog("ws send failed")
|
||||||
finish(current, ConnectionStatus.DISCONNECTED)
|
finish(current, ConnectionStatus.DISCONNECTED)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun listener(attempt: Long) = object : WebSocketListener() {
|
private fun listener(attempt: Long) = object : WebSocketListener() {
|
||||||
override fun onOpen(webSocket: WebSocket, response: Response) = dispatch(attempt, webSocket) {
|
override fun onOpen(webSocket: WebSocket, response: Response) = dispatch(attempt, webSocket) {
|
||||||
// Server sends auth-ok first (LAN direct/guest cookie/admin bearer), then expects hello.
|
onConnectionLog("ws open")
|
||||||
// Do not send hello here; wait for the auth event in onMessage.
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onMessage(webSocket: WebSocket, text: String) = dispatch(attempt, webSocket) {
|
override fun onMessage(webSocket: WebSocket, text: String) = dispatch(attempt, webSocket) {
|
||||||
val event = try {
|
val event = try {
|
||||||
DialogueProtocol.parseEvent(text)
|
DialogueProtocol.parseEvent(text)
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
|
if (!ready) onConnectionLog("握手事件 JSON 无效")
|
||||||
onProtocolError(error.message ?: "Invalid JSON event")
|
onProtocolError(error.message ?: "Invalid JSON event")
|
||||||
return@dispatch
|
return@dispatch
|
||||||
}
|
}
|
||||||
if (!authReceived && event.kind == EventKind.AUTH) {
|
if (event.kind == EventKind.AUTH) {
|
||||||
|
if (!event.payload.optBoolean("ok", true) ||
|
||||||
|
!event.payload.optBoolean("success", true) ||
|
||||||
|
event.type in setOf("auth.error", "auth.failed") ||
|
||||||
|
event.payload.optString("status") in setOf("error", "failed", "denied")) {
|
||||||
|
onConnectionLog("auth failed")
|
||||||
|
finish(webSocket, ConnectionStatus.DISCONNECTED)
|
||||||
|
return@dispatch
|
||||||
|
}
|
||||||
|
if (authReceived) return@dispatch
|
||||||
authReceived = true
|
authReceived = true
|
||||||
|
onConnectionLog("auth ok")
|
||||||
if (webSocket.send(DialogueProtocol.hello())) {
|
if (webSocket.send(DialogueProtocol.hello())) {
|
||||||
ready = true
|
helloSent = true
|
||||||
onStatus(ConnectionStatus.CONNECTED)
|
onConnectionLog("hello sent")
|
||||||
} else {
|
} else {
|
||||||
|
onConnectionLog("hello send failed")
|
||||||
finish(webSocket, ConnectionStatus.DISCONNECTED)
|
finish(webSocket, ConnectionStatus.DISCONNECTED)
|
||||||
}
|
}
|
||||||
return@dispatch
|
return@dispatch
|
||||||
}
|
}
|
||||||
|
if (event.kind == EventKind.HELLO && !ready) {
|
||||||
|
if (!authReceived || !helloSent) {
|
||||||
|
onConnectionLog("hello received before auth")
|
||||||
|
return@dispatch
|
||||||
|
}
|
||||||
|
ready = true
|
||||||
|
cancelHandshakeTimeout()
|
||||||
|
onConnectionLog("hello received")
|
||||||
|
onStatus(ConnectionStatus.CONNECTED)
|
||||||
|
}
|
||||||
|
if (event.kind == EventKind.ERROR && !ready) {
|
||||||
|
onConnectionLog("握手收到 error")
|
||||||
|
finish(webSocket, ConnectionStatus.DISCONNECTED)
|
||||||
|
}
|
||||||
onEvent(event)
|
onEvent(event)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,14 +190,22 @@ class DialogueClient(
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) = dispatch(attempt, webSocket) {
|
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) = dispatch(attempt, webSocket) {
|
||||||
|
// finish invalidates onClosed, so record the close code here as well.
|
||||||
|
onConnectionLog("ws closed: $code")
|
||||||
finish(webSocket, statusFor(code))
|
finish(webSocket, statusFor(code))
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = dispatch(attempt, webSocket) {
|
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = dispatch(attempt, webSocket) {
|
||||||
|
onConnectionLog("ws closed: $code")
|
||||||
finish(webSocket, statusFor(code))
|
finish(webSocket, statusFor(code))
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = dispatch(attempt, webSocket) {
|
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = dispatch(attempt, webSocket) {
|
||||||
|
onConnectionLog(when {
|
||||||
|
response != null -> "ws failure: HTTP ${response.code}"
|
||||||
|
t is SocketTimeoutException -> "连接超时"
|
||||||
|
else -> "ws failure: ${t.javaClass.simpleName}"
|
||||||
|
})
|
||||||
finish(webSocket, if (response?.code == 403) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED)
|
finish(webSocket, if (response?.code == 403) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -164,12 +218,18 @@ class DialogueClient(
|
|||||||
|
|
||||||
private fun finish(webSocket: WebSocket, status: ConnectionStatus) {
|
private fun finish(webSocket: WebSocket, status: ConnectionStatus) {
|
||||||
// Invalidate terminal callbacks so a later failure cannot overwrite a 1013 busy status.
|
// Invalidate terminal callbacks so a later failure cannot overwrite a 1013 busy status.
|
||||||
|
cancelHandshakeTimeout()
|
||||||
socket = null
|
socket = null
|
||||||
ready = false
|
ready = false
|
||||||
webSocket.cancel()
|
webSocket.cancel()
|
||||||
onStatus(status)
|
onStatus(status)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun cancelHandshakeTimeout() {
|
||||||
|
handshakeTimeout?.let { main.removeCallbacks(it) }
|
||||||
|
handshakeTimeout = null
|
||||||
|
}
|
||||||
|
|
||||||
private fun statusFor(code: Int) =
|
private fun statusFor(code: Int) =
|
||||||
if (code == 1013) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED
|
if (code == 1013) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user