fix: abort listen_start no longer blocks new turn, debug log HTTPS fix
- ABORT with reason=listen_start no longer marks new turn as blocked - ABORT ignored when connection lost or voice not active - finish() logs stack trace to Logcat, truncated summary to screen/remote - DebugLogUpload endpoint fixed to HTTPS (was cleartext HTTP to HTTPS port) - Granular logging: onEvent entry, acceptTurn details, ABORT/LISTEN decisions, startCapture result, onConnection transitions, finish() caller Version 0.2.7-m5-fix8
This commit is contained in:
+2
-2
@@ -45,8 +45,8 @@ android {
|
|||||||
applicationId 'com.gorios.lanvoice'
|
applicationId 'com.gorios.lanvoice'
|
||||||
minSdk 26
|
minSdk 26
|
||||||
targetSdk 34
|
targetSdk 34
|
||||||
versionCode 2
|
versionCode 3
|
||||||
versionName '0.2.5'
|
versionName '0.2.7'
|
||||||
ndk { abiFilters 'arm64-v8a' }
|
ndk { abiFilters 'arm64-v8a' }
|
||||||
}
|
}
|
||||||
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
||||||
|
|||||||
@@ -25,11 +25,14 @@ class AudioCapture {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** The caller must obtain RECORD_AUDIO permission before starting. Callbacks run off main. */
|
/** The caller must obtain RECORD_AUDIO permission before starting. Callbacks run off main. */
|
||||||
fun start(onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit) {
|
fun start(
|
||||||
|
onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit,
|
||||||
|
onDiagnostic: (String) -> Unit = {},
|
||||||
|
) {
|
||||||
stop()
|
stop()
|
||||||
val run = Run()
|
val run = Run()
|
||||||
synchronized(lock) { current = run }
|
synchronized(lock) { current = run }
|
||||||
Thread({ record(run, onFrame, onError) }, "lan-voice-capture").apply {
|
Thread({ record(run, onFrame, onError, onDiagnostic) }, "lan-voice-capture").apply {
|
||||||
isDaemon = true
|
isDaemon = true
|
||||||
start()
|
start()
|
||||||
}
|
}
|
||||||
@@ -45,10 +48,15 @@ class AudioCapture {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun record(run: Run, onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit) {
|
private fun record(
|
||||||
|
run: Run, onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit,
|
||||||
|
onDiagnostic: (String) -> Unit,
|
||||||
|
) {
|
||||||
var recorder: AudioRecord? = null
|
var recorder: AudioRecord? = null
|
||||||
var aec: AcousticEchoCanceler? = null
|
var aec: AcousticEchoCanceler? = null
|
||||||
|
var stage = "initialization"
|
||||||
try {
|
try {
|
||||||
|
onDiagnostic("AudioRecord initialization started")
|
||||||
Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO)
|
Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO)
|
||||||
val minimum = AudioRecord.getMinBufferSize(
|
val minimum = AudioRecord.getMinBufferSize(
|
||||||
16_000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT
|
16_000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT
|
||||||
@@ -61,6 +69,7 @@ class AudioCapture {
|
|||||||
)
|
)
|
||||||
recorder = device
|
recorder = device
|
||||||
check(device.state == AudioRecord.STATE_INITIALIZED) { "AudioRecord initialization failed" }
|
check(device.state == AudioRecord.STATE_INITIALIZED) { "AudioRecord initialization failed" }
|
||||||
|
onDiagnostic("AudioRecord initialization ok")
|
||||||
// Availability is reported separately; creating/enabling an effect is best effort.
|
// Availability is reported separately; creating/enabling an effect is best effort.
|
||||||
if (aecAvailability() == AecAvailability.AVAILABLE) {
|
if (aecAvailability() == AecAvailability.AVAILABLE) {
|
||||||
try {
|
try {
|
||||||
@@ -71,9 +80,12 @@ class AudioCapture {
|
|||||||
synchronized(lock) {
|
synchronized(lock) {
|
||||||
if (!run.active || current !== run) return
|
if (!run.active || current !== run) return
|
||||||
run.recorder = device
|
run.recorder = device
|
||||||
|
stage = "startRecording"
|
||||||
device.startRecording()
|
device.startRecording()
|
||||||
check(device.recordingState == AudioRecord.RECORDSTATE_RECORDING) { "Recording did not start" }
|
check(device.recordingState == AudioRecord.RECORDSTATE_RECORDING) { "Recording did not start" }
|
||||||
}
|
}
|
||||||
|
onDiagnostic("AudioRecord startRecording ok")
|
||||||
|
stage = "read"
|
||||||
val frame = ByteArray(FRAME_BYTES)
|
val frame = ByteArray(FRAME_BYTES)
|
||||||
var filled = 0
|
var filled = 0
|
||||||
while (run.active) {
|
while (run.active) {
|
||||||
@@ -91,7 +103,10 @@ class AudioCapture {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
if (run.active) onError(error)
|
if (run.active) {
|
||||||
|
onDiagnostic("AudioRecord $stage failed: ${error.javaClass.simpleName}")
|
||||||
|
onError(error)
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
synchronized(lock) {
|
synchronized(lock) {
|
||||||
run.active = false
|
run.active = false
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ 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(
|
class VoiceSession(
|
||||||
host: String, port: Int, private val onState: (VoiceUiState) -> Unit,
|
host: String, port: Int, private val onState: (VoiceUiState) -> Unit,
|
||||||
onConnectionLog: (String) -> Unit = {},
|
private val onConnectionLog: (String) -> Unit = {},
|
||||||
) {
|
) {
|
||||||
private val main = Handler(Looper.getMainLooper())
|
private val main = Handler(Looper.getMainLooper())
|
||||||
private var state = VoiceUiState()
|
private var state = VoiceUiState()
|
||||||
@@ -57,7 +57,8 @@ class VoiceSession(
|
|||||||
)
|
)
|
||||||
private val dialogue: DialogueClient = DialogueClient(
|
private val dialogue: DialogueClient = DialogueClient(
|
||||||
host, port,
|
host, port,
|
||||||
onStatus = ::onConnection,
|
onStatus = {},
|
||||||
|
onStatusReason = ::onConnection,
|
||||||
onEvent = ::onEvent,
|
onEvent = ::onEvent,
|
||||||
onFrame = ::onFrame,
|
onFrame = ::onFrame,
|
||||||
onProtocolError = { Log.w(TAG, it) },
|
onProtocolError = { Log.w(TAG, it) },
|
||||||
@@ -92,9 +93,9 @@ class VoiceSession(
|
|||||||
// but reuse the authorized WS when it returns. Bound retention if the user leaves.
|
// but reuse the authorized WS when it returns. Bound retention if the user leaves.
|
||||||
backgroundTimeout = Runnable {
|
backgroundTimeout = Runnable {
|
||||||
backgroundTimeout = null
|
backgroundTimeout = null
|
||||||
if (!foreground && !released) dialogue.disconnect()
|
if (!foreground && !released) dialogue.disconnect("permission_background_timeout")
|
||||||
}.also { main.postDelayed(it, 30_000L) }
|
}.also { main.postDelayed(it, 30_000L) }
|
||||||
} else dialogue.disconnect()
|
} else dialogue.disconnect("session_background")
|
||||||
}
|
}
|
||||||
|
|
||||||
fun release() {
|
fun release() {
|
||||||
@@ -145,7 +146,8 @@ class VoiceSession(
|
|||||||
update(state.copy(guidance = "麦克风权限未授予,请允许录音;若不再弹出申请,可在系统应用权限中开启。"))
|
update(state.copy(guidance = "麦克风权限未授予,请允许录音;若不再弹出申请,可在系统应用权限中开启。"))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun onConnection(connection: ConnectionStatus) {
|
private fun onConnection(connection: ConnectionStatus, reason: String) {
|
||||||
|
diagnostic("connection ${state.connection.name} -> ${connection.name} reason=$reason", "connect")
|
||||||
if (connection != ConnectionStatus.CONNECTED) {
|
if (connection != ConnectionStatus.CONNECTED) {
|
||||||
stopCapture()
|
stopCapture()
|
||||||
playback.interrupt()
|
playback.interrupt()
|
||||||
@@ -159,10 +161,13 @@ class VoiceSession(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun startCapture() {
|
private fun startCapture() {
|
||||||
if (!isActive() || capturing) return
|
val active = isActive()
|
||||||
|
diagnostic("startCapture active=$active capturing=$capturing")
|
||||||
|
if (!active || capturing) return
|
||||||
capturing = true
|
capturing = true
|
||||||
val epoch = ++captureEpoch
|
val epoch = ++captureEpoch
|
||||||
DebugLogUpload.log("audio", "capture start")
|
diagnostic("capture start epoch=$epoch")
|
||||||
|
try {
|
||||||
capture.start(
|
capture.start(
|
||||||
onFrame = { pcm ->
|
onFrame = { pcm ->
|
||||||
main.post {
|
main.post {
|
||||||
@@ -178,7 +183,15 @@ class VoiceSession(
|
|||||||
if (epoch == captureEpoch && isActive()) failAudio("无法录音,请检查麦克风权限后重新开始", error)
|
if (epoch == captureEpoch && isActive()) failAudio("无法录音,请检查麦克风权限后重新开始", error)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
onDiagnostic = { message ->
|
||||||
|
main.post {
|
||||||
|
if (epoch == captureEpoch && capturing && !released) diagnostic(message)
|
||||||
|
}
|
||||||
|
},
|
||||||
)
|
)
|
||||||
|
} catch (error: Exception) {
|
||||||
|
failAudio("无法启动录音,请检查麦克风权限后重新开始", error)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun stopCapture() {
|
private fun stopCapture() {
|
||||||
@@ -189,10 +202,22 @@ class VoiceSession(
|
|||||||
|
|
||||||
private fun onEvent(event: ServerEvent) {
|
private fun onEvent(event: ServerEvent) {
|
||||||
val turn = (event.payload.opt("turn_id") as? Number)?.toLong()
|
val turn = (event.payload.opt("turn_id") as? Number)?.toLong()
|
||||||
|
diagnostic("onEvent kind=${event.kind.name} turn_id=$turn")
|
||||||
|
if (released || state.connection != ConnectionStatus.CONNECTED) {
|
||||||
|
diagnostic("event ignored: connection=${state.connection.name} released=$released")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (event.kind == EventKind.ABORT && !isActive()) {
|
||||||
|
diagnostic("ABORT ignored active=false blockedTurn=$blockedTurn")
|
||||||
|
return
|
||||||
|
}
|
||||||
if (turn != null && !acceptTurn(turn)) return
|
if (turn != null && !acceptTurn(turn)) return
|
||||||
val action = event.payload.optString("state", "").ifBlank { event.type.substringAfter('.', "") }
|
val action = event.payload.optString("state", "").ifBlank { event.type.substringAfter('.', "") }
|
||||||
when (event.kind) {
|
when (event.kind) {
|
||||||
EventKind.LISTEN -> if (isActive()) {
|
EventKind.LISTEN -> {
|
||||||
|
val active = isActive()
|
||||||
|
diagnostic("LISTEN action=${if (action in setOf("start", "stop")) action else "other"} active=$active blockedTurn=$blockedTurn")
|
||||||
|
if (!active) return
|
||||||
when (action) {
|
when (action) {
|
||||||
"start" -> {
|
"start" -> {
|
||||||
update(state.copy(phase = VoicePhase.LISTENING))
|
update(state.copy(phase = VoicePhase.LISTENING))
|
||||||
@@ -221,7 +246,11 @@ class VoiceSession(
|
|||||||
if (action in setOf("stop", "done", "end")) playback.endTurn(currentTurn)
|
if (action in setOf("stop", "done", "end")) playback.endTurn(currentTurn)
|
||||||
}
|
}
|
||||||
EventKind.ABORT -> {
|
EventKind.ABORT -> {
|
||||||
blockedTurn = currentTurn
|
// listen_start aborts the previous reply while announcing the NEW turn.
|
||||||
|
// The server's following LISTEN start and TTS belong to that new turn.
|
||||||
|
val listenReset = event.payload.optString("reason") == "listen_start"
|
||||||
|
blockedTurn = if (listenReset) null else currentTurn
|
||||||
|
diagnostic("ABORT blockedTurn=$blockedTurn active=${isActive()} listenReset=$listenReset")
|
||||||
playback.interrupt()
|
playback.interrupt()
|
||||||
if (isActive()) {
|
if (isActive()) {
|
||||||
update(state.copy(phase = VoicePhase.LISTENING))
|
update(state.copy(phase = VoicePhase.LISTENING))
|
||||||
@@ -237,17 +266,22 @@ class VoiceSession(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun onFrame(frame: DownlinkFrame) {
|
private fun onFrame(frame: DownlinkFrame) {
|
||||||
if (!isActive() || !acceptTurn(frame.turnId) || blockedTurn == frame.turnId) return
|
// Avoid uploading the same acceptTurn decision for every 20 ms PCM frame.
|
||||||
|
if (!isActive() || !acceptTurn(frame.turnId, logDecision = !hasTurn || frame.turnId != currentTurn) ||
|
||||||
|
blockedTurn == frame.turnId) return
|
||||||
update(state.copy(phase = VoicePhase.ANSWERING))
|
update(state.copy(phase = VoicePhase.ANSWERING))
|
||||||
if (!playback.enqueue(frame)) {
|
if (!playback.enqueue(frame)) {
|
||||||
failAudio("播放中断,请重新开始语音对话", IllegalStateException("Playback queue rejected frame"))
|
failAudio("播放中断,请重新开始语音对话", IllegalStateException("Playback queue rejected frame"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun acceptTurn(id: Long): Boolean {
|
private fun acceptTurn(id: Long, logDecision: Boolean = true): Boolean {
|
||||||
if (id !in 0..UINT32_MASK) return false
|
val before = "id=$id hasTurn=$hasTurn currentTurn=$currentTurn blockedTurn=$blockedTurn retired=${retiredTurns.size}"
|
||||||
|
if (id !in 0..UINT32_MASK || id in retiredTurns) {
|
||||||
|
if (logDecision) diagnostic("acceptTurn $before accepted=false")
|
||||||
|
return false
|
||||||
|
}
|
||||||
// IDs identify turns; do not assume the server allocates them in numeric order.
|
// IDs identify turns; do not assume the server allocates them in numeric order.
|
||||||
if (id in retiredTurns) return false
|
|
||||||
if (!hasTurn || id != currentTurn) {
|
if (!hasTurn || id != currentTurn) {
|
||||||
if (hasTurn) retiredTurns.add(currentTurn)
|
if (hasTurn) retiredTurns.add(currentTurn)
|
||||||
playback.interrupt()
|
playback.interrupt()
|
||||||
@@ -256,17 +290,22 @@ class VoiceSession(
|
|||||||
sequence = 0
|
sequence = 0
|
||||||
if (blockedTurn != id) blockedTurn = null
|
if (blockedTurn != id) blockedTurn = null
|
||||||
}
|
}
|
||||||
|
if (logDecision) diagnostic("acceptTurn $before accepted=true nextTurn=$currentTurn nextBlocked=$blockedTurn retiredNow=${retiredTurns.size}")
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun failAudio(message: String, error: Exception) {
|
private fun failAudio(message: String, error: Exception) {
|
||||||
DebugLogUpload.log("audio", "audio failed: ${error.javaClass.simpleName}")
|
diagnostic("audio failed: ${error.javaClass.simpleName} connection=${state.connection.name}", "error")
|
||||||
Log.w(TAG, message, error)
|
Log.w(TAG, message, error)
|
||||||
stopVoice()
|
stopVoice()
|
||||||
update(state.copy(guidance = message))
|
update(state.copy(guidance = message))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun playbackIsCurrent(turn: Long, epoch: Long): Boolean = playback.isCurrent(turn, epoch)
|
private fun playbackIsCurrent(turn: Long, epoch: Long): Boolean = playback.isCurrent(turn, epoch)
|
||||||
|
private fun diagnostic(message: String, tag: String = "audio") {
|
||||||
|
DebugLogUpload.log(tag, message)
|
||||||
|
onConnectionLog(message)
|
||||||
|
}
|
||||||
private fun playbackIsCurrent(epoch: Long): Boolean = playback.isCurrent(epoch)
|
private fun playbackIsCurrent(epoch: Long): Boolean = playback.isCurrent(epoch)
|
||||||
private fun isActive() = !released && foreground && state.voiceActive && state.connection == ConnectionStatus.CONNECTED
|
private fun isActive() = !released && foreground && state.voiceActive && state.connection == ConnectionStatus.CONNECTED
|
||||||
private fun update(next: VoiceUiState) { state = next; onState(next) }
|
private fun update(next: VoiceUiState) { state = next; onState(next) }
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ import java.util.concurrent.atomic.AtomicInteger
|
|||||||
|
|
||||||
/** Process-wide, memory-only LAN diagnostics. Callers supply metadata, never payloads. */
|
/** Process-wide, memory-only LAN diagnostics. Callers supply metadata, never payloads. */
|
||||||
object DebugLogUpload {
|
object DebugLogUpload {
|
||||||
private const val ENDPOINT = "http://192.168.31.61:5011/debug/log"
|
private const val ENDPOINT = "https://192.168.31.61:5011/debug/log"
|
||||||
private const val MAX_PENDING = 16
|
private const val MAX_PENDING = 16
|
||||||
private val tags = setOf("connect", "ws", "auth", "audio", "error")
|
private val tags = setOf("connect", "ws", "auth", "audio", "error")
|
||||||
private val pending = AtomicInteger()
|
private val pending = AtomicInteger()
|
||||||
@@ -30,11 +30,11 @@ object DebugLogUpload {
|
|||||||
@Volatile var lastResult: String = "等待发送"
|
@Volatile var lastResult: String = "等待发送"
|
||||||
private set
|
private set
|
||||||
private val json = "application/json; charset=utf-8".toMediaType()
|
private val json = "application/json; charset=utf-8".toMediaType()
|
||||||
// Build independently, never newBuilder() from the voice client. HTTP-only avoids
|
// Build independently from voice. This gateway endpoint uses HTTPS; Android applies
|
||||||
// initializing TLS for the diagnostic channel whose purpose includes TLS failures.
|
// the same packaged certificate trust policy, with normal hostname verification.
|
||||||
private val client by lazy {
|
private val client by lazy {
|
||||||
OkHttpClient.Builder()
|
OkHttpClient.Builder()
|
||||||
.connectionSpecs(listOf(ConnectionSpec.CLEARTEXT))
|
.connectionSpecs(listOf(ConnectionSpec.MODERN_TLS))
|
||||||
.proxy(Proxy.NO_PROXY) // Direct LAN request, independent of any system HTTP proxy.
|
.proxy(Proxy.NO_PROXY) // Direct LAN request, independent of any system HTTP proxy.
|
||||||
.connectionPool(ConnectionPool(2, 30, TimeUnit.SECONDS))
|
.connectionPool(ConnectionPool(2, 30, TimeUnit.SECONDS))
|
||||||
.dispatcher(Dispatcher().apply { maxRequests = 2; maxRequestsPerHost = 2 })
|
.dispatcher(Dispatcher().apply { maxRequests = 2; maxRequestsPerHost = 2 })
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.gorios.lanvoice.net
|
|||||||
|
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
|
import android.util.Log
|
||||||
import okhttp3.Call
|
import okhttp3.Call
|
||||||
import okhttp3.Callback
|
import okhttp3.Callback
|
||||||
import okhttp3.EventListener
|
import okhttp3.EventListener
|
||||||
@@ -40,6 +41,7 @@ class DialogueClient(
|
|||||||
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 onConnectionLog: (String) -> Unit = {},
|
||||||
|
private val onStatusReason: (ConnectionStatus, String) -> Unit = { _, _ -> },
|
||||||
) {
|
) {
|
||||||
private val main = Handler(Looper.getMainLooper())
|
private val main = Handler(Looper.getMainLooper())
|
||||||
private val endpoint = HttpUrl.Builder()
|
private val endpoint = HttpUrl.Builder()
|
||||||
@@ -95,7 +97,7 @@ class DialogueClient(
|
|||||||
socket?.cancel()
|
socket?.cancel()
|
||||||
socket = null
|
socket = null
|
||||||
val attempt = generation
|
val attempt = generation
|
||||||
updateStatus(ConnectionStatus.CONNECTING)
|
updateStatus(ConnectionStatus.CONNECTING, "connect_start")
|
||||||
connectionLog("health checking #$attempt", "connect")
|
connectionLog("health checking #$attempt", "connect")
|
||||||
// Arm before submitting the request; synchronous setup failures are terminal too.
|
// Arm before submitting the request; synchronous setup failures are terminal too.
|
||||||
handshakeTimeout = Runnable {
|
handshakeTimeout = Runnable {
|
||||||
@@ -107,7 +109,7 @@ class DialogueClient(
|
|||||||
else -> "等待 WS(TCP/TLS/HTTP)"
|
else -> "等待 WS(TCP/TLS/HTTP)"
|
||||||
}
|
}
|
||||||
connectionLog("连接超时,请检查网络 · $phase", "error")
|
connectionLog("连接超时,请检查网络 · $phase", "error")
|
||||||
finish(socket, ConnectionStatus.DISCONNECTED)
|
finish(socket, ConnectionStatus.DISCONNECTED, "handshake_timeout")
|
||||||
}
|
}
|
||||||
}.also { main.postDelayed(it, 15_000L) }
|
}.also { main.postDelayed(it, 15_000L) }
|
||||||
startHealthProbe(attempt)
|
startHealthProbe(attempt)
|
||||||
@@ -144,7 +146,7 @@ class DialogueClient(
|
|||||||
current.enqueue(object : Callback {
|
current.enqueue(object : Callback {
|
||||||
override fun onFailure(call: Call, error: IOException) = dispatchHealth(attempt, call) {
|
override fun onFailure(call: Call, error: IOException) = dispatchHealth(attempt, call) {
|
||||||
connectionLog("health failed: ${failureSummary(error)}", "error")
|
connectionLog("health failed: ${failureSummary(error)}", "error")
|
||||||
finish(socket, ConnectionStatus.DISCONNECTED)
|
finish(socket, ConnectionStatus.DISCONNECTED, "health_failure:${failureSummary(error)}")
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onResponse(call: Call, response: Response) {
|
override fun onResponse(call: Call, response: Response) {
|
||||||
@@ -161,7 +163,7 @@ class DialogueClient(
|
|||||||
connectionLog("health submitted #$attempt", "connect")
|
connectionLog("health submitted #$attempt", "connect")
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
connectionLog("health setup failed: ${failureSummary(error)}", "error")
|
connectionLog("health setup failed: ${failureSummary(error)}", "error")
|
||||||
finish(socket, ConnectionStatus.DISCONNECTED)
|
finish(socket, ConnectionStatus.DISCONNECTED, "health_setup_failure:${failureSummary(error)}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,11 +176,11 @@ class DialogueClient(
|
|||||||
connectionLog("ws submitted #$attempt")
|
connectionLog("ws submitted #$attempt")
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
connectionLog("ws setup failed: ${failureSummary(error)}", "error")
|
connectionLog("ws setup failed: ${failureSummary(error)}", "error")
|
||||||
finish(socket, ConnectionStatus.DISCONNECTED)
|
finish(socket, ConnectionStatus.DISCONNECTED, "ws_setup_failure:${failureSummary(error)}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun disconnect() {
|
fun disconnect(reason: String = "client_disconnect") {
|
||||||
checkMainThread()
|
checkMainThread()
|
||||||
generation++ // Invalidate before cancellation can trigger onFailure.
|
generation++ // Invalidate before cancellation can trigger onFailure.
|
||||||
cancelHandshakeTimeout()
|
cancelHandshakeTimeout()
|
||||||
@@ -191,13 +193,13 @@ class DialogueClient(
|
|||||||
previous?.cancel()
|
previous?.cancel()
|
||||||
if (previous != null) connectionLog("ws disconnected")
|
if (previous != null) connectionLog("ws disconnected")
|
||||||
else if (previousHealth != null) connectionLog("health cancelled", "connect")
|
else if (previousHealth != null) connectionLog("health cancelled", "connect")
|
||||||
updateStatus(ConnectionStatus.DISCONNECTED)
|
updateStatus(ConnectionStatus.DISCONNECTED, reason)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun release() {
|
fun release() {
|
||||||
checkMainThread()
|
checkMainThread()
|
||||||
if (released) return
|
if (released) return
|
||||||
disconnect()
|
disconnect("client_release")
|
||||||
released = true
|
released = true
|
||||||
client.dispatcher.executorService.shutdown()
|
client.dispatcher.executorService.shutdown()
|
||||||
client.connectionPool.evictAll()
|
client.connectionPool.evictAll()
|
||||||
@@ -221,7 +223,7 @@ class DialogueClient(
|
|||||||
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)))) {
|
||||||
connectionLog("ws audio send failed", "audio")
|
connectionLog("ws audio send failed", "audio")
|
||||||
finish(current, ConnectionStatus.DISCONNECTED)
|
finish(current, ConnectionStatus.DISCONNECTED, "audio_send_failure_or_backpressure")
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
@@ -236,7 +238,7 @@ class DialogueClient(
|
|||||||
}
|
}
|
||||||
if (current.send(text)) return true
|
if (current.send(text)) return true
|
||||||
connectionLog("ws send failed", "error")
|
connectionLog("ws send failed", "error")
|
||||||
finish(current, ConnectionStatus.DISCONNECTED)
|
finish(current, ConnectionStatus.DISCONNECTED, "control_send_failure")
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -269,7 +271,7 @@ class DialogueClient(
|
|||||||
event.type in setOf("auth.error", "auth.failed") ||
|
event.type in setOf("auth.error", "auth.failed") ||
|
||||||
event.payload.optString("status") in setOf("error", "failed", "denied")) {
|
event.payload.optString("status") in setOf("error", "failed", "denied")) {
|
||||||
connectionLog("auth failed", "error")
|
connectionLog("auth failed", "error")
|
||||||
finish(webSocket, ConnectionStatus.DISCONNECTED)
|
finish(webSocket, ConnectionStatus.DISCONNECTED, "auth_rejected")
|
||||||
return@dispatch
|
return@dispatch
|
||||||
}
|
}
|
||||||
if (authReceived) return@dispatch
|
if (authReceived) return@dispatch
|
||||||
@@ -280,7 +282,7 @@ class DialogueClient(
|
|||||||
connectionLog("hello sent", "auth")
|
connectionLog("hello sent", "auth")
|
||||||
} else {
|
} else {
|
||||||
connectionLog("hello send failed", "error")
|
connectionLog("hello send failed", "error")
|
||||||
finish(webSocket, ConnectionStatus.DISCONNECTED)
|
finish(webSocket, ConnectionStatus.DISCONNECTED, "hello_send_failure")
|
||||||
}
|
}
|
||||||
return@dispatch
|
return@dispatch
|
||||||
}
|
}
|
||||||
@@ -292,11 +294,11 @@ class DialogueClient(
|
|||||||
ready = true
|
ready = true
|
||||||
cancelHandshakeTimeout()
|
cancelHandshakeTimeout()
|
||||||
connectionLog("hello received", "auth")
|
connectionLog("hello received", "auth")
|
||||||
updateStatus(ConnectionStatus.CONNECTED)
|
updateStatus(ConnectionStatus.CONNECTED, "server_hello_received")
|
||||||
}
|
}
|
||||||
if (event.kind == EventKind.ERROR && !ready) {
|
if (event.kind == EventKind.ERROR && !ready) {
|
||||||
connectionLog("握手收到 error", "error")
|
connectionLog("握手收到 error", "error")
|
||||||
finish(webSocket, ConnectionStatus.DISCONNECTED)
|
finish(webSocket, ConnectionStatus.DISCONNECTED, "server_error_during_handshake")
|
||||||
}
|
}
|
||||||
onEvent(event)
|
onEvent(event)
|
||||||
}
|
}
|
||||||
@@ -319,12 +321,12 @@ 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.
|
// finish invalidates onClosed, so record the close code here as well.
|
||||||
connectionLog("ws closed: $code")
|
connectionLog("ws closed: $code")
|
||||||
finish(webSocket, statusFor(code))
|
finish(webSocket, statusFor(code), "ws_closing:$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) {
|
||||||
connectionLog("ws closed: $code")
|
connectionLog("ws closed: $code")
|
||||||
finish(webSocket, statusFor(code))
|
finish(webSocket, statusFor(code), "ws_closed:$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) {
|
||||||
@@ -332,7 +334,8 @@ class DialogueClient(
|
|||||||
response != null -> "ws failure: HTTP ${response.code}"
|
response != null -> "ws failure: HTTP ${response.code}"
|
||||||
else -> "ws failure: ${failureSummary(t)}"
|
else -> "ws failure: ${failureSummary(t)}"
|
||||||
}, "error")
|
}, "error")
|
||||||
finish(webSocket, if (response?.code == 403) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED)
|
finish(webSocket, if (response?.code == 403) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED,
|
||||||
|
if (response != null) "ws_failure_http:${response.code}" else "ws_failure:${failureSummary(t)}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -341,11 +344,12 @@ class DialogueClient(
|
|||||||
onConnectionLog(message)
|
onConnectionLog(message)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun updateStatus(next: ConnectionStatus) {
|
private fun updateStatus(next: ConnectionStatus, reason: String) {
|
||||||
if (status != next) {
|
if (status != next) {
|
||||||
status = next
|
status = next
|
||||||
DebugLogUpload.log("connect", "state=${next.name.lowercase()}")
|
DebugLogUpload.log("connect", "state=${next.name.lowercase()} reason=$reason")
|
||||||
}
|
}
|
||||||
|
onStatusReason(next, reason)
|
||||||
onStatus(next)
|
onStatus(next)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -361,7 +365,12 @@ class DialogueClient(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun finish(webSocket: WebSocket?, status: ConnectionStatus) {
|
private fun finish(webSocket: WebSocket?, status: ConnectionStatus, reason: String) {
|
||||||
|
// Synthetic exception contains only our fixed reason and code locations, no server
|
||||||
|
// payload/Throwable messages. Full trace stays in logcat; LAN/UI get a bounded trace.
|
||||||
|
val stack = Log.getStackTraceString(Throwable("DialogueClient.finish reason=$reason"))
|
||||||
|
Log.w("LanVoice", stack)
|
||||||
|
connectionLog("finish reason=$reason stack=${stack.replace('\n', '|').replace('\t', ' ').take(360)}", "error")
|
||||||
// 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()
|
cancelHandshakeTimeout()
|
||||||
val previousHealth = healthCall
|
val previousHealth = healthCall
|
||||||
@@ -370,7 +379,7 @@ class DialogueClient(
|
|||||||
socket = null
|
socket = null
|
||||||
ready = false
|
ready = false
|
||||||
webSocket?.cancel()
|
webSocket?.cancel()
|
||||||
updateStatus(status)
|
updateStatus(status, reason)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun cancelHandshakeTimeout() {
|
private fun cancelHandshakeTimeout() {
|
||||||
|
|||||||
Reference in New Issue
Block a user