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 android.bluetooth.IBluetoothManager.GET_SYSTEM_STATE_API
21 import android.bluetooth.IBluetoothManager.IPC_CACHE_MODULE_SYSTEM
22 import android.os.IpcDataCache
23 import com.android.bluetooth.flags.Flags
24 import kotlin.time.Duration
25 import kotlin.time.toKotlinDuration
26 import kotlinx.coroutines.flow.MutableSharedFlow
27 import kotlinx.coroutines.flow.filter
28 import kotlinx.coroutines.flow.first
29 import kotlinx.coroutines.runBlocking
30 import kotlinx.coroutines.withTimeoutOrNull
31 
32 /** Thread safe class that allow waiting on a specific state change */
33 class BluetoothAdapterState {
34     // MutableStateFlow cannot be used because it is conflated (See official doc)
35     private val _uiState = MutableSharedFlow<Int>(1 /* replay only most recent value*/)
36 
37     init {
38         set(STATE_OFF)
39     }
40 
<lambda>null41     fun set(s: Int) = runBlocking {
42         _uiState.emit(s)
43         if (Flags.getStateFromSystemServer()) {
44             IpcDataCache.invalidateCache(IPC_CACHE_MODULE_SYSTEM, GET_SYSTEM_STATE_API)
45         }
46     }
47 
getnull48     fun get(): Int = _uiState.replayCache.get(0)
49 
50     fun oneOf(vararg states: Int): Boolean = states.contains(get())
51 
52     override fun toString() = BluetoothAdapter.nameForState(get())
53 
54     fun waitForState(timeout: java.time.Duration, vararg states: Int) = runBlocking {
55         waitForState(timeout.toKotlinDuration(), *states)
56     }
57 
waitForStatenull58     suspend fun waitForState(timeout: Duration, vararg states: Int): Boolean =
59         withTimeoutOrNull(timeout) { _uiState.filter { states.contains(it) }.first() } != null
60 }
61