1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.server.bluetooth
17 
18 import android.bluetooth.BluetoothAdapter
19 import android.bluetooth.BluetoothAdapter.STATE_OFF
20 import kotlin.time.Duration
21 import kotlin.time.toKotlinDuration
22 import kotlinx.coroutines.flow.MutableSharedFlow
23 import kotlinx.coroutines.flow.filter
24 import kotlinx.coroutines.flow.first
25 import kotlinx.coroutines.runBlocking
26 import kotlinx.coroutines.withTimeoutOrNull
27 
28 /** Thread safe class that allow waiting on a specific state change */
29 class BluetoothAdapterState {
30     // MutableStateFlow cannot be used because it is conflated (See official doc)
31     private val _uiState = MutableSharedFlow<Int>(1 /* replay only most recent value*/)
32 
33     init {
34         set(STATE_OFF)
35     }
36 
<lambda>null37     fun set(s: Int) = runBlocking { _uiState.emit(s) }
38 
getnull39     fun get(): Int = _uiState.replayCache.get(0)
40 
41     fun oneOf(vararg states: Int): Boolean = states.contains(get())
42 
43     override fun toString() = BluetoothAdapter.nameForState(get())
44 
45     fun waitForState(timeout: java.time.Duration, vararg states: Int) = runBlocking {
46         waitForState(timeout.toKotlinDuration(), *states)
47     }
48 
waitForStatenull49     suspend fun waitForState(timeout: Duration, vararg states: Int): Boolean =
50         withTimeoutOrNull(timeout) { _uiState.filter { states.contains(it) }.first() } != null
51 }
52