summaryrefslogtreecommitdiff
path: root/tests/tests/wifi/src/android/net/wifi/aware/cts/SingleDeviceTest.java
blob: 74fdf642e09fd5565574a53f23a1aafd340cb122 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
/*
 * Copyright (C) 2017 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 android.net.wifi.aware.cts;

import static android.Manifest.permission.OVERRIDE_WIFI_CONFIG;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.net.wifi.aware.AwarePairingConfig.PAIRING_BOOTSTRAPPING_OPPORTUNISTIC;
import static android.net.wifi.aware.Characteristics.WIFI_AWARE_CIPHER_SUITE_NCS_PK_PASN_128;
import static android.net.wifi.aware.Characteristics.WIFI_AWARE_CIPHER_SUITE_NCS_PK_PASN_256;
import static android.net.wifi.aware.IdentityChangedListener.CLUSTER_CHANGE_EVENT_JOINED;
import static android.net.wifi.aware.IdentityChangedListener.CLUSTER_CHANGE_EVENT_STARTED;

import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock;

import android.annotation.NonNull;
import android.app.UiAutomation;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.MacAddress;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiScanner;
import android.net.wifi.aware.AttachCallback;
import android.net.wifi.aware.AwarePairingConfig;
import android.net.wifi.aware.AwareParams;
import android.net.wifi.aware.AwareResources;
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.ParcelablePeerHandle;
import android.net.wifi.aware.PeerHandle;
import android.net.wifi.aware.PublishConfig;
import android.net.wifi.aware.PublishDiscoverySession;
import android.net.wifi.aware.ServiceDiscoveryInfo;
import android.net.wifi.aware.SubscribeConfig;
import android.net.wifi.aware.SubscribeDiscoverySession;
import android.net.wifi.aware.WifiAwareDataPathSecurityConfig;
import android.net.wifi.aware.WifiAwareManager;
import android.net.wifi.aware.WifiAwareNetworkSpecifier;
import android.net.wifi.aware.WifiAwareSession;
import android.net.wifi.cts.WifiBuildCompat;
import android.net.wifi.cts.WifiJUnit3TestBase;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Parcel;
import android.platform.test.annotations.AppModeFull;

import androidx.test.filters.SdkSuppress;
import androidx.test.platform.app.InstrumentationRegistry;

import com.android.compatibility.common.util.ApiLevelUtil;
import com.android.compatibility.common.util.ApiTest;
import com.android.compatibility.common.util.ShellIdentityUtils;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

/**
 * Wi-Fi Aware CTS test suite: single device testing. Performs tests on a single
 * device to validate Wi-Fi Aware.
 */
@AppModeFull(reason = "Cannot get WifiAwareManager in instant app mode")
public class SingleDeviceTest extends WifiJUnit3TestBase {
    private static final String TAG = "WifiAwareCtsTests";

    // wait for Wi-Fi Aware state changes & network requests callbacks
    private static final int WAIT_FOR_AWARE_CHANGE_SECS = 15; // 15 seconds
    private static final int WAIT_FOR_NETWORK_STATE_CHANGE_SECS = 25; // 25 seconds
    private static final int INTERVAL_BETWEEN_TESTS_SECS = 3; // 3 seconds
    private static final int WAIT_FOR_AWARE_INTERFACE_CREATION_SEC = 3; // 3 seconds
    private static final int MIN_DISTANCE_MM = 1 * 1000;
    private static final int MAX_DISTANCE_MM = 3 * 1000;
    private static final byte[] PMK_VALID = "01234567890123456789012345678901".getBytes();
    private static final int AVAILABLE_DATA_PATH_COUNT = 2;
    private static final int AVAILABLE_PUBLISH_SESSION_COUNT = 8;
    private static final int AVAILABLE_SUBSCRIBE_SESSION_COUNT = 8;

    private final Object mLock = new Object();
    private final HandlerThread mHandlerThread = new HandlerThread("SingleDeviceTest");
    private final Handler mHandler;
    private Boolean mWasVerboseLoggingEnabled;

    {
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper());
    }

    private WifiAwareManager mWifiAwareManager;
    private WifiManager mWifiManager;
    private WifiManager.WifiLock mWifiLock;
    private ConnectivityManager mConnectivityManager;

    // used to store any WifiAwareSession allocated during tests - will clean-up after tests
    private final List<WifiAwareSession> mSessions = new ArrayList<>();

    private static class WifiAwareStateBroadcastReceiver extends BroadcastReceiver {
        private final Object mLock = new Object();
        private CountDownLatch mBlocker = new CountDownLatch(1);
        private int mCountNumber = 0;

        @Override
        public void onReceive(Context context, Intent intent) {
            if (WifiAwareManager.ACTION_WIFI_AWARE_STATE_CHANGED.equals(intent.getAction())) {
                synchronized(mLock) {
                    mCountNumber += 1;
                    mBlocker.countDown();
                    mBlocker = new CountDownLatch(1);
                }
            }
        }

        boolean waitForStateChange() throws InterruptedException {
            CountDownLatch blocker;
            synchronized (mLock) {
                mCountNumber--;
                if (mCountNumber >= 0) {
                    return true;
                }
                blocker = mBlocker;
            }
            return blocker.await(WAIT_FOR_AWARE_CHANGE_SECS, TimeUnit.SECONDS);
        }
    }

    private static class WifiAwareResourcesBroadcastReceiver extends BroadcastReceiver {
        private final Object mLock = new Object();
        private CountDownLatch mBlocker = new CountDownLatch(1);
        private int mCountNumber = 0;
        private AwareResources mResources = null;

        @Override
        public void onReceive(Context context, Intent intent) {
            if (WifiAwareManager.ACTION_WIFI_AWARE_RESOURCE_CHANGED.equals(intent.getAction())) {
                synchronized (mLock) {
                    mCountNumber += 1;
                    mBlocker.countDown();
                    mBlocker = new CountDownLatch(1);
                    mResources = intent.getParcelableExtra(WifiAwareManager.EXTRA_AWARE_RESOURCES);
                }
            }
        }

        boolean waitForStateChange() throws InterruptedException {
            CountDownLatch blocker;
            synchronized (mLock) {
                mCountNumber--;
                if (mCountNumber >= 0) {
                    return true;
                }
                blocker = mBlocker;
            }
            return blocker.await(WAIT_FOR_AWARE_CHANGE_SECS, TimeUnit.SECONDS);
        }

        public AwareResources getResources() {
            return mResources;
        }
    }

    private class AttachCallbackTest extends AttachCallback {
        static final int ATTACHED = 0;
        static final int ATTACH_FAILED = 1;
        static final int ERROR = 2; // no callback: timeout, interruption
        static final int TERMINATE = 3;

        private CountDownLatch mBlocker = new CountDownLatch(1);
        private int mCallbackCalled = ERROR; // garbage init
        private WifiAwareSession mSession = null;

        @Override
        public void onAttached(WifiAwareSession session) {
            mCallbackCalled = ATTACHED;
            mSession = session;
            synchronized (mLock) {
                mSessions.add(session);
            }
            mBlocker.countDown();
        }

        @Override
        public void onAttachFailed() {
            mCallbackCalled = ATTACH_FAILED;
            mBlocker.countDown();
        }

        @Override
        public void onAwareSessionTerminated() {
            synchronized (mLock) {
                mSessions.remove(mSession);
            }
            mCallbackCalled = TERMINATE;
            mSession = null;
            mBlocker.countDown();
        }

        /**
         * Waits for any of the callbacks to be called - or an error (timeout, interruption).
         * Returns one of the ATTACHED, ATTACH_FAILED, or ERROR values.
         */
        int waitForAnyCallback() {
            try {
                boolean noTimeout = mBlocker.await(WAIT_FOR_AWARE_CHANGE_SECS, TimeUnit.SECONDS);
                mBlocker = new CountDownLatch(1);
                if (noTimeout) {
                    return mCallbackCalled;
                } else {
                    return ERROR;
                }
            } catch (InterruptedException e) {
                return ERROR;
            }
        }

        /**
         * Access the session created by a callback. Only useful to be called after calling
         * waitForAnyCallback() and getting the ATTACHED code back.
         */
        WifiAwareSession getSession() {
            return mSession;
        }
    }

    private static class IdentityChangedListenerTest extends IdentityChangedListener {
        private final CountDownLatch mBlockerIdentityCallback = new CountDownLatch(1);
        private final CountDownLatch mBlockerClusterIdCallback = new CountDownLatch(1);
        private byte[] mMac = null;
        private MacAddress mClusterId = null;
        private int mClusterEventType = -1;

        @Override
        public void onIdentityChanged(byte[] mac) {
            mMac = mac;
            mBlockerIdentityCallback.countDown();
        }

        @Override
        public void onClusterIdChanged(int clusterEventType, MacAddress clusterId) {
            super.onClusterIdChanged(clusterEventType, clusterId);
            mClusterId = clusterId;
            mClusterEventType = clusterEventType;
            mBlockerClusterIdCallback.countDown();
        }

        /**
         * Waits for the listener callback to be called - or an error (timeout, interruption).
         * Returns true on callback called, false on error (timeout, interruption).
         */
        boolean waitForIdentityListener() {
            try {
                return mBlockerIdentityCallback.await(WAIT_FOR_AWARE_CHANGE_SECS, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                return false;
            }
        }

        /**
         * Waits for the listener callback to be called - or an error (timeout, interruption).
         * Returns true on callback called, false on error (timeout, interruption).
         */
        boolean waitForClusterIdListener() {
            try {
                return mBlockerClusterIdCallback.await(WAIT_FOR_AWARE_CHANGE_SECS,
                        TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                return false;
            }
        }

        /**
         * Returns the MAC address of the discovery interface supplied to the triggered callback.
         */
        byte[] getMac() {
            return mMac;
        }

        /**
         * Returns the clusterId of the cluster changes supplied to the triggered callback.
         */
        MacAddress getClusterId() {
            return mClusterId;
        }

        /**
         * Returns the clusterEventType of the cluster changes supplied to the triggered callback.
         */
        int getClusterEventType() {
            return mClusterEventType;
        }
    }

    private static class DiscoverySessionCallbackTest extends DiscoverySessionCallback {
        static final int ON_PUBLISH_STARTED = 0;
        static final int ON_SUBSCRIBE_STARTED = 1;
        static final int ON_SESSION_CONFIG_UPDATED = 2;
        static final int ON_SESSION_CONFIG_FAILED = 3;
        static final int ON_SESSION_TERMINATED = 4;
        static final int ON_SERVICE_DISCOVERED = 5;
        static final int ON_MESSAGE_SEND_SUCCEEDED = 6;
        static final int ON_MESSAGE_SEND_FAILED = 7;
        static final int ON_MESSAGE_RECEIVED = 8;
        static final int ON_SESSION_DISCOVERED_LOST = 9;
        static final int ON_SESSION_SUSPEND_SUCCEEDED = 10;
        static final int ON_SESSION_SUSPEND_FAILED = 11;
        static final int ON_SESSION_RESUME_SUCCEEDED = 12;
        static final int ON_SESSION_RESUME_FAILED = 13;
        static final int ON_PAIRING_SETUP_SUCCEEDED = 14;
        static final int ON_PAIRING_SETUP_FAILED = 15;
        static final int ON_PAIRING_SETUP_REQUEST_RECEIVED = 16;
        static final int ON_PAIRING_VERIFICATION_SUCCEEDED = 17;
        static final int ON_PAIRING_VERIFICATION_FAILED = 18;
        static final int ON_BOOTSTRAPPING_SUCCEEDED = 19;
        static final int ON_BOOTSTRAPPING_FAILED = 20;

        private final Object mLocalLock = new Object();
        private final ArrayDeque<Integer> mCallbackQueue = new ArrayDeque<>();

        private CountDownLatch mBlocker;
        private int mCurrentWaitForCallback;

        private PublishDiscoverySession mPublishDiscoverySession;
        private SubscribeDiscoverySession mSubscribeDiscoverySession;

        private void processCallback(int callback) {
            synchronized (mLocalLock) {
                if (mBlocker != null && mCurrentWaitForCallback == callback) {
                    mBlocker.countDown();
                } else {
                    mCallbackQueue.addLast(callback);
                }
            }
        }

        @Override
        public void onPublishStarted(PublishDiscoverySession session) {
            super.onPublishStarted(session);
            mPublishDiscoverySession = session;
            processCallback(ON_PUBLISH_STARTED);
        }

        @Override
        public void onSubscribeStarted(SubscribeDiscoverySession session) {
            super.onSubscribeStarted(session);
            mSubscribeDiscoverySession = session;
            processCallback(ON_SUBSCRIBE_STARTED);
        }

        @Override
        public void onSessionConfigUpdated() {
            super.onSessionConfigUpdated();
            processCallback(ON_SESSION_CONFIG_UPDATED);
        }

        @Override
        public void onSessionConfigFailed() {
            super.onSessionConfigFailed();
            processCallback(ON_SESSION_CONFIG_FAILED);
        }

        @Override
        public void onSessionTerminated() {
            super.onSessionTerminated();
            processCallback(ON_SESSION_TERMINATED);
        }

        @Override
        public void onSessionSuspendSucceeded() {
            super.onSessionSuspendSucceeded();
            processCallback(ON_SESSION_SUSPEND_SUCCEEDED);
        }

        @Override
        public void onSessionSuspendFailed(int reason) {
            super.onSessionSuspendFailed(reason);
            processCallback(ON_SESSION_SUSPEND_FAILED);
        }

        @Override
        public void onSessionResumeSucceeded() {
            super.onSessionResumeSucceeded();
            processCallback(ON_SESSION_RESUME_SUCCEEDED);
        }

        @Override
        public void onSessionResumeFailed(int reason) {
            super.onSessionResumeFailed(reason);
            processCallback(ON_SESSION_RESUME_FAILED);
        }

        @Override
        public void onServiceDiscovered(PeerHandle peerHandle, byte[] serviceSpecificInfo,
                List<byte[]> matchFilter) {
            super.onServiceDiscovered(peerHandle, serviceSpecificInfo, matchFilter);
            processCallback(ON_SERVICE_DISCOVERED);
        }

        @Override
        public void onServiceDiscovered(ServiceDiscoveryInfo info) {
            super.onServiceDiscovered(info);
            processCallback(ON_SERVICE_DISCOVERED);
        }

        @Override
        public void onMessageSendSucceeded(int messageId) {
            super.onMessageSendSucceeded(messageId);
            processCallback(ON_MESSAGE_SEND_SUCCEEDED);
        }

        @Override
        public void onMessageSendFailed(int messageId) {
            super.onMessageSendFailed(messageId);
            processCallback(ON_MESSAGE_SEND_FAILED);
        }

        @Override
        public void onMessageReceived(PeerHandle peerHandle, byte[] message) {
            super.onMessageReceived(peerHandle, message);
            processCallback(ON_MESSAGE_RECEIVED);
        }

        @Override
        public void onServiceLost(PeerHandle peerHandle, int reason) {
            super.onServiceLost(peerHandle, reason);
            processCallback(ON_SESSION_DISCOVERED_LOST);
        }

        @Override
        public void onPairingSetupRequestReceived(@NonNull PeerHandle peerHandle, int requestId) {
            super.onPairingSetupRequestReceived(peerHandle, requestId);
            processCallback(ON_PAIRING_SETUP_REQUEST_RECEIVED);
        }

        @Override
        public void onPairingSetupSucceeded(@NonNull PeerHandle peerHandle,
                @NonNull String alias) {
            super.onPairingSetupSucceeded(peerHandle, alias);
            processCallback(ON_PAIRING_SETUP_SUCCEEDED);

        }

        @Override
        public void onPairingSetupFailed(@NonNull PeerHandle peerHandle) {
            super.onPairingSetupFailed(peerHandle);
            processCallback(ON_PAIRING_SETUP_FAILED);
        }

        @Override
        public void onPairingVerificationSucceed(@NonNull PeerHandle peerHandle,
                @NonNull String alias) {
            super.onPairingVerificationSucceed(peerHandle, alias);
            processCallback(ON_PAIRING_VERIFICATION_SUCCEEDED);
        }

        @Override
        public void onPairingVerificationFailed(@NonNull PeerHandle peerHandle) {
            super.onPairingVerificationFailed(peerHandle);
            processCallback(ON_PAIRING_VERIFICATION_FAILED);
        }

        @Override
        public void onBootstrappingSucceeded(@NonNull PeerHandle peerHandle, int method) {
            super.onBootstrappingSucceeded(peerHandle, method);
            processCallback(ON_BOOTSTRAPPING_SUCCEEDED);
        }

        @Override
        public void onBootstrappingFailed(@NonNull PeerHandle peerHandle) {
            super.onBootstrappingFailed(peerHandle);
            processCallback(ON_BOOTSTRAPPING_FAILED);
        }

        /**
         * Wait for the specified callback - any of the ON_* constants. Returns a true
         * on success (specified callback triggered) or false on failure (timed-out or
         * interrupted while waiting for the requested callback).
         *
         * Note: other callbacks happening while while waiting for the specified callback will
         * be queued.
         */
        boolean waitForCallback(int callback) {
            return waitForCallback(callback, WAIT_FOR_AWARE_CHANGE_SECS);
        }

        /**
         * Wait for the specified callback - any of the ON_* constants. Returns a true
         * on success (specified callback triggered) or false on failure (timed-out or
         * interrupted while waiting for the requested callback).
         *
         * Same as waitForCallback(int callback) execpt that allows specifying a custom timeout.
         * The default timeout is a short value expected to be sufficient for all behaviors which
         * should happen relatively quickly. Specifying a custom timeout should only be done for
         * those cases which are known to take a specific longer period of time.
         *
         * Note: other callbacks happening while while waiting for the specified callback will
         * be queued.
         */
        boolean waitForCallback(int callback, int timeoutSec) {
            synchronized (mLocalLock) {
                boolean found = mCallbackQueue.remove(callback);
                if (found) {
                    return true;
                }

                mCurrentWaitForCallback = callback;
                mBlocker = new CountDownLatch(1);
            }

            try {
                return mBlocker.await(timeoutSec, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                return false;
            }
        }

        /**
         * Indicates whether the specified callback (any of the ON_* constants) has already
         * happened and in the queue. Useful when the order of events is important.
         */
        boolean hasCallbackAlreadyHappened(int callback) {
            synchronized (mLocalLock) {
                return mCallbackQueue.contains(callback);
            }
        }

        /**
         * Returns the last created publish discovery session.
         */
        PublishDiscoverySession getPublishDiscoverySession() {
            PublishDiscoverySession session = mPublishDiscoverySession;
            mPublishDiscoverySession = null;
            return session;
        }

        /**
         * Returns the last created subscribe discovery session.
         */
        SubscribeDiscoverySession getSubscribeDiscoverySession() {
            SubscribeDiscoverySession session = mSubscribeDiscoverySession;
            mSubscribeDiscoverySession = null;
            return session;
        }
    }

    private static class NetworkCallbackTest extends ConnectivityManager.NetworkCallback {
        private final CountDownLatch mBlocker = new CountDownLatch(1);

        @Override
        public void onUnavailable() {
            mBlocker.countDown();
        }

        /**
         * Wait for the onUnavailable() callback to be triggered. Returns true if triggered,
         * otherwise (timed-out, interrupted) returns false.
         */
        boolean waitForOnUnavailable() {
            try {
                return mBlocker.await(WAIT_FOR_NETWORK_STATE_CHANGE_SECS, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                return false;
            }
        }
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }

        assertTrue("Wi-Fi Aware requires Location to be Enabled",
                ((LocationManager) getContext().getSystemService(
                        Context.LOCATION_SERVICE)).isLocationEnabled());

        mWifiAwareManager = (WifiAwareManager) getContext().getSystemService(
                Context.WIFI_AWARE_SERVICE);
        assertNotNull("Wi-Fi Aware Manager", mWifiAwareManager);

        mWifiManager = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
        assertNotNull("Wi-Fi Manager", mWifiManager);

        // turn on verbose logging for tests
        mWasVerboseLoggingEnabled = ShellIdentityUtils.invokeWithShellPermissions(
                () -> mWifiManager.isVerboseLoggingEnabled());
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> mWifiManager.setVerboseLoggingEnabled(true));

        // Turn on Wi-Fi
        mWifiLock = mWifiManager.createWifiLock(TAG);
        mWifiLock.acquire();
        if (!mWifiManager.isWifiEnabled()) {
            ShellIdentityUtils.invokeWithShellPermissions(() -> mWifiManager.setWifiEnabled(true));
        }

        mConnectivityManager = (ConnectivityManager) getContext().getSystemService(
                Context.CONNECTIVITY_SERVICE);
        assertNotNull("Connectivity Manager", mConnectivityManager);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiAwareManager.ACTION_WIFI_AWARE_STATE_CHANGED);
        WifiAwareStateBroadcastReceiver receiver = new WifiAwareStateBroadcastReceiver();
        mContext.registerReceiver(receiver, intentFilter);
        if (!mWifiAwareManager.isAvailable()) {
            assertTrue("Timeout waiting for Wi-Fi Aware to change status",
                    receiver.waitForStateChange());
            assertTrue("Wi-Fi Aware is not available (should be)", mWifiAwareManager.isAvailable());
        }
    }

    @Override
    protected void tearDown() throws Exception {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            super.tearDown();
            return;
        }

        synchronized (mLock) {
            for (WifiAwareSession session : mSessions) {
                // no damage from destroying twice (i.e. ok if test cleaned up after itself already)
                session.close();
            }
            mSessions.clear();
        }

        ShellIdentityUtils.invokeWithShellPermissions(
                () -> mWifiManager.setVerboseLoggingEnabled(mWasVerboseLoggingEnabled));

        super.tearDown();
        Thread.sleep(INTERVAL_BETWEEN_TESTS_SECS * 1000);
    }

    /**
     * Validate:
     * - Characteristics are available
     * - Characteristics values are legitimate. Not in the CDD. However, the tested values are
     *   based on the Wi-Fi Aware protocol.
     */
    public void testCharacteristics() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }

        Characteristics characteristics = mWifiAwareManager.getCharacteristics();
        assertNotNull("Wi-Fi Aware characteristics are null", characteristics);
        assertEquals("Service Name Length", characteristics.getMaxServiceNameLength(), 255);
        assertEquals("Service Specific Information Length",
                characteristics.getMaxServiceSpecificInfoLength(), 255);
        assertEquals("Match Filter Length", characteristics.getMaxMatchFilterLength(), 255);
        assertNotEquals("Cipher suites", characteristics.getSupportedCipherSuites(), 0);
        assertTrue("Max number of NDP", characteristics.getNumberOfSupportedDataPaths() > 0);
        assertTrue("Max number of NDI", characteristics.getNumberOfSupportedDataInterfaces() > 0);
        assertTrue("Max number of Publish sessions",
                characteristics.getNumberOfSupportedPublishSessions() > 0);
        assertTrue("Max number of Subscribe sessions",
                characteristics.getNumberOfSupportedSubscribeSessions() > 0);
        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.S)) {
            ShellIdentityUtils.invokeWithShellPermissions(() ->
                    mWifiAwareManager.enableInstantCommunicationMode(true));
            assertEquals(mWifiAwareManager.isInstantCommunicationModeEnabled(),
                    characteristics.isInstantCommunicationModeSupported());
            ShellIdentityUtils.invokeWithShellPermissions(() ->
                    mWifiAwareManager.enableInstantCommunicationMode(false));
        }
        if (characteristics.isAwarePairingSupported()) {
            assertTrue(((characteristics.getSupportedPairingCipherSuites()
                    & WIFI_AWARE_CIPHER_SUITE_NCS_PK_PASN_128) != 0)
                    || ((characteristics.getSupportedPairingCipherSuites()
                    & WIFI_AWARE_CIPHER_SUITE_NCS_PK_PASN_256) != 0));
        }
    }

    /**
     * Validate:
     * - AwareResources are available
     * - AwareResources values are legitimate. When no resources are used, the value should equal to
     *   the capability.
     */
    public void testAvailableAwareResources() {
        if (!(TestUtils.shouldTestWifiAware(getContext())
                && WifiBuildCompat.isPlatformOrWifiModuleAtLeastS(getContext()))) {
            return;
        }
        AwareResources resources = mWifiAwareManager.getAvailableAwareResources();
        assertNotNull("Available aware resources are null", resources);
        assertTrue(resources.getAvailableDataPathsCount() > 0);
        assertTrue(resources.getAvailablePublishSessionsCount() > 0);
        assertTrue(resources.getAvailableSubscribeSessionsCount() > 0);
    }

    /**
     * Validate that on Wi-Fi Aware availability change we get a broadcast + the API returns
     * correct status.
     */
    public void testAvailabilityStatusChange() throws Exception {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiAwareManager.ACTION_WIFI_AWARE_STATE_CHANGED);

        // 1. Disable Wi-Fi
        WifiAwareStateBroadcastReceiver receiver1 = new WifiAwareStateBroadcastReceiver();
        mContext.registerReceiver(receiver1, intentFilter);
        ShellIdentityUtils.invokeWithShellPermissions(() -> mWifiManager.setWifiEnabled(false));

        assertTrue("Timeout waiting for Wi-Fi Aware to change status",
                receiver1.waitForStateChange());
        // Interface down event may happen before Wifi State change. In that case, Aware available
        // state will keep true for a short time.
        if (mWifiAwareManager.isAvailable()) {
            assertTrue("Timeout waiting for Wi-Fi Aware to change status",
                    receiver1.waitForStateChange());
        }
        assertFalse("Wi-Fi Aware is available (should not be)", mWifiAwareManager.isAvailable());

        // 2. Enable Wi-Fi
        WifiAwareStateBroadcastReceiver receiver2 = new WifiAwareStateBroadcastReceiver();
        mContext.registerReceiver(receiver2, intentFilter);
        ShellIdentityUtils.invokeWithShellPermissions(() -> mWifiManager.setWifiEnabled(true));

        assertTrue("Timeout waiting for Wi-Fi Aware to change status",
                receiver2.waitForStateChange());
        assertTrue("Wi-Fi Aware is not available (should be)", mWifiAwareManager.isAvailable());
    }

    /**
     * Validate that can attach to Wi-Fi Aware.
     */
    public void testAttachNoIdentity() throws InterruptedException {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }

        AttachCallbackTest callback = attachAndGetCallback();
        callback.getSession().close();
        callback.waitForAnyCallback();
        assertNull(callback.getSession());
        if (WifiBuildCompat.isPlatformOrWifiModuleAtLeastS(getContext())) {
            Thread.sleep(WAIT_FOR_AWARE_INTERFACE_CREATION_SEC * 1000);
            assertFalse(mWifiAwareManager.isDeviceAttached());
        }
    }

    /**
     * Validate that can attach to Wi-Fi Aware and get identity information. Use the identity
     * information to validate that MAC address changes on every attach.
     *
     * Note: relies on no other entity using Wi-Fi Aware during the CTS test. Since if it is used
     * then the attach/destroy will not correspond to enable/disable and will not result in a new
     * MAC address being generated.
     */
    public void testAttachDiscoveryAddressChanges() throws InterruptedException {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }

        final int numIterations = 10;
        Set<TestUtils.MacWrapper> macs = new HashSet<>();

        for (int i = 0; i < numIterations; ++i) {
            Thread.sleep(1000);
            AttachCallbackTest attachCb = new AttachCallbackTest();
            IdentityChangedListenerTest identityL = new IdentityChangedListenerTest();
            mWifiAwareManager.attach(attachCb, identityL, mHandler);
            assertEquals("Wi-Fi Aware attach: iteration " + i, AttachCallbackTest.ATTACHED,
                    attachCb.waitForAnyCallback());
            assertTrue("Wi-Fi Aware attach: iteration " + i, identityL.waitForClusterIdListener());
            assertTrue("Wi-Fi Aware attach: iteration " + i, identityL.waitForIdentityListener());

            WifiAwareSession session = attachCb.getSession();
            assertNotNull("Wi-Fi Aware session: iteration " + i, session);

            MacAddress clusterId = identityL.getClusterId();
            assertNotNull("Wi-Fi Aware cluster ID: iteration " + i, clusterId);
            int clusterEventType = identityL.getClusterEventType();
            if (clusterEventType != CLUSTER_CHANGE_EVENT_STARTED
                    && clusterEventType != CLUSTER_CHANGE_EVENT_JOINED) {
                fail("Wi-Fi Aware cluster event type: iteration " + i
                        + ", invalid cluster event type");
            }
            byte[] mac = identityL.getMac();
            assertNotNull("Wi-Fi Aware discovery MAC: iteration " + i, mac);

            session.close();

            macs.add(new TestUtils.MacWrapper(mac));
        }

        assertEquals("", numIterations, macs.size());
    }

    /**
     * Validate a successful publish discovery session lifetime: publish, update publish, destroy.
     */
    public void testPublishDiscoverySuccess() throws Exception {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiAwareManager.ACTION_WIFI_AWARE_RESOURCE_CHANGED);
        WifiAwareResourcesBroadcastReceiver receiver = new WifiAwareResourcesBroadcastReceiver();
        mContext.registerReceiver(receiver, intentFilter);
        final String serviceName = "PublishName";

        WifiAwareSession session = attachAndGetSession();

        PublishConfig publishConfig = new PublishConfig.Builder().setServiceName(
                serviceName).build();
        DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();
        int numOfAllPublishSessions = mWifiAwareManager
                .getAvailableAwareResources().getAvailablePublishSessionsCount();

        // 1. publish
        session.publish(publishConfig, discoveryCb, mHandler);
        assertTrue("Publish started",
                discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_PUBLISH_STARTED));
        PublishDiscoverySession discoverySession = discoveryCb.getPublishDiscoverySession();
        assertNotNull("Publish session", discoverySession);
        assertFalse(discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SERVICE_DISCOVERED));
        assertFalse(discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SESSION_DISCOVERED_LOST));
        assertEquals(numOfAllPublishSessions - 1, mWifiAwareManager
                    .getAvailableAwareResources().getAvailablePublishSessionsCount());
        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
            assertTrue("Time out waiting for resource change", receiver.waitForStateChange());
            assertEquals(numOfAllPublishSessions - 1, receiver.getResources()
                    .getAvailablePublishSessionsCount());
        }

        // 2. update-publish
        publishConfig = new PublishConfig.Builder().setServiceName(
                serviceName).setServiceSpecificInfo("extras".getBytes()).build();
        discoverySession.updatePublish(publishConfig);
        assertTrue("Publish update", discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SESSION_CONFIG_UPDATED));

        // 3. destroy
        assertFalse("Publish not terminated", discoveryCb.hasCallbackAlreadyHappened(
                DiscoverySessionCallbackTest.ON_SESSION_TERMINATED));
        discoverySession.close();

        // 4. try update post-destroy: should time-out waiting for cb
        discoverySession.updatePublish(publishConfig);
        assertFalse("Publish update post destroy", discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SESSION_CONFIG_UPDATED));
        assertEquals(numOfAllPublishSessions, mWifiAwareManager
                .getAvailableAwareResources().getAvailablePublishSessionsCount());
        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
            assertTrue("Time out waiting for resource change", receiver.waitForStateChange());
            assertEquals(numOfAllPublishSessions, receiver.getResources()
                    .getAvailablePublishSessionsCount());
            session.close();
        }
    }

    /**
     * Validate that publish with a Time To Live (TTL) setting expires within the specified
     * time (and validates that the terminate callback is triggered).
     */
    public void testPublishLimitedTtlSuccess() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }

        final String serviceName = "PublishName";
        final int ttlSec = 5;

        WifiAwareSession session = attachAndGetSession();

        PublishConfig publishConfig = new PublishConfig.Builder().setServiceName(
                serviceName).setTtlSec(ttlSec).setTerminateNotificationEnabled(true).build();
        DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();

        // 1. publish
        session.publish(publishConfig, discoveryCb, mHandler);
        assertTrue("Publish started",
                discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_PUBLISH_STARTED));
        PublishDiscoverySession discoverySession = discoveryCb.getPublishDiscoverySession();
        assertNotNull("Publish session", discoverySession);

        // 2. wait for terminate within 'ttlSec'.
        assertTrue("Publish terminated",
                discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_SESSION_TERMINATED,
                        ttlSec + 5));

        // 3. try update post-termination: should time-out waiting for cb
        publishConfig = new PublishConfig.Builder().setServiceName(
                serviceName).setServiceSpecificInfo("extras".getBytes()).build();
        discoverySession.updatePublish(publishConfig);
        assertFalse("Publish update post terminate", discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SESSION_CONFIG_UPDATED));

        session.close();
    }

    /**
     * Validate successful publish session with security config.
     */
    public void testPublishWithSecurityConfig() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }

        final String serviceName = "PublishName";
        final String passphrase = "SomePassword";
        final byte[] pmk = "01234567890123456789012345678901".getBytes();
        final byte[] pmkId = "0123456789012345".getBytes();


        WifiAwareSession session = attachAndGetSession();
        WifiAwareDataPathSecurityConfig securityConfig = new WifiAwareDataPathSecurityConfig
                .Builder(Characteristics.WIFI_AWARE_CIPHER_SUITE_NCS_SK_128)
                .setPskPassphrase(passphrase)
                .build();
        assertEquals(passphrase, securityConfig.getPskPassphrase());
        assertEquals(Characteristics.WIFI_AWARE_CIPHER_SUITE_NCS_SK_128,
                securityConfig.getCipherSuite());
        assertNull(securityConfig.getPmkId());
        assertNull(securityConfig.getPmk());

        PublishConfig.Builder builder = new PublishConfig.Builder()
                .setServiceName(serviceName)
                .setDataPathSecurityConfig(securityConfig);
        PublishConfig publishConfig = builder.build();
        assertEquals(securityConfig, publishConfig.getSecurityConfig());
        DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();

        // 1. publish
        session.publish(publishConfig, discoveryCb, mHandler);
        assertTrue("Publish started",
                discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_PUBLISH_STARTED));
        PublishDiscoverySession discoverySession = discoveryCb.getPublishDiscoverySession();
        assertNotNull("Publish session", discoverySession);
        assertFalse(discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SERVICE_DISCOVERED));
        assertFalse(discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SESSION_DISCOVERED_LOST));

        // 2. update to PK cipher suite
        if ((mWifiAwareManager.getCharacteristics().getSupportedCipherSuites()
                & Characteristics.WIFI_AWARE_CIPHER_SUITE_NCS_PK_128) != 0) {
            securityConfig = new WifiAwareDataPathSecurityConfig
                    .Builder(Characteristics.WIFI_AWARE_CIPHER_SUITE_NCS_PK_128)
                    .setPmk(pmk)
                    .setPmkId(pmkId)
                    .build();
            publishConfig = new PublishConfig.Builder()
                    .setServiceName(serviceName)
                    .setDataPathSecurityConfig(securityConfig)
                    .build();
            discoverySession.updatePublish(publishConfig);
            assertTrue("Publish update", discoveryCb.waitForCallback(
                    DiscoverySessionCallbackTest.ON_SESSION_CONFIG_UPDATED));
        }

        // 3. destroy
        assertFalse("Publish not terminated", discoveryCb.hasCallbackAlreadyHappened(
                DiscoverySessionCallbackTest.ON_SESSION_TERMINATED));
        discoverySession.close();
        session.close();
    }

    /**
     * Validate success publish with instant communacation enabled.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    public void testPublishWithInstantCommunicationModeSuccess() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        Characteristics characteristics = mWifiAwareManager.getCharacteristics();
        if (!characteristics.isInstantCommunicationModeSupported()) {
            return;
        }
        final String serviceName = "PublishName";
        WifiAwareSession session = attachAndGetSession();

        PublishConfig publishConfig = new PublishConfig.Builder()
                .setServiceName(serviceName)
                .setInstantCommunicationModeEnabled(true, WifiScanner.WIFI_BAND_24_GHZ)
                .build();
        assertEquals(WifiScanner.WIFI_BAND_24_GHZ, publishConfig.getInstantCommunicationBand());
        assertTrue(publishConfig.isInstantCommunicationModeEnabled());

        DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();

        // 1. publish
        session.publish(publishConfig, discoveryCb, mHandler);
        assertTrue("Publish started",
                discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_PUBLISH_STARTED));
        PublishDiscoverySession discoverySession = discoveryCb.getPublishDiscoverySession();
        assertNotNull("Publish session", discoverySession);
        assertFalse(discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SERVICE_DISCOVERED));
        assertFalse(discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SESSION_DISCOVERED_LOST));

        // 2. destroy
        assertFalse("Publish not terminated", discoveryCb.hasCallbackAlreadyHappened(
                DiscoverySessionCallbackTest.ON_SESSION_TERMINATED));
        discoverySession.close();
        session.close();
    }

    /**
     * Validate successful publish with a suspendable session when device supports suspension.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    public void testPublishSuccessWithSuspendableSession() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        Characteristics characteristics = mWifiAwareManager.getCharacteristics();
        if (!characteristics.isSuspensionSupported()) {
            return;
        }
        final String serviceName = "PublishName";

        ShellIdentityUtils.invokeWithShellPermissions(() -> {
            WifiAwareSession session = attachAndGetSession();

            PublishConfig publishConfig = new PublishConfig.Builder()
                    .setServiceName(serviceName)
                    .setSuspendable(true)
                    .build();
            assertTrue(publishConfig.isSuspendable());

            DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();

            // 1. publish
            session.publish(publishConfig, discoveryCb, mHandler);
            assertTrue("Publish started",
                    discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_PUBLISH_STARTED));
            PublishDiscoverySession discoverySession = discoveryCb.getPublishDiscoverySession();
            assertNotNull("Publish session", discoverySession);
            assertFalse(discoveryCb.waitForCallback(
                    DiscoverySessionCallbackTest.ON_SERVICE_DISCOVERED));
            assertFalse(discoveryCb.waitForCallback(
                    DiscoverySessionCallbackTest.ON_SESSION_DISCOVERED_LOST));

            // 2. destroy
            assertFalse("Publish not terminated", discoveryCb.hasCallbackAlreadyHappened(
                    DiscoverySessionCallbackTest.ON_SESSION_TERMINATED));
            discoverySession.close();
            session.close();
        });
    }

    /**
     * Validate failure to publish with a suspendable session when device doesn't support
     * suspension.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    public void testPublishFailureWithSuspendableSession() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        Characteristics characteristics = mWifiAwareManager.getCharacteristics();
        if (characteristics.isSuspensionSupported()) {
            return;
        }
        final String serviceName = "PublishName";

        ShellIdentityUtils.invokeWithShellPermissions(() -> {
            WifiAwareSession session = attachAndGetSession();

            assertThrows(IllegalArgumentException.class, () -> {
                PublishConfig publishConfig = new PublishConfig.Builder()
                        .setServiceName(serviceName)
                        .setSuspendable(true)
                        .build();
                assertTrue(publishConfig.isSuspendable());

                DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();
                session.publish(publishConfig, discoveryCb, mHandler);
            });

            session.close();
        });
    }

    /**
     * Validate successful suspend/resume with a publish session.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    @ApiTest(apis = {"android.net.wifi.aware.DiscoverySession#suspend",
            "android.net.wifi.aware.DiscoverySession#resume"})
    public void testSuspendResumeFailWithoutNdpOnPublishSession() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        Characteristics characteristics = mWifiAwareManager.getCharacteristics();
        if (!characteristics.isSuspensionSupported()) {
            return;
        }
        final String serviceName = "PublishName";

        ShellIdentityUtils.invokeWithShellPermissions(() -> {
            WifiAwareSession session = attachAndGetSession();

            PublishConfig publishConfig = new PublishConfig.Builder()
                    .setServiceName(serviceName)
                    .setSuspendable(true)
                    .build();
            assertTrue(publishConfig.isSuspendable());

            DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();

            // 1. publish
            session.publish(publishConfig, discoveryCb, mHandler);
            assertTrue("Publish started",
                    discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_PUBLISH_STARTED));
            PublishDiscoverySession discoverySession = discoveryCb.getPublishDiscoverySession();
            assertNotNull("Publish session", discoverySession);
            assertFalse(discoveryCb.waitForCallback(
                    DiscoverySessionCallbackTest.ON_SERVICE_DISCOVERED));
            assertFalse(discoveryCb.waitForCallback(
                    DiscoverySessionCallbackTest.ON_SESSION_DISCOVERED_LOST));

            // 2. suspend
            discoverySession.suspend();
            assertTrue(discoveryCb.waitForCallback(
                    DiscoverySessionCallbackTest.ON_SESSION_SUSPEND_FAILED));

            // 3. resume
            discoverySession.resume();
            assertTrue(discoveryCb.waitForCallback(
                    DiscoverySessionCallbackTest.ON_SESSION_RESUME_FAILED));

            // 4. destroy
            assertFalse("Publish not terminated", discoveryCb.hasCallbackAlreadyHappened(
                    DiscoverySessionCallbackTest.ON_SESSION_TERMINATED));
            discoverySession.close();

            // 5. try suspend/resume post-destroy: should throw exception
            assertThrows(IllegalStateException.class, discoverySession::suspend);
            assertThrows(IllegalStateException.class, discoverySession::resume);

            session.close();
        });
    }

    /**
     * Validate a successful subscribe discovery session lifetime: subscribe, update subscribe,
     * destroy.
     */
    public void testSubscribeDiscoverySuccess() throws Exception {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiAwareManager.ACTION_WIFI_AWARE_RESOURCE_CHANGED);
        WifiAwareResourcesBroadcastReceiver receiver = new WifiAwareResourcesBroadcastReceiver();
        mContext.registerReceiver(receiver, intentFilter);
        final String serviceName = "SubscribeName";

        WifiAwareSession session = attachAndGetSession();

        SubscribeConfig subscribeConfig = new SubscribeConfig.Builder().setServiceName(
                serviceName).build();
        DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();
        int numOfAllSubscribeSessions = mWifiAwareManager
                .getAvailableAwareResources().getAvailableSubscribeSessionsCount();
        // 1. subscribe
        session.subscribe(subscribeConfig, discoveryCb, mHandler);
        assertTrue("Subscribe started",
                discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_SUBSCRIBE_STARTED));
        SubscribeDiscoverySession discoverySession = discoveryCb.getSubscribeDiscoverySession();
        assertNotNull("Subscribe session", discoverySession);
        assertFalse(discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SERVICE_DISCOVERED));
        assertFalse(discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SESSION_DISCOVERED_LOST));
        assertEquals(numOfAllSubscribeSessions - 1, mWifiAwareManager
                .getAvailableAwareResources().getAvailableSubscribeSessionsCount());
        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
            assertTrue("Time out waiting for resource change", receiver.waitForStateChange());
            assertEquals(numOfAllSubscribeSessions - 1, receiver.getResources()
                    .getAvailableSubscribeSessionsCount());
        }

        // 2. update-subscribe
        boolean rttSupported = getContext().getPackageManager().hasSystemFeature(
                    PackageManager.FEATURE_WIFI_RTT);
        SubscribeConfig.Builder builder = new SubscribeConfig.Builder().setServiceName(
                    serviceName).setServiceSpecificInfo("extras".getBytes());

        if (rttSupported) {
            builder.setMinDistanceMm(MIN_DISTANCE_MM);
        }
        subscribeConfig = builder.build();

        discoverySession.updateSubscribe(subscribeConfig);
        assertTrue("Subscribe update", discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SESSION_CONFIG_UPDATED));

        // 3. destroy
        assertFalse("Subscribe not terminated", discoveryCb.hasCallbackAlreadyHappened(
                DiscoverySessionCallbackTest.ON_SESSION_TERMINATED));
        discoverySession.close();

        // 4. try update post-destroy: should time-out waiting for cb
        discoverySession.updateSubscribe(subscribeConfig);
        assertFalse("Subscribe update post destroy", discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SESSION_CONFIG_UPDATED));
        assertEquals(numOfAllSubscribeSessions, mWifiAwareManager
                .getAvailableAwareResources().getAvailableSubscribeSessionsCount());
        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
            assertTrue("Time out waiting for resource change", receiver.waitForStateChange());
            assertEquals(numOfAllSubscribeSessions, receiver.getResources()
                    .getAvailableSubscribeSessionsCount());
        }

        session.close();
    }

    /**
     * Validate success subscribe with instant communication enabled.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    public void testSubscribeWithInstantCommunicationModeSuccess() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        Characteristics characteristics = mWifiAwareManager.getCharacteristics();
        if (!characteristics.isInstantCommunicationModeSupported()) {
            return;
        }
        final String serviceName = "SubscribeName";
        WifiAwareSession session = attachAndGetSession();

        SubscribeConfig subscribeConfig = new SubscribeConfig.Builder()
                .setServiceName(serviceName)
                .setInstantCommunicationModeEnabled(true, WifiScanner.WIFI_BAND_24_GHZ)
                .build();

        assertEquals(WifiScanner.WIFI_BAND_24_GHZ, subscribeConfig.getInstantCommunicationBand());
        assertTrue(subscribeConfig.isInstantCommunicationModeEnabled());

        DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();

        // 1. subscribe
        session.subscribe(subscribeConfig, discoveryCb, mHandler);
        assertTrue("Subscribe started",
                discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_SUBSCRIBE_STARTED));
        SubscribeDiscoverySession discoverySession = discoveryCb.getSubscribeDiscoverySession();
        assertNotNull("Subscribe session", discoverySession);
        assertFalse(discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SERVICE_DISCOVERED));
        assertFalse(discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SESSION_DISCOVERED_LOST));

        // 2. destroy
        assertFalse("Subscribe not terminated", discoveryCb.hasCallbackAlreadyHappened(
                DiscoverySessionCallbackTest.ON_SESSION_TERMINATED));
        discoverySession.close();
        session.close();
    }

    /**
     * Validate that subscribe with a Time To Live (TTL) setting expires within the specified
     * time (and validates that the terminate callback is triggered).
     */
    public void testSubscribeLimitedTtlSuccess() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }

        final String serviceName = "SubscribeName";
        final int ttlSec = 5;

        WifiAwareSession session = attachAndGetSession();

        SubscribeConfig subscribeConfig = new SubscribeConfig.Builder().setServiceName(
                serviceName).setTtlSec(ttlSec).setTerminateNotificationEnabled(true).build();
        DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();

        // 1. subscribe
        session.subscribe(subscribeConfig, discoveryCb, mHandler);
        assertTrue("Subscribe started",
                discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_SUBSCRIBE_STARTED));
        SubscribeDiscoverySession discoverySession = discoveryCb.getSubscribeDiscoverySession();
        assertNotNull("Subscribe session", discoverySession);

        // 2. wait for terminate within 'ttlSec'.
        assertTrue("Subscribe terminated",
                discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_SESSION_TERMINATED,
                        ttlSec + 5));

        // 3. try update post-termination: should time-out waiting for cb
        subscribeConfig = new SubscribeConfig.Builder().setServiceName(
                serviceName).setServiceSpecificInfo("extras".getBytes()).build();
        discoverySession.updateSubscribe(subscribeConfig);
        assertFalse("Subscribe update post terminate", discoveryCb.waitForCallback(
                DiscoverySessionCallbackTest.ON_SESSION_CONFIG_UPDATED));

        session.close();
    }

    /**
     * Validate successful subscribe with a suspendable session when device supports suspension.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    public void testSubscribeSuccessWithSuspendableSession() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        Characteristics characteristics = mWifiAwareManager.getCharacteristics();
        if (!characteristics.isSuspensionSupported()) {
            return;
        }
        final String serviceName = "SubscribeName";

        ShellIdentityUtils.invokeWithShellPermissions(() -> {
            WifiAwareSession session = attachAndGetSession();

            SubscribeConfig subscribeConfig = new SubscribeConfig.Builder()
                    .setServiceName(serviceName)
                    .setSuspendable(true)
                    .build();

            assertTrue(subscribeConfig.isSuspendable());

            DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();

            // 1. subscribe
            session.subscribe(subscribeConfig, discoveryCb, mHandler);
            assertTrue("Subscribe started",
                    discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_SUBSCRIBE_STARTED));
            SubscribeDiscoverySession discoverySession = discoveryCb.getSubscribeDiscoverySession();
            assertNotNull("Subscribe session", discoverySession);
            assertFalse(discoveryCb.waitForCallback(
                    DiscoverySessionCallbackTest.ON_SERVICE_DISCOVERED));
            assertFalse(discoveryCb.waitForCallback(
                    DiscoverySessionCallbackTest.ON_SESSION_DISCOVERED_LOST));

            // 2. destroy
            assertFalse("Subscribe not terminated", discoveryCb.hasCallbackAlreadyHappened(
                    DiscoverySessionCallbackTest.ON_SESSION_TERMINATED));
            discoverySession.close();
            session.close();
        });
    }

    /**
     * Validate failure to subscribe with a suspendable session when device doesn't support
     * suspension.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    public void testSubscribeFailureWithSuspendableSession() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        Characteristics characteristics = mWifiAwareManager.getCharacteristics();
        if (characteristics.isSuspensionSupported()) {
            return;
        }
        final String serviceName = "SubscribeName";

        ShellIdentityUtils.invokeWithShellPermissions(() -> {
            WifiAwareSession session = attachAndGetSession();

            assertThrows(IllegalArgumentException.class, () -> {
                SubscribeConfig subscribeConfig = new SubscribeConfig.Builder()
                        .setServiceName(serviceName)
                        .setSuspendable(true)
                        .build();

                assertTrue(subscribeConfig.isSuspendable());

                DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();
                session.subscribe(subscribeConfig, discoveryCb, mHandler);
            });

            session.close();
        });
    }

    /**
     * Validate successful suspend/resume with a subscribe session.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    @ApiTest(apis = {"android.net.wifi.aware.DiscoverySession#suspend",
            "android.net.wifi.aware.DiscoverySession#resume"})
    public void testSuspendResumeFailWithoutNdpOnSubscribeSession() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        Characteristics characteristics = mWifiAwareManager.getCharacteristics();
        if (!characteristics.isSuspensionSupported()) {
            return;
        }
        final String serviceName = "SubscribeName";

        ShellIdentityUtils.invokeWithShellPermissions(() -> {
            WifiAwareSession session = attachAndGetSession();

            SubscribeConfig subscribeConfig = new SubscribeConfig.Builder()
                    .setServiceName(serviceName)
                    .setSuspendable(true)
                    .build();

            assertTrue(subscribeConfig.isSuspendable());

            DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();

            // 1. subscribe
            session.subscribe(subscribeConfig, discoveryCb, mHandler);
            assertTrue("Subscribe started",
                    discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_SUBSCRIBE_STARTED));
            SubscribeDiscoverySession discoverySession = discoveryCb.getSubscribeDiscoverySession();
            assertNotNull("Subscribe session", discoverySession);
            assertFalse(discoveryCb.waitForCallback(
                    DiscoverySessionCallbackTest.ON_SERVICE_DISCOVERED));
            assertFalse(discoveryCb.waitForCallback(
                    DiscoverySessionCallbackTest.ON_SESSION_DISCOVERED_LOST));

            // 2. suspend
            discoverySession.suspend();
            assertTrue(discoveryCb.waitForCallback(
                    DiscoverySessionCallbackTest.ON_SESSION_SUSPEND_FAILED));

            // 3. resume
            discoverySession.resume();
            assertTrue(discoveryCb.waitForCallback(
                    DiscoverySessionCallbackTest.ON_SESSION_RESUME_FAILED));

            // 4. destroy
            assertFalse("Subscribe not terminated", discoveryCb.hasCallbackAlreadyHappened(
                    DiscoverySessionCallbackTest.ON_SESSION_TERMINATED));
            discoverySession.close();

            // 5. try suspend/resume post-destroy: should throw exception
            assertThrows(IllegalStateException.class, discoverySession::suspend);
            assertThrows(IllegalStateException.class, discoverySession::resume);

            session.close();
        });
    }

    /**
     * Test the send message flow. Since testing single device cannot send to a real peer -
     * validate that sending to a bogus peer fails.
     */
    public void testSendMessageFail() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }

        WifiAwareSession session = attachAndGetSession();

        PublishConfig publishConfig = new PublishConfig.Builder().setServiceName(
                "ValidName").build();
        DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();

        // 1. publish
        session.publish(publishConfig, discoveryCb, mHandler);
        assertTrue("Publish started",
                discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_PUBLISH_STARTED));
        PublishDiscoverySession discoverySession = discoveryCb.getPublishDiscoverySession();
        assertNotNull("Publish session", discoverySession);

        // 2. send a message with a null peer-handle - expect exception
        try {
            discoverySession.sendMessage(null, -1290, "some message".getBytes());
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // empty
        }

        discoverySession.close();
        session.close();
    }

    /**
     * Request an Aware data-path (open) as a Responder with an arbitrary peer MAC address. Validate
     * that receive an onUnavailable() callback.
     */
    public void testDataPathOpenOutOfBandFail() throws InterruptedException {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        MacAddress mac = MacAddress.fromString("00:01:02:03:04:05");

        // 1. initialize Aware: only purpose is to make sure it is available for OOB data-path
        WifiAwareSession session = attachAndGetSession();

        PublishConfig publishConfig = new PublishConfig.Builder().setServiceName(
                "ValidName").build();
        DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();
        session.publish(publishConfig, discoveryCb, mHandler);
        assertTrue("Publish started",
                discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_PUBLISH_STARTED));
        Thread.sleep(WAIT_FOR_AWARE_INTERFACE_CREATION_SEC * 1000);

        // 2. request an AWARE network
        NetworkCallbackTest networkCb = new NetworkCallbackTest();
        NetworkRequest nr = new NetworkRequest.Builder().addTransportType(
                NetworkCapabilities.TRANSPORT_WIFI_AWARE).setNetworkSpecifier(
                session.createNetworkSpecifierOpen(
                        WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR,
                        mac.toByteArray())).build();
        mConnectivityManager.requestNetwork(nr, networkCb);
        assertTrue("OnUnavailable not received", networkCb.waitForOnUnavailable());

        session.close();
    }

    /**
     * Request an Aware data-path (encrypted with Passphrase) as a Responder with an arbitrary peer
     * MAC address.
     * Validate that receive an onUnavailable() callback.
     */
    public void testDataPathPassphraseOutOfBandFail() throws InterruptedException {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        MacAddress mac = MacAddress.fromString("00:01:02:03:04:05");

        // 1. initialize Aware: only purpose is to make sure it is available for OOB data-path
        WifiAwareSession session = attachAndGetSession();

        PublishConfig publishConfig = new PublishConfig.Builder().setServiceName(
                "ValidName").build();
        DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();
        session.publish(publishConfig, discoveryCb, mHandler);
        assertTrue("Publish started",
                discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_PUBLISH_STARTED));
        Thread.sleep(WAIT_FOR_AWARE_INTERFACE_CREATION_SEC * 1000);

        // 2. request an AWARE network
        NetworkCallbackTest networkCb = new NetworkCallbackTest();
        NetworkRequest nr = new NetworkRequest.Builder().addTransportType(
                NetworkCapabilities.TRANSPORT_WIFI_AWARE).setNetworkSpecifier(
                session.createNetworkSpecifierPassphrase(
                        WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR, mac.toByteArray(),
                        "abcdefghihk")).build();
        mConnectivityManager.requestNetwork(nr, networkCb);
        assertTrue("OnUnavailable not received", networkCb.waitForOnUnavailable());

        session.close();
    }

    /**
     * Request an Aware data-path (encrypted with PMK) as a Responder with an arbitrary peer MAC
     * address.
     * Validate that receive an onUnavailable() callback.
     */
    public void testDataPathPmkOutOfBandFail() throws InterruptedException {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        MacAddress mac = MacAddress.fromString("00:01:02:03:04:05");

        // 1. initialize Aware: only purpose is to make sure it is available for OOB data-path
        WifiAwareSession session = attachAndGetSession();

        PublishConfig publishConfig = new PublishConfig.Builder().setServiceName(
                "ValidName").build();
        DiscoverySessionCallbackTest discoveryCb = new DiscoverySessionCallbackTest();
        session.publish(publishConfig, discoveryCb, mHandler);
        assertTrue("Publish started",
                discoveryCb.waitForCallback(DiscoverySessionCallbackTest.ON_PUBLISH_STARTED));
        Thread.sleep(WAIT_FOR_AWARE_INTERFACE_CREATION_SEC * 1000);

        // 2. request an AWARE network
        NetworkCallbackTest networkCb = new NetworkCallbackTest();
        NetworkRequest nr = new NetworkRequest.Builder().addTransportType(
                NetworkCapabilities.TRANSPORT_WIFI_AWARE).setNetworkSpecifier(
                session.createNetworkSpecifierPmk(
                        WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR, mac.toByteArray(),
                        PMK_VALID)).build();
        mConnectivityManager.requestNetwork(nr, networkCb);
        assertTrue("OnUnavailable not received", networkCb.waitForOnUnavailable());

        session.close();
    }

    /**
     * Test WifiAwareNetworkSpecifier.
     */
    public void testWifiAwareNetworkSpecifier() {
        DiscoverySession session = mock(DiscoverySession.class);
        PeerHandle handle = mock(PeerHandle.class);
        WifiAwareNetworkSpecifier networkSpecifier =
                new WifiAwareNetworkSpecifier.Builder(session, handle).build();
        assertFalse(networkSpecifier.canBeSatisfiedBy(null));
        assertTrue(networkSpecifier.canBeSatisfiedBy(networkSpecifier));

        WifiAwareNetworkSpecifier anotherNetworkSpecifier =
                new WifiAwareNetworkSpecifier.Builder(session, handle).setPmk(PMK_VALID).build();
        assertFalse(networkSpecifier.canBeSatisfiedBy(anotherNetworkSpecifier));
    }

    /**
     * Test ParcelablePeerHandle parcel.
     */
    public void testParcelablePeerHandle() {
        PeerHandle peerHandle = mock(PeerHandle.class);
        ParcelablePeerHandle parcelablePeerHandle = new ParcelablePeerHandle(peerHandle);
        Parcel parcelW = Parcel.obtain();
        parcelablePeerHandle.writeToParcel(parcelW, 0);
        byte[] bytes = parcelW.marshall();
        parcelW.recycle();

        Parcel parcelR = Parcel.obtain();
        parcelR.unmarshall(bytes, 0, bytes.length);
        parcelR.setDataPosition(0);
        ParcelablePeerHandle rereadParcelablePeerHandle =
                ParcelablePeerHandle.CREATOR.createFromParcel(parcelR);

        assertEquals(parcelablePeerHandle, rereadParcelablePeerHandle);
        assertEquals(parcelablePeerHandle.hashCode(), rereadParcelablePeerHandle.hashCode());
    }

    /**
     * Test AwareResources constructor function.
     */
    public void testAwareResourcesConstructor() {
        AwareResources awareResources = new AwareResources(AVAILABLE_DATA_PATH_COUNT,
                AVAILABLE_PUBLISH_SESSION_COUNT, AVAILABLE_SUBSCRIBE_SESSION_COUNT);
        assertEquals(AVAILABLE_DATA_PATH_COUNT, awareResources.getAvailableDataPathsCount());
        assertEquals(AVAILABLE_PUBLISH_SESSION_COUNT, awareResources
                .getAvailablePublishSessionsCount());
        assertEquals(AVAILABLE_SUBSCRIBE_SESSION_COUNT, awareResources
                .getAvailableSubscribeSessionsCount());
    }

    /**
     * Verify setAwareParams works when have permission
     */
    public void testAwareParams() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        AwareParams params = new AwareParams();
        params.setDiscoveryWindowWakeInterval24Ghz(5);
        params.setDiscoveryWindowWakeInterval5Ghz(5);
        params.setDiscoveryBeaconIntervalMillis(50);
        params.setDwEarlyTerminationEnabled(true);
        params.setMacRandomizationIntervalSeconds(1000);
        params.setNumSpatialStreamsInDiscovery(1);
        assertEquals(5, params.getDiscoveryWindowWakeInterval24Ghz());
        assertEquals(5, params.getDiscoveryWindowWakeInterval5Ghz());
        assertEquals(50, params.getDiscoveryBeaconIntervalMillis());
        assertEquals(1000, params.getMacRandomizationIntervalSeconds());
        assertEquals(1, params.getNumSpatialStreamsInDiscovery());
        assertTrue(params.isDwEarlyTerminationEnabled());
        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> mWifiAwareManager.setAwareParams(params)
            );
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> mWifiAwareManager.setAwareParams(null)
            );
        }
    }

    /**
     * Verify Aware pairing config class.
     */
    public void testAwarePairingConfig() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        boolean pairingSupported = mWifiAwareManager.getCharacteristics().isAwarePairingSupported();
        AwarePairingConfig config = new AwarePairingConfig.Builder()
                .setPairingCacheEnabled(true)
                .setPairingSetupEnabled(true)
                .setPairingVerificationEnabled(true)
                .setBootstrappingMethods(PAIRING_BOOTSTRAPPING_OPPORTUNISTIC)
                .build();
        assertTrue(config.isPairingCacheEnabled());
        assertTrue(config.isPairingSetupEnabled());
        assertTrue(config.isPairingVerificationEnabled());
        assertEquals(PAIRING_BOOTSTRAPPING_OPPORTUNISTIC, config.getBootstrappingMethods());

        if (!ApiLevelUtil.isAfter(Build.VERSION_CODES.TIRAMISU)) {
            return;
        }

        WifiAwareSession session = attachAndGetSession();

        PublishConfig publishConfig = new PublishConfig.Builder().setServiceName(
                "ValidName").setPairingConfig(config).build();
        assertEquals(config, publishConfig.getPairingConfig());
        DiscoverySessionCallbackTest discoveryCb1 = new DiscoverySessionCallbackTest();
        // Should send exception when pairing is not supported
        if (!pairingSupported) {
            assertThrows(IllegalArgumentException.class, () ->
                    session.publish(publishConfig, discoveryCb1, mHandler));
        } else {
            session.publish(publishConfig, discoveryCb1, mHandler);
            assertTrue("Publish started", discoveryCb1
                    .waitForCallback(DiscoverySessionCallbackTest.ON_PUBLISH_STARTED));
        }

        DiscoverySessionCallbackTest discoveryCb2 = new DiscoverySessionCallbackTest();
        SubscribeConfig subscribeConfig = new SubscribeConfig.Builder().setServiceName(
                "ValidName").setPairingConfig(config).build();
        assertEquals(config, subscribeConfig.getPairingConfig());
        // Should send exception when pairing is not supported
        if (!pairingSupported) {
            assertThrows(IllegalArgumentException.class, () ->
                    session.subscribe(subscribeConfig, discoveryCb2, mHandler));
        } else {
            session.subscribe(subscribeConfig, discoveryCb2, mHandler);
            assertTrue("Subscribe started", discoveryCb2
                    .waitForCallback(DiscoverySessionCallbackTest.ON_SUBSCRIBE_STARTED));
        }
    }

    public void testAttachOffload() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            boolean hasPermission = mContext.checkCallingOrSelfPermission(OVERRIDE_WIFI_CONFIG)
                    == PERMISSION_GRANTED;
            // Attach offload session
            final AttachCallbackTest attachCb = new AttachCallbackTest();
            ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
            if (!hasPermission) {
                assertThrows(SecurityException.class, () ->
                        mWifiAwareManager.attachOffload(executor, attachCb));
                return;
            }
            mWifiAwareManager.attachOffload(executor, attachCb);
            int cbCalled = attachCb.waitForAnyCallback();
            assertEquals("Wi-Fi Aware attach", AttachCallbackTest.ATTACHED, cbCalled);
            // Attach a normal session offload session should be terminated
            attachAndGetCallback();
            cbCalled = attachCb.waitForAnyCallback();
            assertEquals("Wi-Fi Aware session terminate", AttachCallbackTest.TERMINATE, cbCalled);
            assertNull(attachCb.getSession());
            // Attach offload again, should fail.
            final AttachCallbackTest attachCb1 = new AttachCallbackTest();

            mWifiAwareManager.attachOffload(executor, attachCb1);
            cbCalled = attachCb1.waitForAnyCallback();
            assertEquals("Wi-Fi Aware attach", AttachCallbackTest.ATTACH_FAILED, cbCalled);
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Verify setAwareParams throw exception without permission
     */
    public void testAwareParamsWithoutPermission() {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        assertThrows(SecurityException.class, () -> mWifiAwareManager.setAwareParams(null));
    }

    /**
     * Verify {@link WifiAwareManager#setOpportunisticModeEnabled(boolean)} and
     * {@link WifiAwareManager#isOpportunisticModeEnabled(Executor, Consumer)}
     */
    public void testSetOpportunistic() throws InterruptedException {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        AtomicBoolean enabled = new AtomicBoolean(false);
        Consumer<Boolean> result = value -> {
            synchronized (mLock) {
                enabled.set(value);
                mLock.notify();
            }
        };
        try {
            mWifiAwareManager.setOpportunisticModeEnabled(true);
            mWifiAwareManager.isOpportunisticModeEnabled(
                    Executors.newSingleThreadScheduledExecutor(),
                    result);
            synchronized (mLock) {
                mLock.wait(WAIT_FOR_AWARE_CHANGE_SECS * 1000);
            }
            assertTrue(enabled.get());
            attachAndGetSession();
            if (!ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
                return;
            }
            AtomicBoolean called = new AtomicBoolean(false);
            AtomicBoolean canBeCreated = new AtomicBoolean(false);
            AtomicReference<Set<WifiManager.InterfaceCreationImpact>>
                    interfacesWhichWillBeDeleted = new AtomicReference<>(null);
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> mWifiManager.reportCreateInterfaceImpact(
                            WifiManager.WIFI_INTERFACE_TYPE_DIRECT, true,
                            Executors.newSingleThreadScheduledExecutor(),
                            (canBeCreatedLocal, interfacesWhichWillBeDeletedLocal) -> {
                                synchronized (mLock) {
                                    canBeCreated.set(canBeCreatedLocal);
                                    called.set(true);
                                    interfacesWhichWillBeDeleted
                                            .set(interfacesWhichWillBeDeletedLocal);
                                    mLock.notify();
                                }
                            }));
            synchronized (mLock) {
                mLock.wait(WAIT_FOR_AWARE_CHANGE_SECS * 1000);
            }
            assertTrue(called.get());
            if (canBeCreated.get()) {
                for (WifiManager.InterfaceCreationImpact entry
                        : interfacesWhichWillBeDeleted.get()) {
                    int interfaceType = entry.getInterfaceType();
                    assertEquals(WifiManager.WIFI_INTERFACE_TYPE_AWARE, interfaceType);
                    Set<String> packages = entry.getPackages();
                    assertTrue(packages.isEmpty());
                }
            }
        } finally {
            mWifiAwareManager.setOpportunisticModeEnabled(false);
        }
    }

    public void testSetMasterPreference() throws InterruptedException  {
        if (!TestUtils.shouldTestWifiAware(getContext())) {
            return;
        }
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            AtomicInteger mp = new AtomicInteger(-1);
            Consumer<Integer> result = value -> {
                mp.set(value);
                mLock.notify();
            };
            Executor executor = Executors.newSingleThreadScheduledExecutor();
            WifiAwareSession session = attachAndGetSession();
            if (!ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
                // Shell doesn't have permission before T.
                assertThrows(SecurityException.class, () -> session
                        .getMasterPreference(executor, result));
                assertThrows(SecurityException.class, () -> session
                        .setMasterPreference(254));
                return;
            }
            session.getMasterPreference(executor, result);
            synchronized (mLock) {
                mLock.wait(WAIT_FOR_AWARE_CHANGE_SECS * 1000);
            }
            assertEquals(0, mp.get());
            session.setMasterPreference(254);
            session.getMasterPreference(executor, result);
            synchronized (mLock) {
                mLock.wait(WAIT_FOR_AWARE_CHANGE_SECS * 1000);
            }
            assertEquals(254, mp.get());
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    // local utilities

    private WifiAwareSession attachAndGetSession() {
        AttachCallbackTest attachCb = new AttachCallbackTest();
        mWifiAwareManager.attach(attachCb, mHandler);
        int cbCalled = attachCb.waitForAnyCallback();
        assertEquals("Wi-Fi Aware attach", AttachCallbackTest.ATTACHED, cbCalled);

        WifiAwareSession session = attachCb.getSession();
        assertNotNull("Wi-Fi Aware session", session);
        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.S)) {
            assertTrue(mWifiAwareManager.isDeviceAttached());
        }

        return session;
    }

    // local utilities

    private AttachCallbackTest attachAndGetCallback() {
        AttachCallbackTest attachCb = new AttachCallbackTest();
        mWifiAwareManager.attach(attachCb, mHandler);
        int cbCalled = attachCb.waitForAnyCallback();
        assertEquals("Wi-Fi Aware attach", AttachCallbackTest.ATTACHED, cbCalled);
        return attachCb;
    }
}