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