blob: e0929bb47a3aaa081588f0c00718ee57d16f724f [file] [log] [blame]
Paul Huf5020472024-07-04 07:51:22 +00001/*
2 * Copyright (C) 2024 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
17package com.google.snippet.connectivity
18
19import android.net.wifi.WifiManager
20import android.net.wifi.p2p.WifiP2pManager
21import androidx.test.platform.app.InstrumentationRegistry
22import com.google.android.mobly.snippet.Snippet
23import com.google.android.mobly.snippet.rpc.Rpc
24import java.util.concurrent.CompletableFuture
25import java.util.concurrent.TimeUnit
26import kotlin.test.fail
27
28private const val TIMEOUT_MS = 60000L
29
30class Wifip2pMultiDevicesSnippet : Snippet {
31 private val context by lazy { InstrumentationRegistry.getInstrumentation().getTargetContext() }
32 private val wifiManager by lazy {
33 context.getSystemService(WifiManager::class.java)
34 ?: fail("Could not get WifiManager service")
35 }
36 private val wifip2pManager by lazy {
37 context.getSystemService(WifiP2pManager::class.java)
38 ?: fail("Could not get WifiP2pManager service")
39 }
40 private lateinit var wifip2pChannel: WifiP2pManager.Channel
41
42 @Rpc(description = "Check whether the device supports Wi-Fi P2P.")
43 fun isP2pSupported() = wifiManager.isP2pSupported()
44
45 @Rpc(description = "Start Wi-Fi P2P")
46 fun startWifiP2p() {
47 // Initialize Wi-Fi P2P
48 wifip2pChannel = wifip2pManager.initialize(context, context.mainLooper, null)
49
50 // Ensure the Wi-Fi P2P channel is available
51 val p2pStateEnabledFuture = CompletableFuture<Boolean>()
52 wifip2pManager.requestP2pState(wifip2pChannel) { state ->
53 if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
54 p2pStateEnabledFuture.complete(true)
55 }
56 }
57 p2pStateEnabledFuture.get(TIMEOUT_MS, TimeUnit.MILLISECONDS)
58 }
59
60 @Rpc(description = "Stop Wi-Fi P2P")
61 fun stopWifiP2p() {
62 if (this::wifip2pChannel.isInitialized) {
63 wifip2pManager.cancelConnect(wifip2pChannel, null)
64 wifip2pManager.removeGroup(wifip2pChannel, null)
65 }
66 }
67}