summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--WIFI_OWNERS1
-rw-r--r--service/ServiceWifiResources/res/values-eu/strings.xml2
-rw-r--r--tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/ConnectivityManagerSnippet.java22
-rw-r--r--tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/WifiAwareManagerSnippet.java264
-rw-r--r--tests/hostsidetests/multidevices/test/aware/constants.py50
-rw-r--r--tests/hostsidetests/multidevices/test/aware/integration/Android.bp43
-rw-r--r--tests/hostsidetests/multidevices/test/aware/integration/aware_lib_utils.py209
-rw-r--r--tests/hostsidetests/multidevices/test/aware/integration/wifi_aware_attached_test.py222
-rw-r--r--tests/hostsidetests/multidevices/test/aware/wifi_aware_manager_test.py65
9 files changed, 762 insertions, 116 deletions
diff --git a/WIFI_OWNERS b/WIFI_OWNERS
index 5ead12ec0b..caa458790e 100644
--- a/WIFI_OWNERS
+++ b/WIFI_OWNERS
@@ -1,5 +1,4 @@
# Bug component: 33618
-etancohen@google.com
arabawy@google.com
satk@google.com
diff --git a/service/ServiceWifiResources/res/values-eu/strings.xml b/service/ServiceWifiResources/res/values-eu/strings.xml
index 9ec4e91d5c..42cf712171 100644
--- a/service/ServiceWifiResources/res/values-eu/strings.xml
+++ b/service/ServiceWifiResources/res/values-eu/strings.xml
@@ -19,7 +19,7 @@
<string name="wifiResourcesAppLabel" product="default" msgid="3120115613525263696">"Sistemaren wifi-baliabideak"</string>
<string name="wifi_available_title" msgid="3899472737467127635">"Konektatu wifi-sare irekira"</string>
<string name="wifi_available_title_connecting" msgid="7233590022728579868">"Wi‑Fi sarera konektatzen"</string>
- <string name="wifi_available_title_connected" msgid="6329493859989844201">"Wi‑Fi sare irekira konektatuta"</string>
+ <string name="wifi_available_title_connected" msgid="6329493859989844201">"Wifi-sare irekira konektatuta"</string>
<string name="wifi_available_title_failed_to_connect" msgid="4840833680513368639">"Ezin izan da konektatu wifi-sare irekira"</string>
<string name="wifi_available_content_failed_to_connect" msgid="4330035988269701861">"Sakatu hau sare guztiak ikusteko"</string>
<string name="wifi_available_action_connect" msgid="5636634933476946222">"Konektatu"</string>
diff --git a/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/ConnectivityManagerSnippet.java b/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/ConnectivityManagerSnippet.java
index 50b6f649b0..d37cbd1f10 100644
--- a/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/ConnectivityManagerSnippet.java
+++ b/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/ConnectivityManagerSnippet.java
@@ -32,6 +32,9 @@ import com.google.android.mobly.snippet.rpc.AsyncRpc;
import com.google.android.mobly.snippet.rpc.Rpc;
import com.google.android.mobly.snippet.util.Log;
+import java.util.HashMap;
+import java.util.Map;
+
public class ConnectivityManagerSnippet implements Snippet {
private static final String EVENT_KEY_CB_NAME = "callbackName";
private static final String EVENT_KEY_NETWORK = "network";
@@ -40,7 +43,7 @@ public class ConnectivityManagerSnippet implements Snippet {
private final Context mContext;
private final ConnectivityManager mConnectivityManager;
- private NetworkCallback mNetworkCallBack;
+ private final Map<String, NetworkCallback> mNetworkCallBacks = new HashMap<>();
class ConnectivityManagerSnippetSnippetException extends Exception {
ConnectivityManagerSnippetSnippetException(String msg) {
@@ -92,7 +95,8 @@ public class ConnectivityManagerSnippet implements Snippet {
/**
* Requests a network with given network request.
*
- * @param callBackId Assigned automatically by mobly.
+ * @param callBackId Assigned automatically by mobly. Will be used as request Id
+ * for further operations
* @param request The request object.
* @param requestNetworkTimeoutMs The timeout in milliseconds.
*/
@@ -100,18 +104,22 @@ public class ConnectivityManagerSnippet implements Snippet {
public void connectivityRequestNetwork(String callBackId, NetworkRequest request,
int requestNetworkTimeoutMs) {
Log.v("Requesting network with request: " + request.toString());
- mNetworkCallBack = new NetworkCallback(callBackId);
- mConnectivityManager.requestNetwork(request, mNetworkCallBack, requestNetworkTimeoutMs);
+ NetworkCallback callback = new NetworkCallback(callBackId);
+ mNetworkCallBacks.put(callBackId, callback);
+ mConnectivityManager.requestNetwork(request, callback, requestNetworkTimeoutMs);
}
/**
* Unregisters the registered network callback and possibly releases requested networks.
+ *
+ * @param requestId Id of the network request.
*/
@Rpc(description = "Unregister a network request")
- public void connectivityUnregisterNetwork() {
- if (mNetworkCallBack == null) {
+ public void connectivityUnregisterNetwork(String requestId) {
+ NetworkCallback callback = mNetworkCallBacks.get(requestId);
+ if (callback == null) {
return;
}
- mConnectivityManager.unregisterNetworkCallback(mNetworkCallBack);
+ mConnectivityManager.unregisterNetworkCallback(callback);
}
}
diff --git a/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/WifiAwareManagerSnippet.java b/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/WifiAwareManagerSnippet.java
index 92f207976c..7ca1a1fa28 100644
--- a/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/WifiAwareManagerSnippet.java
+++ b/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/WifiAwareManagerSnippet.java
@@ -17,11 +17,15 @@
package com.google.snippet.wifi.aware;
import android.Manifest;
+import android.content.BroadcastReceiver;
import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
import android.net.wifi.aware.AttachCallback;
import android.net.wifi.aware.Characteristics;
import android.net.wifi.aware.DiscoverySession;
import android.net.wifi.aware.DiscoverySessionCallback;
+import android.net.wifi.aware.IdentityChangedListener;
import android.net.wifi.aware.PeerHandle;
import android.net.wifi.aware.PublishConfig;
import android.net.wifi.aware.PublishDiscoverySession;
@@ -50,7 +54,10 @@ import com.google.android.mobly.snippet.util.Log;
import org.json.JSONException;
import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
/**
* Snippet class for exposing {@link WifiAwareManager} APIs.
@@ -60,18 +67,13 @@ public class WifiAwareManagerSnippet implements Snippet {
private final WifiAwareManager mWifiAwareManager;
private final Handler mHandler;
// WifiAwareSession will be initialized after attach.
- private WifiAwareSession mWifiAwareSession;
+ private final Map<String, WifiAwareSession> mAttachSessions = new HashMap<>();
// DiscoverySession will be initialized after publish or subscribe
- private DiscoverySession mDiscoverySession;
- private PeerHandle mPeerHandle;
+ private final Map<String, DiscoverySession> mDiscoverySessions = new HashMap<>();
+ private final Map<Integer, PeerHandle> mPeerHandles = new HashMap<>();
private final Object mLock = new Object();
-
- private enum AttachState {
- IDLE, ATTACHING, ATTACHED
- }
-
- private AttachState mAttachState = AttachState.IDLE;
-
+ private final EventCache eventCache = EventCache.getInstance();
+ private WifiAwareStateChangedReceiver stateChangedReceiver;
private static class WifiAwareManagerSnippetException extends Exception {
WifiAwareManagerSnippetException(String msg) {
@@ -93,61 +95,123 @@ public class WifiAwareManagerSnippet implements Snippet {
/**
* Use {@link WifiAwareManager#attach(AttachCallback, Handler)} to attach to the Wi-Fi Aware.
+ * @param callbackId Assigned automatically by mobly. Also will be used as Attach session id for
+ * further operations
*/
@AsyncRpc(description = "Attach to the Wi-Fi Aware service - enabling the application to "
+ "create discovery sessions or publish or subscribe to services.")
public void wifiAwareAttach(String callbackId) throws WifiAwareManagerSnippetException {
- synchronized (mLock) {
- if (mAttachState != AttachState.IDLE) {
- throw new WifiAwareManagerSnippetException(
- "Attaching multiple Wi-Fi Aware session is not supported now. Wi-Fi Aware"
- + " is currently attaching or already attached. Please wait for "
- + "the current operation to complete, or call `wifiAwareDetach` to "
- + "cancel and re-attach .");
- }
- mAttachState = AttachState.ATTACHING;
- }
+ attach(callbackId, true);
+ }
+
+ @AsyncRpc(description = "Attach to the Wi-Fi Aware service - enabling the application to "
+ + "create discovery sessions or publish or subscribe to services.")
+ public void wifiAwareAttached(String callbackId, boolean identityCb)
+ throws WifiAwareManagerSnippetException {
+ attach(callbackId, identityCb);
+ }
+
+ private void attach(String callbackId, boolean identityCb){
AttachCallback attachCallback = new AttachCallback() {
@Override
public void onAttachFailed() {
super.onAttachFailed();
- synchronized (mLock) {
- mAttachState = AttachState.IDLE;
- }
sendEvent(callbackId, "onAttachFailed");
}
@Override
public void onAttached(WifiAwareSession session) {
super.onAttached(session);
+ sendEvent(callbackId, "onAttached");
synchronized (mLock) {
- mWifiAwareSession = session;
- mAttachState = AttachState.ATTACHED;
+ mAttachSessions.put(callbackId, session);
}
- sendEvent(callbackId, "onAttached");
}
@Override
public void onAwareSessionTerminated() {
super.onAwareSessionTerminated();
- wifiAwareDetach();
+ wifiAwareDetach(callbackId);
sendEvent(callbackId, "onAwareSessionTerminated");
}
};
- mWifiAwareManager.attach(attachCallback, mHandler);
+ mWifiAwareManager.attach(attachCallback,
+ (identityCb ? new AwareIdentityChangeListenerPostsEvents(eventCache, callbackId) : null),
+ mHandler);
+ }
+
+ private static class AwareIdentityChangeListenerPostsEvents extends IdentityChangedListener {
+ private final EventCache eventCache;
+ private final String callbackId;
+
+ public AwareIdentityChangeListenerPostsEvents(EventCache eventCache, String callbackId) {
+ this.eventCache = eventCache;
+ this.callbackId = callbackId;
+ }
+
+ @Override
+ public void onIdentityChanged(byte[] mac) {
+ SnippetEvent event = new SnippetEvent(
+ callbackId,
+ "WifiAwareAttachOnIdentityChanged");
+ event.getData().putLong("timestampMs", System.currentTimeMillis());
+ event.getData().putString("mac", Arrays.toString(mac));
+ eventCache.postEvent(event);
+ Log.d("WifiAwareattach identity changed called for WifiAwareAttachOnIdentityChanged");
+ }
+ }
+
+ /**
+ * Starts listening for wifiAware state change related broadcasts.
+ *
+ * @param callbackId the callback id
+ */
+ @AsyncRpc(description = "Start listening for wifiAware state change related broadcasts.")
+ public void wifiAwareMonitorStateChange(String callbackId) {
+ stateChangedReceiver = new WifiAwareStateChangedReceiver(eventCache, callbackId);
+ IntentFilter filter = new IntentFilter(WifiAwareManager.ACTION_WIFI_AWARE_STATE_CHANGED);
+ mContext.registerReceiver(stateChangedReceiver, filter);
+ }
+
+ /** Stops listening for wifiAware state change related broadcasts. */
+ @Rpc(description = "Stop listening for wifiAware state change related broadcasts.")
+ public void wifiAwareMonitorStopStateChange() {
+ if (stateChangedReceiver != null) {
+ mContext.unregisterReceiver(stateChangedReceiver);
+ stateChangedReceiver = null;
+ }
+ }
+
+ class WifiAwareStateChangedReceiver extends BroadcastReceiver {
+ private final EventCache eventCache;
+ private final String callbackId;
+
+ public WifiAwareStateChangedReceiver(EventCache eventCache, String callbackId) {
+ this.eventCache = eventCache;
+ this.callbackId = callbackId;
+ }
+
+ @Override
+ public void onReceive(Context c, Intent intent) {
+ boolean isAvailable = mWifiAwareManager.isAvailable();
+ SnippetEvent event =
+ new SnippetEvent(
+ callbackId, "WifiAwareState" + (isAvailable ? "Available" : "NotAvailable"));
+ eventCache.postEvent(event);
+ }
}
/**
* Use {@link WifiAwareSession#close()} to detach from the Wi-Fi Aware.
+ *
+ * @param sessionId The Id of the Aware attach session
*/
@Rpc(description = "Detach from the Wi-Fi Aware service.")
- public void wifiAwareDetach() {
+ public void wifiAwareDetach(String sessionId) {
synchronized (mLock) {
- if (mWifiAwareSession != null) {
- mWifiAwareSession.close();
- mWifiAwareSession = null;
- }
- mAttachState = AttachState.IDLE;
+ WifiAwareSession session = mAttachSessions.remove(sessionId);
+ if (session == null) return;
+ session.close();
}
}
@@ -158,7 +222,7 @@ public class WifiAwareManagerSnippet implements Snippet {
@Rpc(description = "Check if Wi-Fi aware is attached")
public boolean wifiAwareIsSessionAttached() {
synchronized (mLock) {
- return mAttachState == AttachState.ATTACHED && mWifiAwareSession != null;
+ return !mAttachSessions.isEmpty();
}
}
@@ -228,7 +292,7 @@ public class WifiAwareManagerSnippet implements Snippet {
@Override
public void onPublishStarted(PublishDiscoverySession session) {
- mDiscoverySession = session;
+ mDiscoverySessions.put(mCallBackId, session);
SnippetEvent snippetEvent = new SnippetEvent(mCallBackId, "discoveryResult");
snippetEvent.getData().putString("callbackName", "onPublishStarted");
snippetEvent.getData().putBoolean("isSessionInitialized", session != null);
@@ -237,7 +301,7 @@ public class WifiAwareManagerSnippet implements Snippet {
@Override
public void onSubscribeStarted(SubscribeDiscoverySession session) {
- mDiscoverySession = session;
+ mDiscoverySessions.put(mCallBackId, session);
SnippetEvent snippetEvent = new SnippetEvent(mCallBackId, "discoveryResult");
snippetEvent.getData().putString("callbackName", "onSubscribeStarted");
snippetEvent.getData().putBoolean("isSessionInitialized", session != null);
@@ -264,22 +328,22 @@ public class WifiAwareManagerSnippet implements Snippet {
@Override
public void onServiceDiscovered(PeerHandle peerHandle, byte[] serviceSpecificInfo,
List<byte[]> matchFilter) {
- mPeerHandle = peerHandle;
+ mPeerHandles.put(peerHandle.hashCode(), peerHandle);
SnippetEvent event = new SnippetEvent(mCallBackId, "onServiceDiscovered");
event.getData().putByteArray("serviceSpecificInfo", serviceSpecificInfo);
- event.getData().putInt("peerId", mPeerHandle.hashCode());
+ event.getData().putInt("peerId", peerHandle.hashCode());
putMatchFilterData(matchFilter, event);
EventCache.getInstance().postEvent(event);
}
@Override
public void onServiceDiscovered(ServiceDiscoveryInfo info) {
- mPeerHandle = info.getPeerHandle();
+ mPeerHandles.put(info.getPeerHandle().hashCode(), info.getPeerHandle());
List<byte[]> matchFilter = info.getMatchFilters();
SnippetEvent event = new SnippetEvent(mCallBackId, "onServiceDiscovered");
event.getData().putByteArray("serviceSpecificInfo", info.getServiceSpecificInfo());
event.getData().putString("pairedAlias", info.getPairedAlias());
- event.getData().putInt("peerId", mPeerHandle.hashCode());
+ event.getData().putInt("peerId", info.getPeerHandle().hashCode());
putMatchFilterData(matchFilter, event);
EventCache.getInstance().postEvent(event);
}
@@ -288,11 +352,11 @@ public class WifiAwareManagerSnippet implements Snippet {
public void onServiceDiscoveredWithinRange(PeerHandle peerHandle,
byte[] serviceSpecificInfo,
List<byte[]> matchFilter, int distanceMm) {
- mPeerHandle = peerHandle;
+ mPeerHandles.put(peerHandle.hashCode(), peerHandle);
SnippetEvent event = new SnippetEvent(mCallBackId, "onServiceDiscoveredWithinRange");
event.getData().putByteArray("serviceSpecificInfo", serviceSpecificInfo);
event.getData().putInt("distanceMm", distanceMm);
- event.getData().putInt("peerId", mPeerHandle.hashCode());
+ event.getData().putInt("peerId", peerHandle.hashCode());
putMatchFilterData(matchFilter, event);
EventCache.getInstance().postEvent(event);
}
@@ -315,7 +379,7 @@ public class WifiAwareManagerSnippet implements Snippet {
@Override
public void onMessageReceived(PeerHandle peerHandle, byte[] message) {
- mPeerHandle = peerHandle;
+ mPeerHandles.put(peerHandle.hashCode(), peerHandle);
SnippetEvent event = new SnippetEvent(mCallBackId, "onMessageReceived");
event.getData().putByteArray("receivedMessage", message);
event.getData().putInt("peerId", peerHandle.hashCode());
@@ -348,7 +412,7 @@ public class WifiAwareManagerSnippet implements Snippet {
@Override
public void onPairingVerificationSucceed(
@NonNull PeerHandle peerHandle, @NonNull String alias) {
- super.onPairingVerificationSucceed(mPeerHandle, alias);
+ super.onPairingVerificationSucceed(peerHandle, alias);
SnippetEvent event = new SnippetEvent(mCallBackId, "onPairingVerificationSucceed");
event.getData().putString("pairedAlias", alias);
event.getData().putInt("peerId", peerHandle.hashCode());
@@ -378,10 +442,15 @@ public class WifiAwareManagerSnippet implements Snippet {
}
}
- private void checkWifiAwareSession() throws WifiAwareManagerSnippetException {
- if (mWifiAwareSession == null) {
- throw new WifiAwareManagerSnippetException(
- "Wi-Fi Aware session is not attached. Please call wifiAwareAttach first.");
+ private WifiAwareSession getWifiAwareSession(String sessionId)
+ throws WifiAwareManagerSnippetException {
+ synchronized (mLock) {
+ WifiAwareSession session = mAttachSessions.get(sessionId);
+ if (session == null) {
+ throw new WifiAwareManagerSnippetException(
+ "Wi-Fi Aware session is not attached. Please call wifiAwareAttach first.");
+ }
+ return session;
}
}
@@ -392,19 +461,23 @@ public class WifiAwareManagerSnippet implements Snippet {
* permission flag "neverForLocation". For earlier versions, this method requires
* NEARBY_WIFI_DEVICES and ACCESS_FINE_LOCATION permissions.
*
- * @param callbackId Assigned automatically by mobly.
+ * @param sessionId The Id of the Aware attach session, should be the callbackId from
+ * {@link #wifiAwareAttach(String)}
+ * @param callbackId Assigned automatically by mobly. Also will be used as discovery
+ * session id for further operations
* @param subscribeConfig Defines the subscription configuration via
* WifiAwareJsonDeserializer.
*/
@AsyncRpc(
description = "Create a Wi-Fi Aware subscribe discovery session and handle callbacks.")
- public void wifiAwareSubscribe(String callbackId, SubscribeConfig subscribeConfig) throws
- JSONException, WifiAwareManagerSnippetException {
- checkWifiAwareSession();
+ public void wifiAwareSubscribe(String callbackId, String sessionId,
+ SubscribeConfig subscribeConfig) throws JSONException,
+ WifiAwareManagerSnippetException {
+ WifiAwareSession session = getWifiAwareSession(sessionId);
Log.v("Creating a new Aware subscribe session with config: " + subscribeConfig.toString());
WifiAwareDiscoverySessionCallback myDiscoverySessionCallback =
new WifiAwareDiscoverySessionCallback(callbackId);
- mWifiAwareSession.subscribe(subscribeConfig, myDiscoverySessionCallback, mHandler);
+ session.subscribe(subscribeConfig, myDiscoverySessionCallback, mHandler);
}
/**
@@ -413,29 +486,37 @@ public class WifiAwareManagerSnippet implements Snippet {
* TIRAMISU+.
* ACCESS_FINE_LOCATION is required for earlier versions.
*
- * @param callbackId Assigned automatically by mobly.
+ * @param sessionId The Id of the Aware attach session, should be the callbackId from
+ * {@link #wifiAwareAttach(String)}
+ * @param callbackId Assigned automatically by mobly. Also will be used as discovery
+ * session id for further operations
* @param publishConfig Defines the publish configuration via WifiAwareJsonDeserializer.
*/
@AsyncRpc(description = "Create a Wi-Fi Aware publish discovery session and handle callbacks.")
- public void wifiAwarePublish(String callbackId, PublishConfig publishConfig) throws
- JSONException, WifiAwareManagerSnippetException {
- checkWifiAwareSession();
+ public void wifiAwarePublish(String callbackId, String sessionId, PublishConfig publishConfig)
+ throws JSONException, WifiAwareManagerSnippetException {
+ WifiAwareSession session = getWifiAwareSession(sessionId);
Log.v("Creating a new Aware publish session with config: " + publishConfig.toString());
WifiAwareDiscoverySessionCallback myDiscoverySessionCallback =
new WifiAwareDiscoverySessionCallback(callbackId);
- mWifiAwareSession.publish(publishConfig, myDiscoverySessionCallback, mHandler);
+ session.publish(publishConfig, myDiscoverySessionCallback, mHandler);
}
- private void checkPeerHandler() throws WifiAwareManagerSnippetException {
- if (mPeerHandle == null) {
+ private PeerHandle getPeerHandler(int peerId) throws WifiAwareManagerSnippetException {
+ PeerHandle handle = mPeerHandles.get(peerId);
+ if (handle == null) {
throw new WifiAwareManagerSnippetException("Please call publish or subscribe method");
}
+ return handle;
}
- private void checkDiscoverySession() throws WifiAwareManagerSnippetException {
- if (mDiscoverySession == null) {
+ private DiscoverySession getDiscoverySession(String discoverySessionId)
+ throws WifiAwareManagerSnippetException {
+ DiscoverySession session = mDiscoverySessions.get(discoverySessionId);
+ if (session == null) {
throw new WifiAwareManagerSnippetException("Please call publish or subscribe method");
}
+ return session;
}
/**
@@ -450,8 +531,13 @@ public class WifiAwareManagerSnippet implements Snippet {
* session. If there is no active session, it throws a
* {@link WifiAwareManagerSnippetException}.</p>
*
- * @param messageId an integer representing the message ID, which is used to track the message.
- * @param message a {@link String} containing the message to be sent.
+ * @param discoverySessionId The Id of the discovery session, should be the callbackId from
+ * publish/subscribe action
+ * @param peerId identifier for the peer handle
+ * @param messageId an integer representing the message ID, which is used to track the
+ * message.
+ * @param message a {@link String} containing the message to be sent.
+ *
* @throws WifiAwareManagerSnippetException if there is no active discovery session or
* if sending the message fails.
* @see android.net.wifi.aware.DiscoverySession#sendMessage
@@ -459,11 +545,12 @@ public class WifiAwareManagerSnippet implements Snippet {
* @see java.nio.charset.StandardCharsets#UTF_8
*/
@Rpc(description = "Send a message to a peer using Wi-Fi Aware.")
- public void wifiAwareSendMessage(int messageId, String message) throws
- WifiAwareManagerSnippetException {
+ public void wifiAwareSendMessage(String discoverySessionId, int peerId, int messageId,
+ String message) throws WifiAwareManagerSnippetException {
// 4. send message & wait for send status
- checkDiscoverySession();
- mDiscoverySession.sendMessage(mPeerHandle, messageId,
+ DiscoverySession session = getDiscoverySession(discoverySessionId);
+ PeerHandle handle = getPeerHandler(peerId);
+ session.sendMessage(handle, messageId,
message.getBytes(StandardCharsets.UTF_8));
}
@@ -473,45 +560,50 @@ public class WifiAwareManagerSnippet implements Snippet {
* <p>This method checks if there is an active discovery session. If so,
* it closes the session and sets the session object to null. This ensures
* that resources are properly released and the session is cleanly terminated.</p>
+ *
+ * @param discoverySessionId The Id of the discovery session
*/
@Rpc(description = "Close the current Wi-Fi Aware discovery session.")
- public void wifiAwareCloseDiscoverSession() {
- if (mDiscoverySession != null) {
- mDiscoverySession.close();
- mDiscoverySession = null;
+ public void wifiAwareCloseDiscoverSession(String discoverySessionId) {
+ DiscoverySession session = mDiscoverySessions.remove(discoverySessionId);
+ if (session != null) {
+ session.close();
}
}
/**
- * Closes the current Wi-Fi Aware session if it is active.
+ * Closes all Wi-Fi Aware session if it is active. And clear all cache sessions
*
- * <p>This method checks if there is an active Wi-Fi Aware session. If so,
- * it closes the session and sets the session object to null. This ensures
- * that resources are properly released and the session is cleanly terminated.</p>
*/
@Rpc(description = "Close the current Wi-Fi Aware session.")
- public void wifiAwareCloseWifiAwareSession() {
- if (mWifiAwareSession != null) {
- mWifiAwareSession.close();
- mWifiAwareSession = null;
+ public void wifiAwareCloseAllWifiAwareSession() {
+ synchronized (mLock) {
+ for (WifiAwareSession session : mAttachSessions.values()) {
+ session.close();
+ }
}
+ mAttachSessions.clear();
+ mDiscoverySessions.clear();
+ mPeerHandles.clear();
}
/**
* Creates a Wi-Fi Aware network specifier for requesting network through connectivityManager.
*
+ * @param discoverySessionId The Id of the discovery session,
+ * @param peerId The Id of the peer handle
* @return a {@link String} containing the network specifier encoded as a Base64 string.
* @throws JSONException if there is an error parsing the JSON object.
* @throws WifiAwareManagerSnippetException if there is an error creating the network specifier.
*/
@Rpc(description = "Create a network specifier to be used when specifying a Aware network "
+ "request")
- public String wifiAwareCreateNetworkSpecifier() throws JSONException,
- WifiAwareManagerSnippetException {
- checkDiscoverySession();
- checkPeerHandler();
+ public String wifiAwareCreateNetworkSpecifier(String discoverySessionId, int peerId)
+ throws JSONException, WifiAwareManagerSnippetException {
+ DiscoverySession session = getDiscoverySession(discoverySessionId);
+ PeerHandle handle = getPeerHandler(peerId);
WifiAwareNetworkSpecifier.Builder builder = new WifiAwareNetworkSpecifier.Builder(
- mDiscoverySession, mPeerHandle);
+ session, handle);
WifiAwareNetworkSpecifier specifier = builder.build();
// Write the WifiAwareNetworkSpecifier to a Parcel
Parcel parcel = Parcel.obtain();
diff --git a/tests/hostsidetests/multidevices/test/aware/constants.py b/tests/hostsidetests/multidevices/test/aware/constants.py
index e69be1c139..c871ebe2b4 100644
--- a/tests/hostsidetests/multidevices/test/aware/constants.py
+++ b/tests/hostsidetests/multidevices/test/aware/constants.py
@@ -18,6 +18,7 @@
import enum
import dataclasses
import datetime
+import operator
# Package name for the Wi-Fi Aware snippet application
WIFI_AWARE_SNIPPET_PACKAGE_NAME = "com.google.snippet.wifi.aware"
@@ -130,6 +131,7 @@ class WifiAwareSnippetParams(enum.StrEnum):
LAST_MESSAGE_ID = "lastMessageId"
PAIRING_REQUEST_ID = "pairingRequestId"
BOOTSTRAPPING_METHOD = "bootstrappingMethod"
+ PEER_ID = "peerId"
@enum.unique
@@ -355,3 +357,51 @@ class NetworkRequest:
'network_specifier': self.network_specifier_parcel,
}
return result
+
+
+@enum.unique
+class AttachCallBackMethodType(enum.StrEnum):
+ """Represents Attach Callback Method Type in Wi-Fi Aware.
+
+ https://developer.android.com/reference/android/net/wifi/aware/AttachCallback
+ """
+ ATTACHED = 'onAttached'
+ ATTACH_FAILED = 'onAttachFailed'
+ AWARE_SESSION_TERMINATED = 'onAwareSessionTerminated'
+ ID_CHANGED = 'WifiAwareAttachOnIdentityChanged'
+
+
+@enum.unique
+class WifiAwareBroadcast(enum.StrEnum):
+ WIFI_AWARE_AVAILABLE = "WifiAwareStateAvailable"
+ WIFI_AWARE_NOT_AVAILABLE = "WifiAwareStateNotAvailable"
+
+
+@enum.unique
+class DeviceidleState(enum.StrEnum):
+ ACTIVE = "ACTIVE"
+ IDLE = "IDLE"
+ INACTIVE = "INACTIVE"
+ OVERRIDE = "OVERRIDE"
+
+
+@enum.unique
+class Operator(enum.Enum):
+ """Operator used in the comparison."""
+
+ GREATER = operator.gt
+ GREATER_EQUAL = operator.ge
+ NOT_EQUAL = operator.ne
+ EQUAL = operator.eq
+ LESS = operator.lt
+ LESS_EQUAL = operator.le
+
+
+@enum.unique
+class AndroidVersion(enum.IntEnum):
+ """Android OS version."""
+
+ R = 11
+ S = 12
+ T = 13
+ U = 14
diff --git a/tests/hostsidetests/multidevices/test/aware/integration/Android.bp b/tests/hostsidetests/multidevices/test/aware/integration/Android.bp
new file mode 100644
index 0000000000..cbabfb0f06
--- /dev/null
+++ b/tests/hostsidetests/multidevices/test/aware/integration/Android.bp
@@ -0,0 +1,43 @@
+// Copyright (C) 2023 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package {
+ default_team: "trendy_team_fwk_wifi_hal",
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+python_library_host {
+ name: "aware_lib_utils",
+ srcs: ["aware_lib_utils.py"],
+ libs: ["wifi_aware_constants"],
+}
+
+python_test_host {
+ name: "WifiAwareAttachTestCases",
+ main: "wifi_aware_attached_test.py",
+ srcs: ["wifi_aware_attached_test.py"],
+ data: [":wifi_aware_snippet_new"],
+ libs: [
+ "aware_lib_utils",
+ "mobly",
+ "wifi_aware_constants",
+ ],
+ test_suites: [
+ "general-tests",
+ ],
+ test_options: {
+ unit_test: false,
+ tags: ["mobly"],
+ },
+}
diff --git a/tests/hostsidetests/multidevices/test/aware/integration/aware_lib_utils.py b/tests/hostsidetests/multidevices/test/aware/integration/aware_lib_utils.py
new file mode 100644
index 0000000000..e49d5d2efb
--- /dev/null
+++ b/tests/hostsidetests/multidevices/test/aware/integration/aware_lib_utils.py
@@ -0,0 +1,209 @@
+
+
+# Copyright (C) 2024 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Util for aware test."""
+import datetime
+import logging
+import time
+from typing import Any, Callable
+
+from aware import constants
+
+from mobly import asserts
+from mobly.controllers import android_device
+from mobly.controllers.android_device_lib import callback_handler_v2
+from mobly.snippet import errors
+
+
+_WAIT_DOZE_MODE_IN_SEC = 5
+_TIMEOUT_INTERVAL_IN_SEC = 1
+_WAIT_WIFI_STATE_TIME_OUT = datetime.timedelta(seconds=10)
+_WAIT_TIME_SEC = 3
+
+
+def callback_no_response(
+ callback: callback_handler_v2.CallbackHandlerV2,
+ event_name: str,
+ timeout: int = _WAIT_WIFI_STATE_TIME_OUT.total_seconds(),
+ use_callbackid: bool = False,
+ ):
+ """Makes a callback call and expects no response within a given timeout.
+
+ Args:
+ callback: Snippet callback object.
+ event_name: event name to wait.
+ timeout: Timeout in second.
+ use_callbackid: Using callbackid in eventname, default False.
+
+ Raises:
+ CallBackError: if receive response.
+ """
+ if use_callbackid:
+ event_name += callback.callback_id
+ try:
+ data = callback.waitAndGet(event_name=event_name, timeout=timeout)
+ raise CallBackError(f' Unexpected response {data}')
+ except errors.CallbackHandlerTimeoutError:
+ return
+
+
+class CallBackError(Exception):
+ """Error raised when there is a problem to get callback response."""
+
+
+def control_wifi(ad: android_device.AndroidDevice,
+ wifi_state: bool):
+ """Control Android Wi-Fi status.
+
+ Args:
+ ad: Android test device.
+ wifi_state: True if or Wifi on False if WiFi off.
+ """
+ if _check_wifi_status(ad) != wifi_state:
+ if wifi_state:
+ ad.adb.shell("svc wifi enable")
+ else:
+ ad.adb.shell("svc wifi disable")
+
+
+def _check_wifi_status(ad: android_device.AndroidDevice):
+ """Check Android Wi-Fi status.
+
+ Args:
+ ad: android device object.
+
+ Returns:
+ True if wifi on, False if wifi off.
+ """
+ cmd = ad.adb.shell("cmd wifi status").decode("utf-8").strip()
+ first_line = cmd.split("\n")[0]
+ logging.info("device wifi status: %s", first_line)
+ if "enabled" in first_line:
+ return True
+ else:
+ return False
+
+
+def set_doze_mode(ad: android_device.AndroidDevice, state: bool) -> bool:
+ """Enables/Disables Android doze mode.
+
+ Args:
+ ad: android device object.
+ state: bool, True if intent to enable Android doze mode, False otherwise.
+
+ Returns:
+ True if doze mode is enabled, False otherwise.
+
+ Raises:
+ TimeoutError: If timeout is hit.
+ """
+ if state:
+ ad.log.info("Enables Android doze mode")
+ _dumpsys(ad, "battery unplug")
+ _dumpsys(ad, "deviceidle enable")
+ _dumpsys(ad, "deviceidle force-idle")
+ time.sleep(_WAIT_DOZE_MODE_IN_SEC)
+ else:
+ ad.log.info("Disables Android doze mode")
+ _dumpsys(ad, "deviceidle disable")
+ _dumpsys(ad, "battery reset")
+ for _ in range(10 + 1):
+ adb_shell_result = _dumpsys(ad, "deviceidle get deep")
+ logging.info("dumpsys deviceidle get deep: %s", adb_shell_result)
+ if adb_shell_result.startswith(constants.DeviceidleState.IDLE.value):
+ return True
+ if adb_shell_result.startswith(constants.DeviceidleState.ACTIVE.value):
+ return False
+ time.sleep(_TIMEOUT_INTERVAL_IN_SEC)
+ # At this point, timeout must have occurred.
+ raise errors.CallbackHandlerTimeoutError(
+ ad, "Timed out after waiting for doze_mode set to {state}"
+ )
+
+
+def _dumpsys(ad: android_device.AndroidDevice, command: str) -> str:
+ """Dumpsys device info.
+
+ Args:
+ ad: android device object.
+ command: adb command.
+
+ Returns:
+ Android dumsys info
+ """
+ return ad.adb.shell(f"dumpsys {command}").decode().strip()
+
+
+def check_android_os_version(
+ ad: android_device.AndroidDevice,
+ operator_func: Callable[[Any, Any], bool],
+ android_version: constants.AndroidVersion,
+ ) -> bool:
+ """Compares device's Android OS version with the given one.
+
+ Args:
+ ad: Android devices.
+ operator_func: Operator used in the comparison.
+ android_version: The given Android OS version.
+
+ Returns:
+ bool: The comparison result.
+ """
+ device_os_version = int(ad.adb.shell("getprop ro.build.version.release"))
+ result = False
+ if isinstance(operator_func, constants.Operator):
+ return operator_func.value(device_os_version, android_version)
+ return result
+
+
+def _get_airplane_mode(ad: android_device.AndroidDevice) -> bool:
+ """Gets the airplane mode.
+
+ Args:
+ ad: android device object.
+
+ Returns:
+ True if airplane mode On, False for Off.
+ """
+ state = ad.adb.shell("settings get global airplane_mode_on")
+ return bool(int(state))
+
+
+def set_airplane_mode(ad: android_device.AndroidDevice, state: bool):
+ """Sets the airplane mode to the given state.
+
+ Args:
+ ad: android device object.
+ state: bool, True for Airplane mode on, False for off.
+ """
+ ad.adb.shell(
+ ["settings", "put", "global", "airplane_mode_on", str(int(state))]
+ )
+ ad.adb.shell([
+ "am",
+ "broadcast",
+ "-a",
+ "android.intent.action.AIRPLANE_MODE",
+ "--ez",
+ "state",
+ str(state),
+ ])
+ start_time = time.time()
+ while _get_airplane_mode(ad) != state:
+ time.sleep(_TIMEOUT_INTERVAL_IN_SEC)
+ asserts.assert_greater(
+ time.time() - start_time > _WAIT_TIME_SEC,
+ f"Failed to set airplane mode to: {state}",
+ )
diff --git a/tests/hostsidetests/multidevices/test/aware/integration/wifi_aware_attached_test.py b/tests/hostsidetests/multidevices/test/aware/integration/wifi_aware_attached_test.py
new file mode 100644
index 0000000000..f167de6c0c
--- /dev/null
+++ b/tests/hostsidetests/multidevices/test/aware/integration/wifi_aware_attached_test.py
@@ -0,0 +1,222 @@
+# Copyright (C) 2024 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Lint as: python3
+"""ACTS Wi-Fi Aware Attached test reimplemented in Mobly."""
+import sys
+
+from aware import constants
+
+import aware_lib_utils as autils
+from mobly import asserts
+from mobly import base_test
+from mobly import records
+from mobly import test_runner
+from mobly import utils
+from mobly.controllers import android_device
+
+
+RUNTIME_PERMISSIONS = (
+ 'android.permission.ACCESS_FINE_LOCATION',
+ 'android.permission.ACCESS_COARSE_LOCATION',
+ 'android.permission.NEARBY_WIFI_DEVICES',
+)
+PACKAGE_NAME = constants.WIFI_AWARE_SNIPPET_PACKAGE_NAME
+
+
+class WifiAwareAttachTest(base_test.BaseTestClass):
+ """Wi-Fi Aware Attach test class."""
+
+ ads: list[android_device.AndroidDevice]
+
+ def setup_class(self):
+ # Register two Android devices.
+ self.ads = self.register_controller(android_device, min_number=1)
+
+ def setup_device(device: android_device.AndroidDevice):
+ device.load_snippet('wifi_aware_snippet', PACKAGE_NAME)
+ for permission in RUNTIME_PERMISSIONS:
+ device.adb.shell(['pm', 'grant', PACKAGE_NAME, permission])
+ asserts.abort_all_if(
+ not device.wifi_aware_snippet.wifiAwareIsAvailable(),
+ f'{device} Wi-Fi Aware is not available.',
+ )
+
+ # Set up devices in parallel.
+ utils.concurrent_exec(
+ setup_device,
+ param_list=[[ad] for ad in self.ads],
+ max_workers=1,
+ raise_on_exception=True,
+ )
+
+ def setup_test(self):
+ for ad in self.ads:
+ autils.control_wifi(ad, True)
+ aware_avail = ad.wifi_aware_snippet.wifiAwareIsAvailable()
+ if not aware_avail:
+ ad.log.info('Aware not available. Waiting ...')
+ state_handler = ad.wifi_aware_snippet.wifiAwareMonitorStateChange()
+ state_handler.waitAndGet(constants.WifiAwareBroadcast.WIFI_AWARE_AVAILABLE)
+
+ def teardown_test(self):
+ utils.concurrent_exec(
+ self._teardown_test_on_device,
+ param_list=[[ad] for ad in self.ads],
+ max_workers=1,
+ raise_on_exception=True,
+ )
+ utils.concurrent_exec(
+ lambda d: d.services.create_output_excerpts_all(self.current_test_info),
+ param_list=[[ad] for ad in self.ads],
+ raise_on_exception=True,
+ )
+
+ def _teardown_test_on_device(self, ad: android_device.AndroidDevice) -> None:
+ ad.wifi_aware_snippet.wifiAwareCloseAllWifiAwareSession()
+ ad.wifi_aware_snippet.wifiAwareMonitorStopStateChange()
+ autils.set_airplane_mode(ad, False)
+ autils.control_wifi(ad, True)
+
+ def on_fail(self, record: records.TestResult) -> None:
+ android_device.take_bug_reports(
+ self.ads, destination=self.current_test_info.output_path
+ )
+
+ def test_attach(self) -> None:
+ """Basic attaching request.
+
+ Validates that attaching to the Wi-Fi Aware service works
+ without IdentityChanged callback.
+ """
+ dut = self.ads[0]
+ handler = dut.wifi_aware_snippet.wifiAwareAttached(False)
+ handler.waitAndGet(constants.AttachCallBackMethodType.ATTACHED)
+ autils.callback_no_response(
+ handler, constants.AttachCallBackMethodType.ID_CHANGED
+ )
+
+ def test_attach_with_identity(self) -> None:
+ """Basic attaching request with extra callback.
+
+ Validates that attaching to the Wi-Fi Aware service works
+ with IdentityChanged callback.
+ """
+ dut = self.ads[0]
+ handler = dut.wifi_aware_snippet.wifiAwareAttached(True)
+ handler.waitAndGet(constants.AttachCallBackMethodType.ATTACHED)
+ handler.waitAndGet(constants.AttachCallBackMethodType.ID_CHANGED)
+
+ def test_attach_multiple_sessions(self):
+ """Multiple attaching request.
+
+ Validates that attaching to the Wi-Fi Aware service works with
+ multiple request at same time.
+ """
+ dut = self.ads[0]
+ handler_1 = dut.wifi_aware_snippet.wifiAwareAttached(False)
+ handler_2 = dut.wifi_aware_snippet.wifiAwareAttached(True)
+ handler_3 = dut.wifi_aware_snippet.wifiAwareAttached(False)
+ handler_1.waitAndGet(constants.AttachCallBackMethodType.ATTACHED)
+ autils.callback_no_response(
+ handler_1, constants.AttachCallBackMethodType.ID_CHANGED, 10, True
+ )
+ handler_2.waitAndGet(constants.AttachCallBackMethodType.ATTACHED)
+ handler_2.waitAndGet(constants.AttachCallBackMethodType.ID_CHANGED)
+ handler_3.waitAndGet(constants.AttachCallBackMethodType.ATTACHED)
+ autils.callback_no_response(
+ handler_3, constants.AttachCallBackMethodType.ID_CHANGED, 10, True
+ )
+
+ def test_attach_with_no_wifi(self):
+ """WiFi Aware attempt to attach with wifi off.
+
+ Validates that if trying to attach with Wi-Fi disabled will receive
+ the expected failure callback. As a side-effect also validates that the
+ broadcast for Aware unavailable is received.
+ """
+ dut = self.ads[0]
+ state_handler = dut.wifi_aware_snippet.wifiAwareMonitorStateChange()
+ autils.control_wifi(dut, False)
+ state_handler.waitAndGet(constants.WifiAwareBroadcast.WIFI_AWARE_NOT_AVAILABLE)
+ attach_callback = dut.wifi_aware_snippet.wifiAwareAttached(True)
+ attach_callback.waitAndGet(constants.AttachCallBackMethodType.ATTACH_FAILED)
+ dut.wifi_aware_snippet.wifiAwareMonitorStopStateChange()
+
+ def test_attach_with_location_off(self):
+ """Function/Attach test cases/attempt to attach with location mode off.
+
+ Validates that if trying to attach with device location mode off will
+ receive the expected failure callback. As a side-effect also validates
+ that the broadcast for Aware unavailable is received.
+ """
+ dut = self.ads[0]
+ asserts.skip_if(
+ autils.check_android_os_version(
+ dut, constants.Operator.GREATER_EQUAL, constants.AndroidVersion.T
+ ),
+ 'From T build Aware will not be disabled due to location off',
+ )
+ state_handler = dut.wifi_aware_snippet.wifiAwareMonitorStateChange()
+ dut.adb.shell('settings put secure location_mode 0')
+ state_handler.waitAndGet(constants.WifiAwareBroadcast.WIFI_AWARE_NOT_AVAILABLE)
+ attach_callback = dut.wifi_aware_snippet.wifiAwareAttached(True)
+ attach_callback.waitAndGet(constants.AttachCallBackMethodType.ATTACH_FAILED)
+ dut.adb.shell('settings put secure location_mode 3')
+ state_handler.waitAndGet(constants.WifiAwareBroadcast.WIFI_AWARE_AVAILABLE)
+ dut.wifi_aware_snippet.wifiAwareMonitorStopStateChange()
+
+ def test_attach_apm_toggle_attach_again(self):
+ """Function/Attach test cases/attempt to attach with airplane mode on.
+
+ Validates that enabling Airplane mode while Aware is on resets it
+ correctly, and allows it to be re-enabled when Airplane mode is then
+ disabled.
+ """
+ dut = self.ads[0]
+ asserts.skip_if(
+ not dut.is_adb_root,
+ 'APM toggle needs Android device(s) with root permission',
+ )
+ state_handler = dut.wifi_aware_snippet.wifiAwareMonitorStateChange()
+ attach_callback = dut.wifi_aware_snippet.wifiAwareAttached(True)
+ attach_callback.waitAndGet(constants.AttachCallBackMethodType.ATTACHED)
+ autils.set_airplane_mode(dut, True)
+ if autils.check_android_os_version(
+ dut, constants.Operator.GREATER_EQUAL, constants.AndroidVersion.T
+ ):
+ if not autils._check_wifi_status(dut):
+ return
+ else:
+ autils.control_wifi(dut, False)
+ autils.callback_no_response(
+ state_handler,
+ constants.WifiAwareBroadcast.WIFI_AWARE_AVAILABLE,
+ 10,
+ True,)
+ state_handler.waitAndGet(constants.WifiAwareBroadcast.WIFI_AWARE_NOT_AVAILABLE)
+ autils.set_airplane_mode(dut, False)
+ state_handler.waitAndGet(constants.WifiAwareBroadcast.WIFI_AWARE_AVAILABLE)
+ attach_callback = dut.wifi_aware_snippet.wifiAwareAttached(True)
+ attach_callback.waitAndGet(constants.AttachCallBackMethodType.ATTACHED)
+ dut.wifi_aware_snippet.wifiAwareMonitorStopStateChange()
+
+
+if __name__ == '__main__':
+ # Take test args
+ if '--' in sys.argv:
+ index = sys.argv.index('--')
+ sys.argv = sys.argv[:1] + sys.argv[index + 1 :]
+
+ test_runner.main()
diff --git a/tests/hostsidetests/multidevices/test/aware/wifi_aware_manager_test.py b/tests/hostsidetests/multidevices/test/aware/wifi_aware_manager_test.py
index 6b3f659ac4..42157e767b 100644
--- a/tests/hostsidetests/multidevices/test/aware/wifi_aware_manager_test.py
+++ b/tests/hostsidetests/multidevices/test/aware/wifi_aware_manager_test.py
@@ -109,28 +109,28 @@ class WifiAwareManagerTest(base_test.BaseTestClass):
5. Sends messages between the publisher and subscriber.
6. Creates a Wi-Fi Aware network between the publisher and subscriber.
"""
- utils.concurrent_exec(
- self._start_attach,
- ((self.publisher,), (self.subscriber,)),
- max_workers=2,
- raise_on_exception=True,
- )
+ publisher_attach_session = self._start_attach(self.publisher)
+ subscriber_attach_session = self._start_attach(self.subscriber)
pub_aware_session_cb_handler = self._start_publish(
+ attach_session_id=publisher_attach_session,
publish_type=constants.PublishType.UNSOLICITED,
service_specific_info=_PUB_SSI,
match_filter=_MATCH_FILTER,
is_ranging_enabled=False,
)
+ publish_session = pub_aware_session_cb_handler.callback_id
self.publisher.log.info('Created the publish session.')
sub_aware_session_cb_handler = self._start_subscribe(
+ attach_session_id=subscriber_attach_session,
subscribe_type=constants.SubscribeType.PASSIVE,
match_filter=_MATCH_FILTER,
)
+ subscribe_session = sub_aware_session_cb_handler.callback_id
self.subscriber.log.info('Created the subscribe session.')
# Wait for discovery.
- self._wait_for_discovery(
+ subscriber_peer = self._wait_for_discovery(
sub_aware_session_cb_handler,
pub_service_specific_info=_PUB_SSI,
is_ranging_enabled=False,
@@ -138,11 +138,13 @@ class WifiAwareManagerTest(base_test.BaseTestClass):
self.subscriber.log.info('Discovered the published session.')
# Subscriber sends a message to publisher.
- self._send_msg_and_check_received(
+ publisher_peer = self._send_msg_and_check_received(
sender=self.subscriber,
sender_aware_session_cb_handler=sub_aware_session_cb_handler,
receiver=self.publisher,
receiver_aware_session_cb_handler=pub_aware_session_cb_handler,
+ discovery_session=subscribe_session,
+ peer=subscriber_peer,
send_message=_MSG_SUB_TO_PUB,
send_message_id=_MSG_ID_SUB_TO_PUB,
)
@@ -156,6 +158,8 @@ class WifiAwareManagerTest(base_test.BaseTestClass):
sender_aware_session_cb_handler=pub_aware_session_cb_handler,
receiver=self.subscriber,
receiver_aware_session_cb_handler=sub_aware_session_cb_handler,
+ discovery_session=publish_session,
+ peer=publisher_peer,
send_message=_MSG_PUB_TO_SUB,
send_message_id=_MSG_ID_PUB_TO_SUB,
)
@@ -164,8 +168,12 @@ class WifiAwareManagerTest(base_test.BaseTestClass):
)
# Request network.
- pub_network_cb_handler = self._request_network(ad=self.publisher)
- sub_network_cb_handler = self._request_network(ad=self.subscriber)
+ pub_network_cb_handler = self._request_network(ad=self.publisher,
+ discovery_session=publish_session,
+ peer=publisher_peer,)
+ sub_network_cb_handler = self._request_network(ad=self.subscriber,
+ discovery_session=subscribe_session,
+ peer=subscriber_peer,)
# Wait for network.
self._wait_for_network(
ad=self.publisher,
@@ -177,10 +185,17 @@ class WifiAwareManagerTest(base_test.BaseTestClass):
)
logging.info('Wi-Fi Aware network created successfully.')
- def _start_attach(self, ad: android_device.AndroidDevice) -> None:
+ self.publisher.wifi_aware_snippet.connectivityUnregisterNetwork(pub_network_cb_handler.callback_id)
+ self.subscriber.wifi_aware_snippet.connectivityUnregisterNetwork(sub_network_cb_handler.callback_id)
+ self.publisher.wifi_aware_snippet.wifiAwareCloseDiscoverSession(publish_session)
+ self.subscriber.wifi_aware_snippet.wifiAwareCloseDiscoverSession(subscribe_session)
+ self.publisher.wifi_aware_snippet.wifiAwareDetach(publisher_attach_session)
+ self.subscriber.wifi_aware_snippet.wifiAwareDetach(subscriber_attach_session)
+
+ def _start_attach(self, ad: android_device.AndroidDevice) -> str:
"""Starts the attach process on the provided device."""
handler = ad.wifi_aware_snippet.wifiAwareAttach()
- handler.waitAndGet(
+ attach_event = handler.waitAndGet(
event_name=AttachCallBackMethodType.ATTACHED,
timeout=_DEFAULT_TIMEOUT,
)
@@ -189,10 +204,12 @@ class WifiAwareManagerTest(base_test.BaseTestClass):
f'{ad} attach succeeded, but Wi-Fi Aware session is still null.'
)
ad.log.info('Attach Wi-Fi Aware session succeeded.')
+ return attach_event.callback_id
def _start_publish(
self,
*,
+ attach_session_id,
publish_type,
service_name=constants.WifiAwareTestConstants.SERVICE_NAME,
service_specific_info=constants.WifiAwareTestConstants.PUB_SSI,
@@ -211,7 +228,7 @@ class WifiAwareManagerTest(base_test.BaseTestClass):
# Start the publishing session and return the handler.
publish_handler = self.publisher.wifi_aware_snippet.wifiAwarePublish(
- config.to_dict()
+ attach_session_id, config.to_dict()
)
# Wait for publish session to start.
@@ -236,6 +253,7 @@ class WifiAwareManagerTest(base_test.BaseTestClass):
def _start_subscribe(
self,
*,
+ attach_session_id,
subscribe_type,
service_name=constants.WifiAwareTestConstants.SERVICE_NAME,
service_specific_info=constants.WifiAwareTestConstants.SUB_SSI,
@@ -255,7 +273,7 @@ class WifiAwareManagerTest(base_test.BaseTestClass):
# Start the subscription session and return the handler.
subscribe_handler = self.subscriber.wifi_aware_snippet.wifiAwareSubscribe(
- config.to_dict()
+ attach_session_id, config.to_dict()
)
# Wait for subscribe session to start.
@@ -281,7 +299,7 @@ class WifiAwareManagerTest(base_test.BaseTestClass):
sub_aware_session_cb_handler: callback_handler_v2.CallbackHandlerV2,
pub_service_specific_info: str,
is_ranging_enabled: bool,
- ) -> None:
+ ) -> int:
"""Waits for the subscriber to discover the published service."""
event_name = constants.DiscoverySessionCallbackMethodType.SERVICE_DISCOVERED
if is_ranging_enabled:
@@ -316,6 +334,8 @@ class WifiAwareManagerTest(base_test.BaseTestClass):
f'{self.subscriber} got unexpected match filter data in discovery'
f' callback event "{event_name}".'
)
+ return discover_data.data[constants.WifiAwareSnippetParams.PEER_ID]
+
def _send_msg_and_check_received(
self,
@@ -324,11 +344,13 @@ class WifiAwareManagerTest(base_test.BaseTestClass):
sender_aware_session_cb_handler: callback_handler_v2.CallbackHandlerV2,
receiver: android_device.AndroidDevice,
receiver_aware_session_cb_handler: callback_handler_v2.CallbackHandlerV2,
+ discovery_session: str,
+ peer: int,
send_message: str,
send_message_id: int,
- ):
+ ) -> int:
sender.wifi_aware_snippet.wifiAwareSendMessage(
- send_message_id, send_message
+ discovery_session, peer, send_message_id, send_message
)
message_send_result = sender_aware_session_cb_handler.waitAndGet(
event_name=constants.DiscoverySessionCallbackMethodType.MESSAGE_SEND_RESULT,
@@ -363,14 +385,17 @@ class WifiAwareManagerTest(base_test.BaseTestClass):
send_message,
f'{receiver} received the message but message content mismatched.'
)
+ return receive_message_event.data[constants.WifiAwareSnippetParams.PEER_ID]
def _request_network(
self,
ad: android_device.AndroidDevice,
+ discovery_session: str,
+ peer: int,
) -> callback_handler_v2.CallbackHandlerV2:
"""Requests a Wi-Fi Aware network."""
network_specifier_parcel = (
- ad.wifi_aware_snippet.wifiAwareCreateNetworkSpecifier()
+ ad.wifi_aware_snippet.wifiAwareCreateNetworkSpecifier(discovery_session, peer)
)
network_request_dict = constants.NetworkRequest(
transport_type=_TRANSPORT_TYPE_WIFI_AWARE,
@@ -433,9 +458,7 @@ class WifiAwareManagerTest(base_test.BaseTestClass):
)
def _teardown_test_on_device(self, ad: android_device.AndroidDevice) -> None:
- ad.wifi_aware_snippet.connectivityUnregisterNetwork()
- ad.wifi_aware_snippet.wifiAwareCloseDiscoverSession()
- ad.wifi_aware_snippet.wifiAwareDetach()
+ ad.wifi_aware_snippet.wifiAwareCloseAllWifiAwareSession()
def on_fail(self, record: records.TestResult) -> None:
android_device.take_bug_reports(self.ads, destination=self.current_test_info.output_path)