Document radio invitation state and cover continuation and stale pending events
This commit is contained in:
1 parent
3d04e59447
commit
b033b15335
2 files changed
+67
-2
No files matched your search
@@ -18,11 +18,15 @@ import kotlinx.coroutines.launch
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/** Состояния карточки; PREPARING локален, ENDED соответствует FINISHED ядра либо локальному отказу очереди. */
|
||||
enum class RadioCallPhase { OUTGOING, INCOMING, RINGING, PREPARING, ENDED, WAIT_DECISION }
|
||||
/** id/peer — ненулевые uint64 как биты Long, channelId — десятичный uint64.
|
||||
* Имена — снимок для UI; incoming фиксирует роль, reason — radio_call_reason, без перевода в модели. */
|
||||
data class RadioCallState(
|
||||
val id: Long, val channelId: String, val peer: Long, val peerName: String, val channelName: String,
|
||||
val incoming: Boolean, val phase: RadioCallPhase, val reason: Int = 0
|
||||
)
|
||||
/** Ожидаемое включение рации Activity; результат возвращается в activated с тем же id. */
|
||||
data class RadioCallActivation(val id: Long, val channelId: String)
|
||||
|
||||
/** На main хранит живое приглашение рации; StateFlow повторяет текущий снимок после пересоздания UI.
|
||||
@@ -50,8 +54,10 @@ object RadioCallController {
|
||||
private var visible = false
|
||||
private var answerOnVisible = 0L
|
||||
private var ready = false
|
||||
/** На main: занят также между принятым START и первым событием; ENDED-карточка не удерживает активность. */
|
||||
fun busy(): Boolean = pendingStart != null || _state.value?.phase?.let { it != RadioCallPhase.ENDED } == true
|
||||
|
||||
/** На main запросить START ненулевым участнику/каналу. Резерв busy снимает первое событие либо reset/отказ очереди. */
|
||||
fun start(channel: String, peer: Long) {
|
||||
checkMain()
|
||||
if (!ready || !NativeLib.isReady() || busy() || CallController.state.value?.ongoing == true) {
|
||||
@@ -71,6 +77,7 @@ object RadioCallController {
|
||||
if (!command(id, START, group, peer)) { pendingStart = null; syncActivity(); showOutcome(5) }
|
||||
}
|
||||
|
||||
/** Activity onStart/onStop: отложенный ответ из уведомления допустим только своему ещё входящему вызову. */
|
||||
fun setVisible(value: Boolean) {
|
||||
checkMain()
|
||||
visible = value
|
||||
@@ -91,6 +98,7 @@ object RadioCallController {
|
||||
if (visible) accept() else answerOnVisible = id
|
||||
}
|
||||
|
||||
/** На main запросить микрофон и включение рации; повтор/невидимая Activity не создают новую активацию. */
|
||||
fun accept() {
|
||||
checkMain()
|
||||
val st = _state.value ?: return
|
||||
@@ -109,13 +117,18 @@ object RadioCallController {
|
||||
IncomingCallManager.stopRinging()
|
||||
_state.value = st.copy(phase = RadioCallPhase.PREPARING)
|
||||
_activation.value = RadioCallActivation(st.id, st.channelId)
|
||||
LogManager.addLog("INFO", "radio", "Call audio requested id=${st.id} channel=${st.channelId} incoming=true")
|
||||
}
|
||||
|
||||
/** Вызывается после фактического async-запуска аудио, а не установки флага в ViewModel. */
|
||||
/** На main после фактического async-запуска аудио. Принимается один результат своей PREPARING-активации;
|
||||
* входящий ждёт FINISHED после ACCEPT/FAIL, успешный исходящий снимает карточку сразу. */
|
||||
fun activated(id: Long, success: Boolean) {
|
||||
checkMain()
|
||||
val st = _state.value ?: return
|
||||
if (st.id != id || st.phase != RadioCallPhase.PREPARING || _activation.value?.id != id) return
|
||||
if (st.id != id || st.phase != RadioCallPhase.PREPARING || _activation.value?.id != id) {
|
||||
LogManager.addLog("DEBUG", "radio", "Call activation ignored id=$id success=$success current=${st.id}/${st.phase}")
|
||||
return
|
||||
}
|
||||
_activation.value = null
|
||||
LogManager.addLog(if (success) "INFO" else "ERROR", "radio", "Call activation id=$id success=$success incoming=${st.incoming}")
|
||||
if (st.incoming) {
|
||||
@@ -123,6 +136,7 @@ object RadioCallController {
|
||||
} else if (success) clear() else finish(st, 7)
|
||||
}
|
||||
|
||||
/** На main завершить своё приглашение: DECLINE входящего, иначе CANCEL. Локальная очистка не ждёт очереди. */
|
||||
fun end(id: Long = _state.value?.id ?: 0L) {
|
||||
checkMain()
|
||||
val st = _state.value ?: return
|
||||
@@ -131,6 +145,7 @@ object RadioCallController {
|
||||
finish(st, if (st.incoming && st.phase == RadioCallPhase.INCOMING) 2 else 4)
|
||||
}
|
||||
|
||||
/** На main при stop/restart ядра снять pending/activation/карточку/таймер; SERVICE_STARTED снова разрешает команды. */
|
||||
fun reset() {
|
||||
checkMain()
|
||||
ready = false
|
||||
@@ -141,6 +156,8 @@ object RadioCallController {
|
||||
clear()
|
||||
}
|
||||
|
||||
/** Main-dispatcher событий: 12/13 — start/stop ядра, 65 — id/group/peer:8LE + phase/reason/incoming:1.
|
||||
* Проверяются размер, ненулевые ID, сочетание роли/фазы/причины и полная identity живого запроса. */
|
||||
fun onEvent(type: Int, data: ByteArray?) {
|
||||
checkMain()
|
||||
if (type == 12) { ready = NativeLib.isReady(); return }
|
||||
@@ -218,6 +235,7 @@ object RadioCallController {
|
||||
else {
|
||||
_state.value = current.copy(phase = RadioCallPhase.PREPARING)
|
||||
_activation.value = RadioCallActivation(id, current.channelId)
|
||||
LogManager.addLog("INFO", "radio", "Call audio requested id=$id channel=${current.channelId} incoming=false")
|
||||
}
|
||||
} else finish(current, reason)
|
||||
} else LogManager.addLog("WARN", "radio", "Call event transition ignored id=$id current=${current.phase} phase=$phase")
|
||||
@@ -235,6 +253,7 @@ object RadioCallController {
|
||||
if (!st.incoming || reason == 7) showOutcome(reason)
|
||||
}
|
||||
|
||||
/** На main подтвердить PHONE_BUSY для своей WAIT_DECISION-попытки; CONTINUE сохраняет id, новый срок задаёт ядро. */
|
||||
fun continueCall(id: Long) {
|
||||
checkMain()
|
||||
val st = _state.value ?: return
|
||||
@@ -252,6 +271,7 @@ object RadioCallController {
|
||||
syncActivity()
|
||||
}
|
||||
|
||||
/** UI resource для radio_call_reason; неизвестная причина показывается как «недоступен». */
|
||||
fun reasonText(reason: Int): Int = when (reason) {
|
||||
2 -> R.string.radio_call_declined
|
||||
3 -> R.string.radio_call_busy
|
||||
|
||||
+45
@@ -288,4 +288,49 @@ class RadioCallLifecycleTest {
|
||||
assertTrue(error.get() is IllegalStateException)
|
||||
assertTrue(intent.getBooleanExtra(IncomingCallManager.EXTRA_ANSWER_RADIO, false)); diagnostic("requires main thread")
|
||||
}
|
||||
|
||||
@Test fun continuedCallUsesTheSameAttemptAndAcceptsTheNextCoreTransitions() {
|
||||
val id = outgoing(); emit(id, 5, incoming = false)
|
||||
RadioCallController.continueCall(id)
|
||||
assertEquals(id, calls.last().id); assertEquals(8, calls.last().action)
|
||||
emit(id, 1, incoming = false); emit(id, 3, incoming = false)
|
||||
assertEquals(RadioCallPhase.RINGING, state?.phase)
|
||||
emit(id, 4, 1, false); RadioCallController.activated(id, true)
|
||||
assertNull(state); assertFalse(RadioCallController.busy())
|
||||
}
|
||||
|
||||
@Test fun unsignedIdentifiersPreserveAllTheirWireBits() {
|
||||
RadioCallController.start(ULong.MAX_VALUE.toString(), -2)
|
||||
val request = calls.single()
|
||||
assertEquals(-1L, request.group); assertEquals(-2L, request.peer)
|
||||
RadioCallController.onEvent(65, event(request.id, -1, -2, 1, incoming = false))
|
||||
assertEquals(ULong.MAX_VALUE.toString(), state?.channelId); assertEquals(-2L, state?.peer)
|
||||
}
|
||||
|
||||
@Test fun resetCancelsAQueuedStartAndOldStartedEventCannotReopenIt() {
|
||||
RadioCallController.start("7", 99); val id = calls.single().id
|
||||
RadioCallController.reset()
|
||||
assertEquals(5, calls.last().action); assertEquals(id, calls.last().id); assertFalse(RadioCallController.busy())
|
||||
RadioCallController.onEvent(12, null); emit(id, 1, incoming = false)
|
||||
assertNull(state); diagnostic("without pending start")
|
||||
}
|
||||
|
||||
@Test fun anOldResultCannotPublishAnOutcomeOrReleaseTheNextPendingStart() {
|
||||
val old = outgoing(); RadioCallController.end()
|
||||
RadioCallController.start("8", 100); val pending = calls.last { it.action == 1 }
|
||||
val posted = requireNotNull(context.notificationManager).posted.size
|
||||
emit(old, 4, 2, false)
|
||||
assertTrue(RadioCallController.busy()); assertNull(state)
|
||||
assertEquals(posted, requireNotNull(context.notificationManager).posted.size)
|
||||
RadioCallController.onEvent(65, event(pending.id, 8, 100, 1, incoming = false))
|
||||
assertEquals(pending.id, state?.id)
|
||||
}
|
||||
|
||||
@Test fun anEndedCardsTimerCannotCancelAQueuedReplacementStart() {
|
||||
outgoing(); RadioCallController.end(); dispatcher.scheduler.runCurrent()
|
||||
RadioCallController.start("7", 99); val pending = calls.last { it.action == 1 }
|
||||
dispatcher.scheduler.advanceUntilIdle()
|
||||
assertTrue(RadioCallController.busy())
|
||||
emit(pending.id, 1, incoming = false); assertEquals(pending.id, state?.id)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user