blob: 770954079b178df1142e46b45a7dd84835d8ee20 [file] [log] [blame]
Mark De Ruyter1a7ae572018-03-02 15:35:36 -08001#!/usr/bin/env python3
Ang Li73697b32015-12-03 00:41:53 +00002#
tturney1bdf77d2015-12-28 17:46:13 -08003# Copyright 2016 Google, Inc.
Ang Li73697b32015-12-03 00:41:53 +00004#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
Ang Li5bd83f32016-05-23 14:39:38 -070017import logging
Girish Moturucf4dccd2018-08-27 12:22:00 -070018import os
James Mattis5a5dd492020-05-14 13:09:43 -070019import re
xianyuanjia0431ba32018-12-14 09:56:42 -080020import shutil
Girish Moturucf4dccd2018-08-27 12:22:00 -070021import time
Ang Li73697b32015-12-03 00:41:53 +000022
David Sue4cd9c22019-03-26 18:07:26 -070023from collections import namedtuple
Ang Li73697b32015-12-03 00:41:53 +000024from enum import IntEnum
25from queue import Empty
26
Ang Li82522812016-06-02 13:57:21 -070027from acts import asserts
Xianyuan Jia0e39e552019-01-24 17:17:47 -080028from acts import context
Ang Li374d7602016-02-08 17:27:27 -080029from acts import signals
Ang Lifee28402016-07-13 13:43:29 -070030from acts import utils
Ang Li2d3fe982016-06-08 10:00:43 -070031from acts.controllers import attenuator
Bindu Mahadev7e5dc682019-02-01 16:53:34 -080032from acts.controllers.ap_lib import hostapd_security
33from acts.controllers.ap_lib import hostapd_ap_preset
Girish Moturucf4dccd2018-08-27 12:22:00 -070034from acts.controllers.ap_lib.hostapd_constants import BAND_2G
35from acts.controllers.ap_lib.hostapd_constants import BAND_5G
Roshan Pius5fd42eb2021-01-21 12:26:31 -080036from acts_contrib.test_utils.net import connectivity_const as cconsts
Xianyuan Jia63751fb2020-11-17 00:07:40 +000037from acts_contrib.test_utils.tel import tel_defines
Roshan Pius5fd42eb2021-01-21 12:26:31 -080038from acts_contrib.test_utils.wifi import wifi_constants
39from acts_contrib.test_utils.wifi.aware import aware_test_utils as autils
Ang Li73697b32015-12-03 00:41:53 +000040
Bindu Mahadev1d3991e2017-03-20 18:06:54 -070041# Default timeout used for reboot, toggle WiFi and Airplane mode,
42# for the system to settle down after the operation.
43DEFAULT_TIMEOUT = 10
Ang Li73697b32015-12-03 00:41:53 +000044# Number of seconds to wait for events that are supposed to happen quickly.
45# Like onSuccess for start background scan and confirmation on wifi state
46# change.
47SHORT_TIMEOUT = 30
Bindu Mahadev7060a9f2018-05-04 13:48:12 -070048ROAMING_TIMEOUT = 30
Preetesh Barrettoe8c428b2019-02-14 09:15:44 -080049WIFI_CONNECTION_TIMEOUT_DEFAULT = 30
Ang Li73697b32015-12-03 00:41:53 +000050# Speed of light in m/s.
51SPEED_OF_LIGHT = 299792458
52
Qi Jiang8b443672018-03-16 14:46:50 -070053DEFAULT_PING_ADDR = "https://www.google.com/robots.txt"
Ang Li73697b32015-12-03 00:41:53 +000054
Girish Moturuddc0d382020-08-24 12:08:41 -070055CNSS_DIAG_CONFIG_PATH = "/data/vendor/wifi/cnss_diag/"
56CNSS_DIAG_CONFIG_FILE = "cnss_diag.conf"
57
Girish Moturu36348a32019-12-10 08:41:54 -080058ROAMING_ATTN = {
Omar El Ayach8c017902020-10-18 10:26:57 -070059 "AP1_on_AP2_off": [0, 0, 95, 95],
60 "AP1_off_AP2_on": [95, 95, 0, 0],
61 "default": [0, 0, 0, 0]
62}
Ang Li82522812016-06-02 13:57:21 -070063
Xianyuan Jia0e39e552019-01-24 17:17:47 -080064
Ang Li73697b32015-12-03 00:41:53 +000065class WifiEnums():
66
Omar El Ayach8c017902020-10-18 10:26:57 -070067 SSID_KEY = "SSID" # Used for Wifi & SoftAp
Roshan Piusc999e5e2018-11-09 10:59:52 -080068 SSID_PATTERN_KEY = "ssidPattern"
Bindu Mahadev4c94b532019-01-09 12:20:10 -080069 NETID_KEY = "network_id"
Omar El Ayach8c017902020-10-18 10:26:57 -070070 BSSID_KEY = "BSSID" # Used for Wifi & SoftAp
Roshan Piusc999e5e2018-11-09 10:59:52 -080071 BSSID_PATTERN_KEY = "bssidPattern"
Omar El Ayach8c017902020-10-18 10:26:57 -070072 PWD_KEY = "password" # Used for Wifi & SoftAp
Ang Li73697b32015-12-03 00:41:53 +000073 frequency_key = "frequency"
Omar El Ayach8c017902020-10-18 10:26:57 -070074 HIDDEN_KEY = "hiddenSSID" # Used for Wifi & SoftAp
Roshan Piusd1204442018-11-12 12:20:39 -080075 IS_APP_INTERACTION_REQUIRED = "isAppInteractionRequired"
76 IS_USER_INTERACTION_REQUIRED = "isUserInteractionRequired"
Roshan Pius55fb7c42020-04-03 14:47:18 -070077 IS_SUGGESTION_METERED = "isMetered"
Roshan Piusd1204442018-11-12 12:20:39 -080078 PRIORITY = "priority"
Omar El Ayach8c017902020-10-18 10:26:57 -070079 SECURITY = "security" # Used for Wifi & SoftAp
Ang Li73697b32015-12-03 00:41:53 +000080
leslce9cf6d2020-02-19 16:37:07 +080081 # Used for SoftAp
lesl6d30a172020-03-05 15:05:22 +080082 AP_BAND_KEY = "apBand"
83 AP_CHANNEL_KEY = "apChannel"
84 AP_MAXCLIENTS_KEY = "MaxNumberOfClients"
85 AP_SHUTDOWNTIMEOUT_KEY = "ShutdownTimeoutMillis"
86 AP_SHUTDOWNTIMEOUTENABLE_KEY = "AutoShutdownEnabled"
87 AP_CLIENTCONTROL_KEY = "ClientControlByUserEnabled"
88 AP_ALLOWEDLIST_KEY = "AllowedClientList"
89 AP_BLOCKEDLIST_KEY = "BlockedClientList"
90
leslce9cf6d2020-02-19 16:37:07 +080091 WIFI_CONFIG_SOFTAP_BAND_2G = 1
92 WIFI_CONFIG_SOFTAP_BAND_5G = 2
93 WIFI_CONFIG_SOFTAP_BAND_2G_5G = 3
94 WIFI_CONFIG_SOFTAP_BAND_6G = 4
95 WIFI_CONFIG_SOFTAP_BAND_2G_6G = 5
96 WIFI_CONFIG_SOFTAP_BAND_5G_6G = 6
97 WIFI_CONFIG_SOFTAP_BAND_ANY = 7
98
99 # DO NOT USE IT for new test case! Replaced by WIFI_CONFIG_SOFTAP_BAND_
100 WIFI_CONFIG_APBAND_2G = WIFI_CONFIG_SOFTAP_BAND_2G
101 WIFI_CONFIG_APBAND_5G = WIFI_CONFIG_SOFTAP_BAND_5G
102 WIFI_CONFIG_APBAND_AUTO = WIFI_CONFIG_SOFTAP_BAND_2G_5G
103
104 WIFI_CONFIG_APBAND_2G_OLD = 0
105 WIFI_CONFIG_APBAND_5G_OLD = 1
106 WIFI_CONFIG_APBAND_AUTO_OLD = -1
Ang Li73697b32015-12-03 00:41:53 +0000107
Ang Li82522812016-06-02 13:57:21 -0700108 WIFI_WPS_INFO_PBC = 0
109 WIFI_WPS_INFO_DISPLAY = 1
110 WIFI_WPS_INFO_KEYPAD = 2
111 WIFI_WPS_INFO_LABEL = 3
112 WIFI_WPS_INFO_INVALID = 4
Ang Li73697b32015-12-03 00:41:53 +0000113
lesl6d30a172020-03-05 15:05:22 +0800114 class SoftApSecurityType():
115 OPEN = "NONE"
116 WPA2 = "WPA2_PSK"
117 WPA3_SAE_TRANSITION = "WPA3_SAE_TRANSITION"
118 WPA3_SAE = "WPA3_SAE"
119
Ang Li73697b32015-12-03 00:41:53 +0000120 class CountryCode():
Girish Moturue648b6a2021-03-04 13:52:15 -0800121 AUSTRALIA = "AU"
Ang Li73697b32015-12-03 00:41:53 +0000122 CHINA = "CN"
Girish Moturua5ef35d2020-10-19 14:58:01 -0700123 GERMANY = "DE"
Ang Li73697b32015-12-03 00:41:53 +0000124 JAPAN = "JP"
125 UK = "GB"
126 US = "US"
127 UNKNOWN = "UNKNOWN"
128
129 # Start of Macros for EAP
130 # EAP types
131 class Eap(IntEnum):
132 NONE = -1
133 PEAP = 0
Ang Li82522812016-06-02 13:57:21 -0700134 TLS = 1
Ang Li73697b32015-12-03 00:41:53 +0000135 TTLS = 2
Ang Li82522812016-06-02 13:57:21 -0700136 PWD = 3
137 SIM = 4
138 AKA = 5
139 AKA_PRIME = 6
140 UNAUTH_TLS = 7
Ang Li73697b32015-12-03 00:41:53 +0000141
142 # EAP Phase2 types
143 class EapPhase2(IntEnum):
Ang Li82522812016-06-02 13:57:21 -0700144 NONE = 0
145 PAP = 1
146 MSCHAP = 2
147 MSCHAPV2 = 3
148 GTC = 4
Ang Li73697b32015-12-03 00:41:53 +0000149
150 class Enterprise:
Ang Li82522812016-06-02 13:57:21 -0700151 # Enterprise Config Macros
152 EMPTY_VALUE = "NULL"
153 EAP = "eap"
154 PHASE2 = "phase2"
155 IDENTITY = "identity"
156 ANON_IDENTITY = "anonymous_identity"
157 PASSWORD = "password"
158 SUBJECT_MATCH = "subject_match"
Ang Li73697b32015-12-03 00:41:53 +0000159 ALTSUBJECT_MATCH = "altsubject_match"
160 DOM_SUFFIX_MATCH = "domain_suffix_match"
Ang Li82522812016-06-02 13:57:21 -0700161 CLIENT_CERT = "client_cert"
162 CA_CERT = "ca_cert"
163 ENGINE = "engine"
164 ENGINE_ID = "engine_id"
165 PRIVATE_KEY_ID = "key_id"
166 REALM = "realm"
167 PLMN = "plmn"
168 FQDN = "FQDN"
169 FRIENDLY_NAME = "providerFriendlyName"
170 ROAMING_IDS = "roamingConsortiumIds"
Jimmy Chen7baec622020-06-23 19:00:33 +0800171 OCSP = "ocsp"
Omar El Ayach8c017902020-10-18 10:26:57 -0700172
Ang Li73697b32015-12-03 00:41:53 +0000173 # End of Macros for EAP
174
175 # Macros for wifi p2p.
176 WIFI_P2P_SERVICE_TYPE_ALL = 0
177 WIFI_P2P_SERVICE_TYPE_BONJOUR = 1
178 WIFI_P2P_SERVICE_TYPE_UPNP = 2
179 WIFI_P2P_SERVICE_TYPE_VENDOR_SPECIFIC = 255
180
181 class ScanResult:
182 CHANNEL_WIDTH_20MHZ = 0
183 CHANNEL_WIDTH_40MHZ = 1
184 CHANNEL_WIDTH_80MHZ = 2
185 CHANNEL_WIDTH_160MHZ = 3
186 CHANNEL_WIDTH_80MHZ_PLUS_MHZ = 4
187
188 # Macros for wifi rtt.
189 class RttType(IntEnum):
Ang Li82522812016-06-02 13:57:21 -0700190 TYPE_ONE_SIDED = 1
191 TYPE_TWO_SIDED = 2
Ang Li73697b32015-12-03 00:41:53 +0000192
193 class RttPeerType(IntEnum):
Ang Li82522812016-06-02 13:57:21 -0700194 PEER_TYPE_AP = 1
195 PEER_TYPE_STA = 2 # Requires NAN.
196 PEER_P2P_GO = 3
197 PEER_P2P_CLIENT = 4
198 PEER_NAN = 5
Ang Li73697b32015-12-03 00:41:53 +0000199
200 class RttPreamble(IntEnum):
Ang Li82522812016-06-02 13:57:21 -0700201 PREAMBLE_LEGACY = 0x01
202 PREAMBLE_HT = 0x02
203 PREAMBLE_VHT = 0x04
Ang Li73697b32015-12-03 00:41:53 +0000204
205 class RttBW(IntEnum):
Ang Li82522812016-06-02 13:57:21 -0700206 BW_5_SUPPORT = 0x01
207 BW_10_SUPPORT = 0x02
208 BW_20_SUPPORT = 0x04
209 BW_40_SUPPORT = 0x08
210 BW_80_SUPPORT = 0x10
Ang Li73697b32015-12-03 00:41:53 +0000211 BW_160_SUPPORT = 0x20
212
213 class Rtt(IntEnum):
Ang Li82522812016-06-02 13:57:21 -0700214 STATUS_SUCCESS = 0
215 STATUS_FAILURE = 1
216 STATUS_FAIL_NO_RSP = 2
217 STATUS_FAIL_REJECTED = 3
218 STATUS_FAIL_NOT_SCHEDULED_YET = 4
219 STATUS_FAIL_TM_TIMEOUT = 5
220 STATUS_FAIL_AP_ON_DIFF_CHANNEL = 6
221 STATUS_FAIL_NO_CAPABILITY = 7
222 STATUS_ABORTED = 8
223 STATUS_FAIL_INVALID_TS = 9
224 STATUS_FAIL_PROTOCOL = 10
225 STATUS_FAIL_SCHEDULE = 11
226 STATUS_FAIL_BUSY_TRY_LATER = 12
227 STATUS_INVALID_REQ = 13
228 STATUS_NO_WIFI = 14
229 STATUS_FAIL_FTM_PARAM_OVERRIDE = 15
Ang Li73697b32015-12-03 00:41:53 +0000230
Ang Li82522812016-06-02 13:57:21 -0700231 REASON_UNSPECIFIED = -1
232 REASON_NOT_AVAILABLE = -2
233 REASON_INVALID_LISTENER = -3
234 REASON_INVALID_REQUEST = -4
Ang Li73697b32015-12-03 00:41:53 +0000235
236 class RttParam:
237 device_type = "deviceType"
238 request_type = "requestType"
239 BSSID = "bssid"
240 channel_width = "channelWidth"
241 frequency = "frequency"
242 center_freq0 = "centerFreq0"
243 center_freq1 = "centerFreq1"
244 number_burst = "numberBurst"
245 interval = "interval"
246 num_samples_per_burst = "numSamplesPerBurst"
247 num_retries_per_measurement_frame = "numRetriesPerMeasurementFrame"
248 num_retries_per_FTMR = "numRetriesPerFTMR"
249 lci_request = "LCIRequest"
250 lcr_request = "LCRRequest"
251 burst_timeout = "burstTimeout"
252 preamble = "preamble"
253 bandwidth = "bandwidth"
254 margin = "margin"
255
256 RTT_MARGIN_OF_ERROR = {
257 RttBW.BW_80_SUPPORT: 2,
258 RttBW.BW_40_SUPPORT: 5,
259 RttBW.BW_20_SUPPORT: 5
260 }
261
262 # Macros as specified in the WifiScanner code.
Ang Li82522812016-06-02 13:57:21 -0700263 WIFI_BAND_UNSPECIFIED = 0 # not specified
264 WIFI_BAND_24_GHZ = 1 # 2.4 GHz band
265 WIFI_BAND_5_GHZ = 2 # 5 GHz band without DFS channels
266 WIFI_BAND_5_GHZ_DFS_ONLY = 4 # 5 GHz band with DFS channels
267 WIFI_BAND_5_GHZ_WITH_DFS = 6 # 5 GHz band with DFS channels
268 WIFI_BAND_BOTH = 3 # both bands without DFS channels
269 WIFI_BAND_BOTH_WITH_DFS = 7 # both bands with DFS channels
Ang Li73697b32015-12-03 00:41:53 +0000270
271 REPORT_EVENT_AFTER_BUFFER_FULL = 0
272 REPORT_EVENT_AFTER_EACH_SCAN = 1
273 REPORT_EVENT_FULL_SCAN_RESULT = 2
274
xshuaabcfeb2018-02-14 11:43:24 -0800275 SCAN_TYPE_LOW_LATENCY = 0
276 SCAN_TYPE_LOW_POWER = 1
277 SCAN_TYPE_HIGH_ACCURACY = 2
278
Ang Li73697b32015-12-03 00:41:53 +0000279 # US Wifi frequencies
Omar El Ayach8c017902020-10-18 10:26:57 -0700280 ALL_2G_FREQUENCIES = [
281 2412, 2417, 2422, 2427, 2432, 2437, 2442, 2447, 2452, 2457, 2462
282 ]
283 DFS_5G_FREQUENCIES = [
284 5260, 5280, 5300, 5320, 5500, 5520, 5540, 5560, 5580, 5600, 5620, 5640,
285 5660, 5680, 5700, 5720
286 ]
287 NONE_DFS_5G_FREQUENCIES = [
288 5180, 5200, 5220, 5240, 5745, 5765, 5785, 5805, 5825
289 ]
Ang Li73697b32015-12-03 00:41:53 +0000290 ALL_5G_FREQUENCIES = DFS_5G_FREQUENCIES + NONE_DFS_5G_FREQUENCIES
291
292 band_to_frequencies = {
Ang Li82522812016-06-02 13:57:21 -0700293 WIFI_BAND_24_GHZ: ALL_2G_FREQUENCIES,
294 WIFI_BAND_5_GHZ: NONE_DFS_5G_FREQUENCIES,
295 WIFI_BAND_5_GHZ_DFS_ONLY: DFS_5G_FREQUENCIES,
296 WIFI_BAND_5_GHZ_WITH_DFS: ALL_5G_FREQUENCIES,
297 WIFI_BAND_BOTH: ALL_2G_FREQUENCIES + NONE_DFS_5G_FREQUENCIES,
298 WIFI_BAND_BOTH_WITH_DFS: ALL_5G_FREQUENCIES + ALL_2G_FREQUENCIES
Ang Li73697b32015-12-03 00:41:53 +0000299 }
300
301 # All Wifi frequencies to channels lookup.
302 freq_to_channel = {
303 2412: 1,
304 2417: 2,
305 2422: 3,
306 2427: 4,
307 2432: 5,
308 2437: 6,
309 2442: 7,
310 2447: 8,
311 2452: 9,
312 2457: 10,
313 2462: 11,
314 2467: 12,
315 2472: 13,
316 2484: 14,
317 4915: 183,
318 4920: 184,
319 4925: 185,
320 4935: 187,
321 4940: 188,
322 4945: 189,
323 4960: 192,
324 4980: 196,
325 5035: 7,
326 5040: 8,
327 5045: 9,
328 5055: 11,
329 5060: 12,
330 5080: 16,
331 5170: 34,
332 5180: 36,
333 5190: 38,
334 5200: 40,
335 5210: 42,
336 5220: 44,
337 5230: 46,
338 5240: 48,
339 5260: 52,
340 5280: 56,
341 5300: 60,
342 5320: 64,
343 5500: 100,
344 5520: 104,
345 5540: 108,
346 5560: 112,
347 5580: 116,
348 5600: 120,
349 5620: 124,
350 5640: 128,
351 5660: 132,
352 5680: 136,
353 5700: 140,
354 5745: 149,
355 5765: 153,
356 5785: 157,
Omar El Ayachdb8463b2020-05-15 18:08:23 -0700357 5795: 159,
Ang Li73697b32015-12-03 00:41:53 +0000358 5805: 161,
359 5825: 165,
360 }
361
362 # All Wifi channels to frequencies lookup.
363 channel_2G_to_freq = {
364 1: 2412,
365 2: 2417,
366 3: 2422,
367 4: 2427,
368 5: 2432,
369 6: 2437,
370 7: 2442,
371 8: 2447,
372 9: 2452,
373 10: 2457,
374 11: 2462,
375 12: 2467,
376 13: 2472,
377 14: 2484
378 }
379
380 channel_5G_to_freq = {
381 183: 4915,
382 184: 4920,
383 185: 4925,
384 187: 4935,
385 188: 4940,
386 189: 4945,
387 192: 4960,
388 196: 4980,
389 7: 5035,
390 8: 5040,
391 9: 5045,
392 11: 5055,
393 12: 5060,
394 16: 5080,
395 34: 5170,
396 36: 5180,
397 38: 5190,
398 40: 5200,
399 42: 5210,
400 44: 5220,
401 46: 5230,
402 48: 5240,
Omar El Ayach8c017902020-10-18 10:26:57 -0700403 50: 5250,
Ang Li73697b32015-12-03 00:41:53 +0000404 52: 5260,
405 56: 5280,
406 60: 5300,
407 64: 5320,
408 100: 5500,
409 104: 5520,
410 108: 5540,
411 112: 5560,
412 116: 5580,
413 120: 5600,
414 124: 5620,
415 128: 5640,
416 132: 5660,
417 136: 5680,
418 140: 5700,
419 149: 5745,
Omar El Ayachdb8463b2020-05-15 18:08:23 -0700420 151: 5755,
Ang Li73697b32015-12-03 00:41:53 +0000421 153: 5765,
Omar El Ayachdb8463b2020-05-15 18:08:23 -0700422 155: 5775,
Ang Li73697b32015-12-03 00:41:53 +0000423 157: 5785,
Omar El Ayachdb8463b2020-05-15 18:08:23 -0700424 159: 5795,
Ang Li73697b32015-12-03 00:41:53 +0000425 161: 5805,
426 165: 5825
427 }
428
Ang Li82522812016-06-02 13:57:21 -0700429
Ang Li73697b32015-12-03 00:41:53 +0000430class WifiChannelBase:
431 ALL_2G_FREQUENCIES = []
432 DFS_5G_FREQUENCIES = []
433 NONE_DFS_5G_FREQUENCIES = []
434 ALL_5G_FREQUENCIES = DFS_5G_FREQUENCIES + NONE_DFS_5G_FREQUENCIES
435 MIX_CHANNEL_SCAN = []
436
437 def band_to_freq(self, band):
438 _band_to_frequencies = {
Omar El Ayach8c017902020-10-18 10:26:57 -0700439 WifiEnums.WIFI_BAND_24_GHZ:
440 self.ALL_2G_FREQUENCIES,
441 WifiEnums.WIFI_BAND_5_GHZ:
442 self.NONE_DFS_5G_FREQUENCIES,
443 WifiEnums.WIFI_BAND_5_GHZ_DFS_ONLY:
444 self.DFS_5G_FREQUENCIES,
445 WifiEnums.WIFI_BAND_5_GHZ_WITH_DFS:
446 self.ALL_5G_FREQUENCIES,
Ang Li82522812016-06-02 13:57:21 -0700447 WifiEnums.WIFI_BAND_BOTH:
448 self.ALL_2G_FREQUENCIES + self.NONE_DFS_5G_FREQUENCIES,
449 WifiEnums.WIFI_BAND_BOTH_WITH_DFS:
450 self.ALL_5G_FREQUENCIES + self.ALL_2G_FREQUENCIES
Ang Li73697b32015-12-03 00:41:53 +0000451 }
452 return _band_to_frequencies[band]
453
Ang Li82522812016-06-02 13:57:21 -0700454
Ang Li73697b32015-12-03 00:41:53 +0000455class WifiChannelUS(WifiChannelBase):
456 # US Wifi frequencies
Omar El Ayach8c017902020-10-18 10:26:57 -0700457 ALL_2G_FREQUENCIES = [
458 2412, 2417, 2422, 2427, 2432, 2437, 2442, 2447, 2452, 2457, 2462
459 ]
460 NONE_DFS_5G_FREQUENCIES = [
461 5180, 5200, 5220, 5240, 5745, 5765, 5785, 5805, 5825
462 ]
463 MIX_CHANNEL_SCAN = [
464 2412, 2437, 2462, 5180, 5200, 5280, 5260, 5300, 5500, 5320, 5520, 5560,
465 5700, 5745, 5805
466 ]
Ang Li73697b32015-12-03 00:41:53 +0000467
468 def __init__(self, model=None):
Omar El Ayach8c017902020-10-18 10:26:57 -0700469 self.DFS_5G_FREQUENCIES = [
470 5260, 5280, 5300, 5320, 5500, 5520, 5540, 5560, 5580, 5600, 5620,
471 5640, 5660, 5680, 5700, 5720
472 ]
Girish Moturu0c567b02017-08-11 16:20:01 -0700473 self.ALL_5G_FREQUENCIES = self.DFS_5G_FREQUENCIES + self.NONE_DFS_5G_FREQUENCIES
Ang Li73697b32015-12-03 00:41:53 +0000474
Bindu Mahadevff295782019-02-08 16:17:48 -0800475
Girish Moturuf02fa1d2017-05-21 09:51:23 +0530476class WifiReferenceNetworks:
477 """ Class to parse and return networks of different band and
478 auth type from reference_networks
479 """
480 def __init__(self, obj):
481 self.reference_networks = obj
482 self.WIFI_2G = "2g"
483 self.WIFI_5G = "5g"
484
485 self.secure_networks_2g = []
486 self.secure_networks_5g = []
487 self.open_networks_2g = []
488 self.open_networks_5g = []
489 self._parse_networks()
490
491 def _parse_networks(self):
492 for network in self.reference_networks:
493 for key in network:
494 if key == self.WIFI_2G:
495 if "password" in network[key]:
496 self.secure_networks_2g.append(network[key])
497 else:
498 self.open_networks_2g.append(network[key])
499 else:
500 if "password" in network[key]:
501 self.secure_networks_5g.append(network[key])
502 else:
503 self.open_networks_5g.append(network[key])
504
505 def return_2g_secure_networks(self):
506 return self.secure_networks_2g
507
508 def return_5g_secure_networks(self):
509 return self.secure_networks_5g
510
511 def return_2g_open_networks(self):
512 return self.open_networks_2g
513
514 def return_5g_open_networks(self):
515 return self.open_networks_5g
516
517 def return_secure_networks(self):
518 return self.secure_networks_2g + self.secure_networks_5g
519
520 def return_open_networks(self):
521 return self.open_networks_2g + self.open_networks_5g
522
Ang Li82522812016-06-02 13:57:21 -0700523
524def _assert_on_fail_handler(func, assert_on_fail, *args, **kwargs):
525 """Wrapper function that handles the bahevior of assert_on_fail.
526
527 When assert_on_fail is True, let all test signals through, which can
528 terminate test cases directly. When assert_on_fail is False, the wrapper
529 raises no test signals and reports operation status by returning True or
530 False.
531
532 Args:
533 func: The function to wrap. This function reports operation status by
534 raising test signals.
535 assert_on_fail: A boolean that specifies if the output of the wrapper
536 is test signal based or return value based.
537 args: Positional args for func.
538 kwargs: Name args for func.
539
540 Returns:
541 If assert_on_fail is True, returns True/False to signal operation
542 status, otherwise return nothing.
543 """
544 try:
545 func(*args, **kwargs)
546 if not assert_on_fail:
547 return True
548 except signals.TestSignal:
549 if assert_on_fail:
550 raise
551 return False
552
553
554def assert_network_in_list(target, network_list):
555 """Makes sure a specified target Wi-Fi network exists in a list of Wi-Fi
556 networks.
557
558 Args:
559 target: A dict representing a Wi-Fi network.
560 E.g. {WifiEnums.SSID_KEY: "SomeNetwork"}
561 network_list: A list of dicts, each representing a Wi-Fi network.
562 """
563 match_results = match_networks(target, network_list)
564 asserts.assert_true(
565 match_results, "Target network %s, does not exist in network list %s" %
566 (target, network_list))
567
568
Ang Li73697b32015-12-03 00:41:53 +0000569def match_networks(target_params, networks):
570 """Finds the WiFi networks that match a given set of parameters in a list
571 of WiFi networks.
572
Girish Moturubc48d9f2016-11-01 13:24:14 -0700573 To be considered a match, the network should contain every key-value pair
574 of target_params
Ang Li73697b32015-12-03 00:41:53 +0000575
576 Args:
Girish Moturubc48d9f2016-11-01 13:24:14 -0700577 target_params: A dict with 1 or more key-value pairs representing a Wi-Fi network.
578 E.g { 'SSID': 'wh_ap1_5g', 'BSSID': '30:b5:c2:33:e4:47' }
Ang Li73697b32015-12-03 00:41:53 +0000579 networks: A list of dict objects representing WiFi networks.
580
581 Returns:
582 The networks that match the target parameters.
583 """
584 results = []
Betty Zhou3caa0982017-02-22 19:26:20 -0800585 asserts.assert_true(target_params,
586 "Expected networks object 'target_params' is empty")
Ang Li73697b32015-12-03 00:41:53 +0000587 for n in networks:
Girish Moturubc48d9f2016-11-01 13:24:14 -0700588 add_network = 1
Ang Li9a66de72016-02-08 15:26:38 -0800589 for k, v in target_params.items():
590 if k not in n:
Girish Moturubc48d9f2016-11-01 13:24:14 -0700591 add_network = 0
592 break
Ang Li9a66de72016-02-08 15:26:38 -0800593 if n[k] != v:
Girish Moturubc48d9f2016-11-01 13:24:14 -0700594 add_network = 0
595 break
596 if add_network:
Ang Li73697b32015-12-03 00:41:53 +0000597 results.append(n)
598 return results
599
Bindu Mahadevff295782019-02-08 16:17:48 -0800600
Roshan Pius93b519c2018-05-09 12:07:11 -0700601def wait_for_wifi_state(ad, state, assert_on_fail=True):
602 """Waits for the device to transition to the specified wifi state
603
604 Args:
605 ad: An AndroidDevice object.
606 state: Wifi state to wait for.
607 assert_on_fail: If True, error checks in this function will raise test
608 failure signals.
609
610 Returns:
611 If assert_on_fail is False, function returns True if the device transitions
612 to the specified state, False otherwise. If assert_on_fail is True, no return value.
613 """
Omar El Ayach8c017902020-10-18 10:26:57 -0700614 return _assert_on_fail_handler(_wait_for_wifi_state,
615 assert_on_fail,
616 ad,
617 state=state)
Roshan Pius93b519c2018-05-09 12:07:11 -0700618
619
620def _wait_for_wifi_state(ad, state):
621 """Toggles the state of wifi.
622
623 TestFailure signals are raised when something goes wrong.
624
625 Args:
626 ad: An AndroidDevice object.
627 state: Wifi state to wait for.
628 """
629 if state == ad.droid.wifiCheckState():
630 # Check if the state is already achieved, so we don't wait for the
631 # state change event by mistake.
632 return
633 ad.droid.wifiStartTrackingStateChange()
Omar El Ayach8c017902020-10-18 10:26:57 -0700634 fail_msg = "Device did not transition to Wi-Fi state to %s on %s." % (
635 state, ad.serial)
Roshan Pius93b519c2018-05-09 12:07:11 -0700636 try:
637 ad.ed.wait_for_event(wifi_constants.WIFI_STATE_CHANGED,
638 lambda x: x["data"]["enabled"] == state,
639 SHORT_TIMEOUT)
640 except Empty:
641 asserts.assert_equal(state, ad.droid.wifiCheckState(), fail_msg)
642 finally:
643 ad.droid.wifiStopTrackingStateChange()
Ang Li82522812016-06-02 13:57:21 -0700644
Bindu Mahadevff295782019-02-08 16:17:48 -0800645
Ang Li82522812016-06-02 13:57:21 -0700646def wifi_toggle_state(ad, new_state=None, assert_on_fail=True):
Ang Li6b557182015-11-11 17:19:17 -0800647 """Toggles the state of wifi.
Ang Li73697b32015-12-03 00:41:53 +0000648
Ang Li6b557182015-11-11 17:19:17 -0800649 Args:
650 ad: An AndroidDevice object.
651 new_state: Wifi state to set to. If None, opposite of the current state.
Ang Li82522812016-06-02 13:57:21 -0700652 assert_on_fail: If True, error checks in this function will raise test
653 failure signals.
Ang Li73697b32015-12-03 00:41:53 +0000654
Ang Li6b557182015-11-11 17:19:17 -0800655 Returns:
Ang Li82522812016-06-02 13:57:21 -0700656 If assert_on_fail is False, function returns True if the toggle was
657 successful, False otherwise. If assert_on_fail is True, no return value.
658 """
Omar El Ayach8c017902020-10-18 10:26:57 -0700659 return _assert_on_fail_handler(_wifi_toggle_state,
660 assert_on_fail,
661 ad,
662 new_state=new_state)
Ang Li82522812016-06-02 13:57:21 -0700663
664
665def _wifi_toggle_state(ad, new_state=None):
666 """Toggles the state of wifi.
667
668 TestFailure signals are raised when something goes wrong.
669
670 Args:
671 ad: An AndroidDevice object.
672 new_state: The state to set Wi-Fi to. If None, opposite of the current
673 state will be set.
Ang Li6b557182015-11-11 17:19:17 -0800674 """
Ang Li31b00782016-06-21 13:04:23 -0700675 if new_state is None:
676 new_state = not ad.droid.wifiCheckState()
Ang Lie5c85c92016-07-27 15:38:09 -0700677 elif new_state == ad.droid.wifiCheckState():
678 # Check if the new_state is already achieved, so we don't wait for the
679 # state change event by mistake.
680 return
681 ad.droid.wifiStartTrackingStateChange()
Ang Li31b00782016-06-21 13:04:23 -0700682 ad.log.info("Setting Wi-Fi state to %s.", new_state)
Roshan Pius5a027fa2018-05-04 13:59:38 -0700683 ad.ed.clear_all_events()
Ang Li31b00782016-06-21 13:04:23 -0700684 # Setting wifi state.
Ang Li6b557182015-11-11 17:19:17 -0800685 ad.droid.wifiToggleState(new_state)
Jaineel3bd9bea2019-12-13 12:44:17 -0800686 time.sleep(2)
Ang Lie2e93a22016-06-22 16:43:28 -0700687 fail_msg = "Failed to set Wi-Fi state to %s on %s." % (new_state,
688 ad.serial)
Ang Li73697b32015-12-03 00:41:53 +0000689 try:
Roshan Pius5a027fa2018-05-04 13:59:38 -0700690 ad.ed.wait_for_event(wifi_constants.WIFI_STATE_CHANGED,
691 lambda x: x["data"]["enabled"] == new_state,
692 SHORT_TIMEOUT)
Ang Li73697b32015-12-03 00:41:53 +0000693 except Empty:
Ang Li82522812016-06-02 13:57:21 -0700694 asserts.assert_equal(new_state, ad.droid.wifiCheckState(), fail_msg)
Ang Li6b557182015-11-11 17:19:17 -0800695 finally:
696 ad.droid.wifiStopTrackingStateChange()
697
Ang Li82522812016-06-02 13:57:21 -0700698
Ang Li6b557182015-11-11 17:19:17 -0800699def reset_wifi(ad):
Ang Li1179fa72016-06-16 09:44:06 -0700700 """Clears all saved Wi-Fi networks on a device.
701
702 This will turn Wi-Fi on.
Ang Li6b557182015-11-11 17:19:17 -0800703
704 Args:
705 ad: An AndroidDevice object.
706
Ang Li6b557182015-11-11 17:19:17 -0800707 """
Ang Li6b557182015-11-11 17:19:17 -0800708 networks = ad.droid.wifiGetConfiguredNetworks()
709 if not networks:
710 return
711 for n in networks:
712 ad.droid.wifiForgetNetwork(n['networkId'])
713 try:
Bindu Mahadev4e710362016-11-17 16:17:11 -0800714 event = ad.ed.pop_event(wifi_constants.WIFI_FORGET_NW_SUCCESS,
Ang Li82522812016-06-02 13:57:21 -0700715 SHORT_TIMEOUT)
Ang Li6b557182015-11-11 17:19:17 -0800716 except Empty:
Ang Li1179fa72016-06-16 09:44:06 -0700717 logging.warning("Could not confirm the removal of network %s.", n)
718 # Check again to see if there's any network left.
Betty Zhou3caa0982017-02-22 19:26:20 -0800719 asserts.assert_true(
720 not ad.droid.wifiGetConfiguredNetworks(),
721 "Failed to remove these configured Wi-Fi networks: %s" % networks)
Ang Li82522812016-06-02 13:57:21 -0700722
Ang Li73697b32015-12-03 00:41:53 +0000723
Bindu Mahadev1d3991e2017-03-20 18:06:54 -0700724def toggle_airplane_mode_on_and_off(ad):
725 """Turn ON and OFF Airplane mode.
Bindu Mahadev3c54c492017-02-15 16:00:08 -0800726
Bindu Mahadev1d3991e2017-03-20 18:06:54 -0700727 ad: An AndroidDevice object.
728 Returns: Assert if turning on/off Airplane mode fails.
Bindu Mahadev3c54c492017-02-15 16:00:08 -0800729
Bindu Mahadev1d3991e2017-03-20 18:06:54 -0700730 """
731 ad.log.debug("Toggling Airplane mode ON.")
Omar El Ayach8c017902020-10-18 10:26:57 -0700732 asserts.assert_true(utils.force_airplane_mode(ad, True),
733 "Can not turn on airplane mode on: %s" % ad.serial)
Bindu Mahadev1d3991e2017-03-20 18:06:54 -0700734 time.sleep(DEFAULT_TIMEOUT)
735 ad.log.debug("Toggling Airplane mode OFF.")
Omar El Ayach8c017902020-10-18 10:26:57 -0700736 asserts.assert_true(utils.force_airplane_mode(ad, False),
737 "Can not turn on airplane mode on: %s" % ad.serial)
Bindu Mahadev1d3991e2017-03-20 18:06:54 -0700738 time.sleep(DEFAULT_TIMEOUT)
Bindu Mahadev3c54c492017-02-15 16:00:08 -0800739
740
Bindu Mahadev1d3991e2017-03-20 18:06:54 -0700741def toggle_wifi_off_and_on(ad):
742 """Turn OFF and ON WiFi.
Bindu Mahadev3c54c492017-02-15 16:00:08 -0800743
Bindu Mahadev1d3991e2017-03-20 18:06:54 -0700744 ad: An AndroidDevice object.
745 Returns: Assert if turning off/on WiFi fails.
Bindu Mahadev3c54c492017-02-15 16:00:08 -0800746
Bindu Mahadev1d3991e2017-03-20 18:06:54 -0700747 """
748 ad.log.debug("Toggling wifi OFF.")
749 wifi_toggle_state(ad, False)
750 time.sleep(DEFAULT_TIMEOUT)
751 ad.log.debug("Toggling wifi ON.")
752 wifi_toggle_state(ad, True)
753 time.sleep(DEFAULT_TIMEOUT)
Bindu Mahadev3c54c492017-02-15 16:00:08 -0800754
755
Ang Li73697b32015-12-03 00:41:53 +0000756def wifi_forget_network(ad, net_ssid):
Ang Li8e767182015-12-09 17:29:24 -0800757 """Remove configured Wifi network on an android device.
Ang Li73697b32015-12-03 00:41:53 +0000758
Ang Li8e767182015-12-09 17:29:24 -0800759 Args:
760 ad: android_device object for forget network.
761 net_ssid: ssid of network to be forget
Ang Li73697b32015-12-03 00:41:53 +0000762
Ang Li8e767182015-12-09 17:29:24 -0800763 """
Girish Moturu40d7dc22016-11-02 12:14:56 -0700764 networks = ad.droid.wifiGetConfiguredNetworks()
Ang Li8e767182015-12-09 17:29:24 -0800765 if not networks:
766 return
767 for n in networks:
768 if net_ssid in n[WifiEnums.SSID_KEY]:
Girish Moturu40d7dc22016-11-02 12:14:56 -0700769 ad.droid.wifiForgetNetwork(n['networkId'])
Ang Li8e767182015-12-09 17:29:24 -0800770 try:
Bindu Mahadev4e710362016-11-17 16:17:11 -0800771 event = ad.ed.pop_event(wifi_constants.WIFI_FORGET_NW_SUCCESS,
Betty Zhou3caa0982017-02-22 19:26:20 -0800772 SHORT_TIMEOUT)
Ang Li8e767182015-12-09 17:29:24 -0800773 except Empty:
Girish Moturu1bf82302016-11-01 13:27:00 -0700774 asserts.fail("Failed to remove network %s." % n)
Ang Li73697b32015-12-03 00:41:53 +0000775
Ang Li82522812016-06-02 13:57:21 -0700776
Ang Li73697b32015-12-03 00:41:53 +0000777def wifi_test_device_init(ad):
778 """Initializes an android device for wifi testing.
779
780 0. Make sure SL4A connection is established on the android device.
781 1. Disable location service's WiFi scan.
782 2. Turn WiFi on.
783 3. Clear all saved networks.
784 4. Set country code to US.
785 5. Enable WiFi verbose logging.
786 6. Sync device time with computer time.
787 7. Turn off cellular data.
Ang Lifee28402016-07-13 13:43:29 -0700788 8. Turn off ambient display.
Ang Li73697b32015-12-03 00:41:53 +0000789 """
Ang Lifee28402016-07-13 13:43:29 -0700790 utils.require_sl4a((ad, ))
Ang Li73697b32015-12-03 00:41:53 +0000791 ad.droid.wifiScannerToggleAlwaysAvailable(False)
792 msg = "Failed to turn off location service's scan."
Ang Li82522812016-06-02 13:57:21 -0700793 asserts.assert_true(not ad.droid.wifiScannerIsAlwaysAvailable(), msg)
794 wifi_toggle_state(ad, True)
Ang Li6b557182015-11-11 17:19:17 -0800795 reset_wifi(ad)
Ang Li73697b32015-12-03 00:41:53 +0000796 ad.droid.wifiEnableVerboseLogging(1)
Ang Li8e767182015-12-09 17:29:24 -0800797 msg = "Failed to enable WiFi verbose logging."
Ang Li82522812016-06-02 13:57:21 -0700798 asserts.assert_equal(ad.droid.wifiGetVerboseLoggingLevel(), 1, msg)
Ang Li73697b32015-12-03 00:41:53 +0000799 # We don't verify the following settings since they are not critical.
Ang Lie2e93a22016-06-22 16:43:28 -0700800 # Set wpa_supplicant log level to EXCESSIVE.
Omar El Ayach8c017902020-10-18 10:26:57 -0700801 output = ad.adb.shell(
802 "wpa_cli -i wlan0 -p -g@android:wpa_wlan0 IFNAME="
803 "wlan0 log_level EXCESSIVE",
804 ignore_status=True)
Ang Lie2e93a22016-06-22 16:43:28 -0700805 ad.log.info("wpa_supplicant log change status: %s", output)
Ang Lifee28402016-07-13 13:43:29 -0700806 utils.sync_device_time(ad)
Ang Li0bf8e022016-01-04 17:34:48 -0800807 ad.droid.telephonyToggleDataConnection(False)
Roshan Pius48df08c2019-09-13 08:07:30 -0700808 set_wifi_country_code(ad, WifiEnums.CountryCode.US)
Ang Lifee28402016-07-13 13:43:29 -0700809 utils.set_ambient_display(ad, False)
Ang Li73697b32015-12-03 00:41:53 +0000810
Omar El Ayach8c017902020-10-18 10:26:57 -0700811
Roshan Pius48df08c2019-09-13 08:07:30 -0700812def set_wifi_country_code(ad, country_code):
813 """Sets the wifi country code on the device.
814
815 Args:
816 ad: An AndroidDevice object.
817 country_code: 2 letter ISO country code
codycaldwell35b87182020-01-16 14:08:01 -0800818
819 Raises:
820 An RpcException if unable to set the country code.
Roshan Pius48df08c2019-09-13 08:07:30 -0700821 """
Jaineelc5b56a62019-10-10 17:12:02 -0700822 try:
codycaldwell35b87182020-01-16 14:08:01 -0800823 ad.adb.shell("cmd wifi force-country-code enabled %s" % country_code)
Jaineel Mehtacbad5cc2020-11-19 21:38:18 +0000824 except Exception as e:
Jaineelc5b56a62019-10-10 17:12:02 -0700825 ad.droid.wifiSetCountryCode(WifiEnums.CountryCode.US)
Roshan Pius48df08c2019-09-13 08:07:30 -0700826
Ang Li82522812016-06-02 13:57:21 -0700827
Ang Li6b557182015-11-11 17:19:17 -0800828def start_wifi_connection_scan(ad):
Ang Li73697b32015-12-03 00:41:53 +0000829 """Starts a wifi connection scan and wait for results to become available.
830
831 Args:
Ang Li6b557182015-11-11 17:19:17 -0800832 ad: An AndroidDevice object.
Ang Li73697b32015-12-03 00:41:53 +0000833 """
Roshan Pius7f61f1c2018-01-24 18:36:49 -0800834 ad.ed.clear_all_events()
Ang Li6b557182015-11-11 17:19:17 -0800835 ad.droid.wifiStartScan()
Ang Li82522812016-06-02 13:57:21 -0700836 try:
837 ad.ed.pop_event("WifiManagerScanResultsAvailable", 60)
838 except Empty:
839 asserts.fail("Wi-Fi results did not become available within 60s.")
840
Ang Li73697b32015-12-03 00:41:53 +0000841
Roshan Piuscb9bc482018-02-01 14:27:09 -0800842def start_wifi_connection_scan_and_return_status(ad):
843 """
844 Starts a wifi connection scan and wait for results to become available
845 or a scan failure to be reported.
846
847 Args:
848 ad: An AndroidDevice object.
849 Returns:
850 True: if scan succeeded & results are available
851 False: if scan failed
852 """
853 ad.ed.clear_all_events()
854 ad.droid.wifiStartScan()
855 try:
Omar El Ayach8c017902020-10-18 10:26:57 -0700856 events = ad.ed.pop_events("WifiManagerScan(ResultsAvailable|Failure)",
857 60)
Roshan Piuscb9bc482018-02-01 14:27:09 -0800858 except Empty:
859 asserts.fail(
860 "Wi-Fi scan results/failure did not become available within 60s.")
861 # If there are multiple matches, we check for atleast one success.
862 for event in events:
863 if event["name"] == "WifiManagerScanResultsAvailable":
864 return True
865 elif event["name"] == "WifiManagerScanFailure":
866 ad.log.debug("Scan failure received")
867 return False
868
869
Omar El Ayach8c017902020-10-18 10:26:57 -0700870def start_wifi_connection_scan_and_check_for_network(ad,
871 network_ssid,
Roshan Piuscb9bc482018-02-01 14:27:09 -0800872 max_tries=3):
Roshan Pius7f61f1c2018-01-24 18:36:49 -0800873 """
874 Start connectivity scans & checks if the |network_ssid| is seen in
875 scan results. The method performs a max of |max_tries| connectivity scans
876 to find the network.
877
878 Args:
879 ad: An AndroidDevice object.
880 network_ssid: SSID of the network we are looking for.
881 max_tries: Number of scans to try.
882 Returns:
883 True: if network_ssid is found in scan results.
884 False: if network_ssid is not found in scan results.
885 """
886 for num_tries in range(max_tries):
Roshan Piuscb9bc482018-02-01 14:27:09 -0800887 if start_wifi_connection_scan_and_return_status(ad):
888 scan_results = ad.droid.wifiGetScanResults()
Omar El Ayach8c017902020-10-18 10:26:57 -0700889 match_results = match_networks({WifiEnums.SSID_KEY: network_ssid},
890 scan_results)
Roshan Piuscb9bc482018-02-01 14:27:09 -0800891 if len(match_results) > 0:
892 return True
Roshan Pius7f61f1c2018-01-24 18:36:49 -0800893 return False
894
895
Omar El Ayach8c017902020-10-18 10:26:57 -0700896def start_wifi_connection_scan_and_ensure_network_found(
897 ad, network_ssid, max_tries=3):
Roshan Pius7f61f1c2018-01-24 18:36:49 -0800898 """
899 Start connectivity scans & ensure the |network_ssid| is seen in
900 scan results. The method performs a max of |max_tries| connectivity scans
901 to find the network.
902 This method asserts on failure!
903
904 Args:
905 ad: An AndroidDevice object.
906 network_ssid: SSID of the network we are looking for.
907 max_tries: Number of scans to try.
908 """
909 ad.log.info("Starting scans to ensure %s is present", network_ssid)
910 assert_msg = "Failed to find " + network_ssid + " in scan results" \
911 " after " + str(max_tries) + " tries"
Omar El Ayach8c017902020-10-18 10:26:57 -0700912 asserts.assert_true(
913 start_wifi_connection_scan_and_check_for_network(
914 ad, network_ssid, max_tries), assert_msg)
Roshan Pius7f61f1c2018-01-24 18:36:49 -0800915
916
Omar El Ayach8c017902020-10-18 10:26:57 -0700917def start_wifi_connection_scan_and_ensure_network_not_found(
918 ad, network_ssid, max_tries=3):
Roshan Pius7f61f1c2018-01-24 18:36:49 -0800919 """
920 Start connectivity scans & ensure the |network_ssid| is not seen in
921 scan results. The method performs a max of |max_tries| connectivity scans
922 to find the network.
923 This method asserts on failure!
924
925 Args:
926 ad: An AndroidDevice object.
927 network_ssid: SSID of the network we are looking for.
928 max_tries: Number of scans to try.
929 """
930 ad.log.info("Starting scans to ensure %s is not present", network_ssid)
931 assert_msg = "Found " + network_ssid + " in scan results" \
932 " after " + str(max_tries) + " tries"
Omar El Ayach8c017902020-10-18 10:26:57 -0700933 asserts.assert_false(
934 start_wifi_connection_scan_and_check_for_network(
935 ad, network_ssid, max_tries), assert_msg)
Roshan Pius7f61f1c2018-01-24 18:36:49 -0800936
937
Ang Li73697b32015-12-03 00:41:53 +0000938def start_wifi_background_scan(ad, scan_setting):
939 """Starts wifi background scan.
940
941 Args:
942 ad: android_device object to initiate connection on.
943 scan_setting: A dict representing the settings of the scan.
944
945 Returns:
946 If scan was started successfully, event data of success event is returned.
947 """
Girish Moturu40d7dc22016-11-02 12:14:56 -0700948 idx = ad.droid.wifiScannerStartBackgroundScan(scan_setting)
949 event = ad.ed.pop_event("WifiScannerScan{}onSuccess".format(idx),
Betty Zhou3caa0982017-02-22 19:26:20 -0800950 SHORT_TIMEOUT)
Ang Li73697b32015-12-03 00:41:53 +0000951 return event['data']
952
Ang Li82522812016-06-02 13:57:21 -0700953
Roshan Piusce821342018-01-10 11:03:04 -0800954def start_wifi_tethering(ad, ssid, password, band=None, hidden=None):
Ang Li73697b32015-12-03 00:41:53 +0000955 """Starts wifi tethering on an android_device.
956
957 Args:
958 ad: android_device to start wifi tethering on.
959 ssid: The SSID the soft AP should broadcast.
960 password: The password the soft AP should use.
961 band: The band the soft AP should be set on. It should be either
962 WifiEnums.WIFI_CONFIG_APBAND_2G or WifiEnums.WIFI_CONFIG_APBAND_5G.
Roshan Piusce821342018-01-10 11:03:04 -0800963 hidden: boolean to indicate if the AP needs to be hidden or not.
Ang Li73697b32015-12-03 00:41:53 +0000964
965 Returns:
Girish Moturu3581d612016-11-02 15:08:51 -0700966 No return value. Error checks in this function will raise test failure signals
Ang Li73697b32015-12-03 00:41:53 +0000967 """
Ang Li82522812016-06-02 13:57:21 -0700968 config = {WifiEnums.SSID_KEY: ssid}
Ang Li73697b32015-12-03 00:41:53 +0000969 if password:
970 config[WifiEnums.PWD_KEY] = password
971 if band:
lesl6d30a172020-03-05 15:05:22 +0800972 config[WifiEnums.AP_BAND_KEY] = band
Roshan Piusce821342018-01-10 11:03:04 -0800973 if hidden:
Omar El Ayach8c017902020-10-18 10:26:57 -0700974 config[WifiEnums.HIDDEN_KEY] = hidden
975 asserts.assert_true(ad.droid.wifiSetWifiApConfiguration(config),
976 "Failed to update WifiAp Configuration")
Girish Moturu40d7dc22016-11-02 12:14:56 -0700977 ad.droid.wifiStartTrackingTetherStateChange()
978 ad.droid.connectivityStartTethering(tel_defines.TETHERING_WIFI, False)
Rebecca Silbersteina2889852016-08-11 00:48:53 -0700979 try:
Girish Moturu40d7dc22016-11-02 12:14:56 -0700980 ad.ed.pop_event("ConnectivityManagerOnTetheringStarted")
981 ad.ed.wait_for_event("TetherStateChanged",
Betty Zhou3caa0982017-02-22 19:26:20 -0800982 lambda x: x["data"]["ACTIVE_TETHER"], 30)
Ang Li76216d12016-09-20 14:51:57 -0700983 ad.log.debug("Tethering started successfully.")
Rebecca Silbersteina2889852016-08-11 00:48:53 -0700984 except Empty:
985 msg = "Failed to receive confirmation of wifi tethering starting"
986 asserts.fail(msg)
987 finally:
Girish Moturu40d7dc22016-11-02 12:14:56 -0700988 ad.droid.wifiStopTrackingTetherStateChange()
Ang Li73697b32015-12-03 00:41:53 +0000989
Bindu Mahadevff295782019-02-08 16:17:48 -0800990
Omar El Ayach8c017902020-10-18 10:26:57 -0700991def save_wifi_soft_ap_config(ad,
992 wifi_config,
993 band=None,
994 hidden=None,
995 security=None,
996 password=None,
997 channel=None,
998 max_clients=None,
lesl6d30a172020-03-05 15:05:22 +0800999 shutdown_timeout_enable=None,
1000 shutdown_timeout_millis=None,
1001 client_control_enable=None,
Omar El Ayach8c017902020-10-18 10:26:57 -07001002 allowedList=None,
1003 blockedList=None):
lesl6d30a172020-03-05 15:05:22 +08001004 """ Save a soft ap configuration and verified
1005 Args:
1006 ad: android_device to set soft ap configuration.
1007 wifi_config: a soft ap configuration object, at least include SSID.
1008 band: specifies the band for the soft ap.
1009 hidden: specifies the soft ap need to broadcast its SSID or not.
1010 security: specifies the security type for the soft ap.
1011 password: specifies the password for the soft ap.
1012 channel: specifies the channel for the soft ap.
1013 max_clients: specifies the maximum connected client number.
1014 shutdown_timeout_enable: specifies the auto shut down enable or not.
1015 shutdown_timeout_millis: specifies the shut down timeout value.
1016 client_control_enable: specifies the client control enable or not.
1017 allowedList: specifies allowed clients list.
1018 blockedList: specifies blocked clients list.
1019 """
1020 if security and password:
Omar El Ayach8c017902020-10-18 10:26:57 -07001021 wifi_config[WifiEnums.SECURITY] = security
1022 wifi_config[WifiEnums.PWD_KEY] = password
Girish Moturu528b5442018-06-07 10:48:14 -07001023 if band:
lesl6d30a172020-03-05 15:05:22 +08001024 wifi_config[WifiEnums.AP_BAND_KEY] = band
Girish Moturu528b5442018-06-07 10:48:14 -07001025 if hidden:
1026 wifi_config[WifiEnums.HIDDEN_KEY] = hidden
lesl6d30a172020-03-05 15:05:22 +08001027 if channel and band:
1028 wifi_config[WifiEnums.AP_BAND_KEY] = band
1029 wifi_config[WifiEnums.AP_CHANNEL_KEY] = channel
1030 if max_clients:
1031 wifi_config[WifiEnums.AP_MAXCLIENTS_KEY] = max_clients
1032 if shutdown_timeout_enable:
1033 wifi_config[
1034 WifiEnums.AP_SHUTDOWNTIMEOUTENABLE_KEY] = shutdown_timeout_enable
1035 if shutdown_timeout_millis:
Omar El Ayach8c017902020-10-18 10:26:57 -07001036 wifi_config[WifiEnums.AP_SHUTDOWNTIMEOUT_KEY] = shutdown_timeout_millis
lesl6d30a172020-03-05 15:05:22 +08001037 if client_control_enable:
1038 wifi_config[WifiEnums.AP_CLIENTCONTROL_KEY] = client_control_enable
1039 if allowedList:
1040 wifi_config[WifiEnums.AP_ALLOWEDLIST_KEY] = allowedList
1041 if blockedList:
1042 wifi_config[WifiEnums.AP_BLOCKEDLIST_KEY] = blockedList
1043
1044 if WifiEnums.AP_CHANNEL_KEY in wifi_config and wifi_config[
Omar El Ayach8c017902020-10-18 10:26:57 -07001045 WifiEnums.AP_CHANNEL_KEY] == 0:
lesl6d30a172020-03-05 15:05:22 +08001046 del wifi_config[WifiEnums.AP_CHANNEL_KEY]
1047
1048 if WifiEnums.SECURITY in wifi_config and wifi_config[
Omar El Ayach8c017902020-10-18 10:26:57 -07001049 WifiEnums.SECURITY] == WifiEnums.SoftApSecurityType.OPEN:
lesl6d30a172020-03-05 15:05:22 +08001050 del wifi_config[WifiEnums.SECURITY]
1051 del wifi_config[WifiEnums.PWD_KEY]
1052
Girish Moturu528b5442018-06-07 10:48:14 -07001053 asserts.assert_true(ad.droid.wifiSetWifiApConfiguration(wifi_config),
1054 "Failed to set WifiAp Configuration")
1055
1056 wifi_ap = ad.droid.wifiGetApConfiguration()
1057 asserts.assert_true(
1058 wifi_ap[WifiEnums.SSID_KEY] == wifi_config[WifiEnums.SSID_KEY],
lesl6d30a172020-03-05 15:05:22 +08001059 "Hotspot SSID doesn't match")
1060 if WifiEnums.SECURITY in wifi_config:
1061 asserts.assert_true(
1062 wifi_ap[WifiEnums.SECURITY] == wifi_config[WifiEnums.SECURITY],
1063 "Hotspot Security doesn't match")
1064 if WifiEnums.PWD_KEY in wifi_config:
1065 asserts.assert_true(
1066 wifi_ap[WifiEnums.PWD_KEY] == wifi_config[WifiEnums.PWD_KEY],
1067 "Hotspot Password doesn't match")
Girish Moturu528b5442018-06-07 10:48:14 -07001068
lesl6d30a172020-03-05 15:05:22 +08001069 if WifiEnums.HIDDEN_KEY in wifi_config:
1070 asserts.assert_true(
1071 wifi_ap[WifiEnums.HIDDEN_KEY] == wifi_config[WifiEnums.HIDDEN_KEY],
1072 "Hotspot hidden setting doesn't match")
1073
1074 if WifiEnums.AP_BAND_KEY in wifi_config:
1075 asserts.assert_true(
Omar El Ayach8c017902020-10-18 10:26:57 -07001076 wifi_ap[WifiEnums.AP_BAND_KEY] == wifi_config[
1077 WifiEnums.AP_BAND_KEY], "Hotspot Band doesn't match")
lesl6d30a172020-03-05 15:05:22 +08001078 if WifiEnums.AP_CHANNEL_KEY in wifi_config:
1079 asserts.assert_true(
1080 wifi_ap[WifiEnums.AP_CHANNEL_KEY] == wifi_config[
Omar El Ayach8c017902020-10-18 10:26:57 -07001081 WifiEnums.AP_CHANNEL_KEY], "Hotspot Channel doesn't match")
lesl6d30a172020-03-05 15:05:22 +08001082 if WifiEnums.AP_MAXCLIENTS_KEY in wifi_config:
1083 asserts.assert_true(
1084 wifi_ap[WifiEnums.AP_MAXCLIENTS_KEY] == wifi_config[
Omar El Ayach8c017902020-10-18 10:26:57 -07001085 WifiEnums.AP_MAXCLIENTS_KEY],
1086 "Hotspot Max Clients doesn't match")
lesl6d30a172020-03-05 15:05:22 +08001087 if WifiEnums.AP_SHUTDOWNTIMEOUTENABLE_KEY in wifi_config:
1088 asserts.assert_true(
1089 wifi_ap[WifiEnums.AP_SHUTDOWNTIMEOUTENABLE_KEY] == wifi_config[
Omar El Ayach8c017902020-10-18 10:26:57 -07001090 WifiEnums.AP_SHUTDOWNTIMEOUTENABLE_KEY],
lesl6d30a172020-03-05 15:05:22 +08001091 "Hotspot ShutDown feature flag doesn't match")
1092 if WifiEnums.AP_SHUTDOWNTIMEOUT_KEY in wifi_config:
1093 asserts.assert_true(
1094 wifi_ap[WifiEnums.AP_SHUTDOWNTIMEOUT_KEY] == wifi_config[
Omar El Ayach8c017902020-10-18 10:26:57 -07001095 WifiEnums.AP_SHUTDOWNTIMEOUT_KEY],
lesl6d30a172020-03-05 15:05:22 +08001096 "Hotspot ShutDown timeout setting doesn't match")
1097 if WifiEnums.AP_CLIENTCONTROL_KEY in wifi_config:
1098 asserts.assert_true(
1099 wifi_ap[WifiEnums.AP_CLIENTCONTROL_KEY] == wifi_config[
Omar El Ayach8c017902020-10-18 10:26:57 -07001100 WifiEnums.AP_CLIENTCONTROL_KEY],
lesl6d30a172020-03-05 15:05:22 +08001101 "Hotspot Client control flag doesn't match")
1102 if WifiEnums.AP_ALLOWEDLIST_KEY in wifi_config:
1103 asserts.assert_true(
1104 wifi_ap[WifiEnums.AP_ALLOWEDLIST_KEY] == wifi_config[
Omar El Ayach8c017902020-10-18 10:26:57 -07001105 WifiEnums.AP_ALLOWEDLIST_KEY],
lesl6d30a172020-03-05 15:05:22 +08001106 "Hotspot Allowed List doesn't match")
1107 if WifiEnums.AP_BLOCKEDLIST_KEY in wifi_config:
1108 asserts.assert_true(
1109 wifi_ap[WifiEnums.AP_BLOCKEDLIST_KEY] == wifi_config[
Omar El Ayach8c017902020-10-18 10:26:57 -07001110 WifiEnums.AP_BLOCKEDLIST_KEY],
lesl6d30a172020-03-05 15:05:22 +08001111 "Hotspot Blocked List doesn't match")
Bindu Mahadevff295782019-02-08 16:17:48 -08001112
Omar El Ayach8c017902020-10-18 10:26:57 -07001113
Girish Moturu528b5442018-06-07 10:48:14 -07001114def start_wifi_tethering_saved_config(ad):
1115 """ Turn on wifi hotspot with a config that is already saved """
1116 ad.droid.wifiStartTrackingTetherStateChange()
1117 ad.droid.connectivityStartTethering(tel_defines.TETHERING_WIFI, False)
1118 try:
1119 ad.ed.pop_event("ConnectivityManagerOnTetheringStarted")
1120 ad.ed.wait_for_event("TetherStateChanged",
1121 lambda x: x["data"]["ACTIVE_TETHER"], 30)
1122 except:
1123 asserts.fail("Didn't receive wifi tethering starting confirmation")
1124 finally:
1125 ad.droid.wifiStopTrackingTetherStateChange()
Betty Zhou3caa0982017-02-22 19:26:20 -08001126
Bindu Mahadevff295782019-02-08 16:17:48 -08001127
Ang Li73697b32015-12-03 00:41:53 +00001128def stop_wifi_tethering(ad):
1129 """Stops wifi tethering on an android_device.
Ang Li73697b32015-12-03 00:41:53 +00001130 Args:
1131 ad: android_device to stop wifi tethering on.
1132 """
Girish Moturu40d7dc22016-11-02 12:14:56 -07001133 ad.droid.wifiStartTrackingTetherStateChange()
1134 ad.droid.connectivityStopTethering(tel_defines.TETHERING_WIFI)
Rebecca Silbersteina2889852016-08-11 00:48:53 -07001135 try:
Girish Moturu40d7dc22016-11-02 12:14:56 -07001136 ad.ed.pop_event("WifiManagerApDisabled", 30)
1137 ad.ed.wait_for_event("TetherStateChanged",
Betty Zhou3caa0982017-02-22 19:26:20 -08001138 lambda x: not x["data"]["ACTIVE_TETHER"], 30)
Rebecca Silbersteina2889852016-08-11 00:48:53 -07001139 except Empty:
1140 msg = "Failed to receive confirmation of wifi tethering stopping"
1141 asserts.fail(msg)
1142 finally:
Girish Moturu40d7dc22016-11-02 12:14:56 -07001143 ad.droid.wifiStopTrackingTetherStateChange()
Ang Li82522812016-06-02 13:57:21 -07001144
Ang Li76216d12016-09-20 14:51:57 -07001145
Roshan Pius58916a32016-06-16 16:26:44 -07001146def toggle_wifi_and_wait_for_reconnection(ad,
1147 network,
1148 num_of_tries=1,
1149 assert_on_fail=True):
1150 """Toggle wifi state and then wait for Android device to reconnect to
1151 the provided wifi network.
1152
1153 This expects the device to be already connected to the provided network.
1154
1155 Logic steps are
1156 1. Ensure that we're connected to the network.
1157 2. Turn wifi off.
1158 3. Wait for 10 seconds.
1159 4. Turn wifi on.
1160 5. Wait for the "connected" event, then confirm the connected ssid is the
1161 one requested.
1162
1163 Args:
1164 ad: android_device object to initiate connection on.
1165 network: A dictionary representing the network to await connection. The
1166 dictionary must have the key "SSID".
1167 num_of_tries: An integer that is the number of times to try before
1168 delaring failure. Default is 1.
1169 assert_on_fail: If True, error checks in this function will raise test
1170 failure signals.
1171
1172 Returns:
1173 If assert_on_fail is False, function returns True if the toggle was
1174 successful, False otherwise. If assert_on_fail is True, no return value.
1175 """
Omar El Ayach8c017902020-10-18 10:26:57 -07001176 return _assert_on_fail_handler(_toggle_wifi_and_wait_for_reconnection,
1177 assert_on_fail,
1178 ad,
1179 network,
1180 num_of_tries=num_of_tries)
Roshan Pius58916a32016-06-16 16:26:44 -07001181
1182
Girish Moturu5d9f4202019-12-03 15:29:21 -08001183def _toggle_wifi_and_wait_for_reconnection(ad, network, num_of_tries=3):
Roshan Pius58916a32016-06-16 16:26:44 -07001184 """Toggle wifi state and then wait for Android device to reconnect to
1185 the provided wifi network.
1186
1187 This expects the device to be already connected to the provided network.
1188
1189 Logic steps are
1190 1. Ensure that we're connected to the network.
1191 2. Turn wifi off.
1192 3. Wait for 10 seconds.
1193 4. Turn wifi on.
1194 5. Wait for the "connected" event, then confirm the connected ssid is the
1195 one requested.
1196
1197 This will directly fail a test if anything goes wrong.
1198
1199 Args:
1200 ad: android_device object to initiate connection on.
1201 network: A dictionary representing the network to await connection. The
1202 dictionary must have the key "SSID".
1203 num_of_tries: An integer that is the number of times to try before
1204 delaring failure. Default is 1.
1205 """
Roshan Pius58916a32016-06-16 16:26:44 -07001206 expected_ssid = network[WifiEnums.SSID_KEY]
1207 # First ensure that we're already connected to the provided network.
1208 verify_con = {WifiEnums.SSID_KEY: expected_ssid}
1209 verify_wifi_connection_info(ad, verify_con)
1210 # Now toggle wifi state and wait for the connection event.
1211 wifi_toggle_state(ad, False)
1212 time.sleep(10)
1213 wifi_toggle_state(ad, True)
1214 ad.droid.wifiStartTrackingStateChange()
1215 try:
1216 connect_result = None
1217 for i in range(num_of_tries):
1218 try:
Bindu Mahadev4e710362016-11-17 16:17:11 -08001219 connect_result = ad.ed.pop_event(wifi_constants.WIFI_CONNECTED,
Roshan Pius58916a32016-06-16 16:26:44 -07001220 30)
1221 break
1222 except Empty:
1223 pass
Omar El Ayach8c017902020-10-18 10:26:57 -07001224 asserts.assert_true(
1225 connect_result, "Failed to connect to Wi-Fi network %s on %s" %
1226 (network, ad.serial))
Betty Zhou3caa0982017-02-22 19:26:20 -08001227 logging.debug("Connection result on %s: %s.", ad.serial,
1228 connect_result)
Roshan Pius58916a32016-06-16 16:26:44 -07001229 actual_ssid = connect_result['data'][WifiEnums.SSID_KEY]
Omar El Ayach8c017902020-10-18 10:26:57 -07001230 asserts.assert_equal(
1231 actual_ssid, expected_ssid, "Connected to the wrong network on %s."
1232 "Expected %s, but got %s." %
1233 (ad.serial, expected_ssid, actual_ssid))
Betty Zhou3caa0982017-02-22 19:26:20 -08001234 logging.info("Connected to Wi-Fi network %s on %s", actual_ssid,
1235 ad.serial)
Roshan Pius58916a32016-06-16 16:26:44 -07001236 finally:
1237 ad.droid.wifiStopTrackingStateChange()
1238
1239
Omar El Ayach8c017902020-10-18 10:26:57 -07001240def wait_for_connect(ad,
1241 expected_ssid=None,
1242 expected_id=None,
1243 tries=2,
Oscar Shucb9af9b2019-05-02 20:01:49 +00001244 assert_on_fail=True):
Roshan Piusd1204442018-11-12 12:20:39 -08001245 """Wait for a connect event.
1246
1247 This will directly fail a test if anything goes wrong.
1248
1249 Args:
1250 ad: An Android device object.
1251 expected_ssid: SSID of the network to connect to.
1252 expected_id: Network Id of the network to connect to.
1253 tries: An integer that is the number of times to try before failing.
1254 assert_on_fail: If True, error checks in this function will raise test
1255 failure signals.
1256
1257 Returns:
1258 Returns a value only if assert_on_fail is false.
1259 Returns True if the connection was successful, False otherwise.
1260 """
Omar El Ayach8c017902020-10-18 10:26:57 -07001261 return _assert_on_fail_handler(_wait_for_connect, assert_on_fail, ad,
1262 expected_ssid, expected_id, tries)
Roshan Piusd1204442018-11-12 12:20:39 -08001263
1264
Oscar Shucb9af9b2019-05-02 20:01:49 +00001265def _wait_for_connect(ad, expected_ssid=None, expected_id=None, tries=2):
Roshan Piusd1204442018-11-12 12:20:39 -08001266 """Wait for a connect event.
1267
1268 Args:
1269 ad: An Android device object.
1270 expected_ssid: SSID of the network to connect to.
1271 expected_id: Network Id of the network to connect to.
1272 tries: An integer that is the number of times to try before failing.
1273 """
1274 ad.droid.wifiStartTrackingStateChange()
1275 try:
Omar El Ayach8c017902020-10-18 10:26:57 -07001276 connect_result = _wait_for_connect_event(ad,
1277 ssid=expected_ssid,
1278 id=expected_id,
1279 tries=tries)
1280 asserts.assert_true(
1281 connect_result,
1282 "Failed to connect to Wi-Fi network %s" % expected_ssid)
Roshan Piusd1204442018-11-12 12:20:39 -08001283 ad.log.debug("Wi-Fi connection result: %s.", connect_result)
1284 actual_ssid = connect_result['data'][WifiEnums.SSID_KEY]
1285 if expected_ssid:
1286 asserts.assert_equal(actual_ssid, expected_ssid,
1287 "Connected to the wrong network")
1288 actual_id = connect_result['data'][WifiEnums.NETID_KEY]
1289 if expected_id:
1290 asserts.assert_equal(actual_id, expected_id,
1291 "Connected to the wrong network")
1292 ad.log.info("Connected to Wi-Fi network %s.", actual_ssid)
1293 except Empty:
1294 asserts.fail("Failed to start connection process to %s" %
1295 expected_ssid)
1296 except Exception as error:
1297 ad.log.error("Failed to connect to %s with error %s", expected_ssid,
1298 error)
1299 raise signals.TestFailure("Failed to connect to %s network" %
1300 expected_ssid)
1301 finally:
1302 ad.droid.wifiStopTrackingStateChange()
1303
1304
Oscar Shucb9af9b2019-05-02 20:01:49 +00001305def _wait_for_connect_event(ad, ssid=None, id=None, tries=1):
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001306 """Wait for a connect event on queue and pop when available.
1307
1308 Args:
1309 ad: An Android device object.
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001310 ssid: SSID of the network to connect to.
1311 id: Network Id of the network to connect to.
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001312 tries: An integer that is the number of times to try before failing.
1313
1314 Returns:
1315 A dict with details of the connection data, which looks like this:
1316 {
1317 'time': 1485460337798,
1318 'name': 'WifiNetworkConnected',
1319 'data': {
1320 'rssi': -27,
1321 'is_24ghz': True,
1322 'mac_address': '02:00:00:00:00:00',
1323 'network_id': 1,
1324 'BSSID': '30:b5:c2:33:d3:fc',
1325 'ip_address': 117483712,
1326 'link_speed': 54,
1327 'supplicant_state': 'completed',
1328 'hidden_ssid': False,
1329 'SSID': 'wh_ap1_2g',
1330 'is_5ghz': False}
1331 }
1332
1333 """
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001334 conn_result = None
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001335
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001336 # If ssid and network id is None, just wait for any connect event.
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001337 if id is None and ssid is None:
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001338 for i in range(tries):
1339 try:
Omar El Ayach8c017902020-10-18 10:26:57 -07001340 conn_result = ad.ed.pop_event(wifi_constants.WIFI_CONNECTED,
1341 30)
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001342 break
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001343 except Empty:
1344 pass
1345 else:
Omar El Ayach8c017902020-10-18 10:26:57 -07001346 # If ssid or network id is specified, wait for specific connect event.
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001347 for i in range(tries):
1348 try:
Omar El Ayach8c017902020-10-18 10:26:57 -07001349 conn_result = ad.ed.pop_event(wifi_constants.WIFI_CONNECTED,
1350 30)
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001351 if id and conn_result['data'][WifiEnums.NETID_KEY] == id:
1352 break
1353 elif ssid and conn_result['data'][WifiEnums.SSID_KEY] == ssid:
1354 break
1355 except Empty:
1356 pass
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001357
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001358 return conn_result
1359
Bindu Mahadevff295782019-02-08 16:17:48 -08001360
Roshan Piusffc29912019-01-18 13:39:49 -08001361def wait_for_disconnect(ad, timeout=10):
1362 """Wait for a disconnect event within the specified timeout.
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001363
1364 Args:
1365 ad: Android device object.
Roshan Piusffc29912019-01-18 13:39:49 -08001366 timeout: Timeout in seconds.
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001367
1368 """
1369 try:
1370 ad.droid.wifiStartTrackingStateChange()
Roshan Piusffc29912019-01-18 13:39:49 -08001371 event = ad.ed.pop_event("WifiNetworkDisconnected", timeout)
Roshan Piusbf7e3982018-02-15 12:37:41 -08001372 except Empty:
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001373 raise signals.TestFailure("Device did not disconnect from the network")
Roshan Piusffc29912019-01-18 13:39:49 -08001374 finally:
1375 ad.droid.wifiStopTrackingStateChange()
1376
1377
1378def ensure_no_disconnect(ad, duration=10):
1379 """Ensure that there is no disconnect for the specified duration.
1380
1381 Args:
1382 ad: Android device object.
1383 duration: Duration in seconds.
1384
1385 """
1386 try:
1387 ad.droid.wifiStartTrackingStateChange()
1388 event = ad.ed.pop_event("WifiNetworkDisconnected", duration)
1389 raise signals.TestFailure("Device disconnected from the network")
1390 except Empty:
1391 pass
1392 finally:
1393 ad.droid.wifiStopTrackingStateChange()
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001394
1395
Omar El Ayach8c017902020-10-18 10:26:57 -07001396def connect_to_wifi_network(ad,
1397 network,
1398 assert_on_fail=True,
1399 check_connectivity=True,
1400 hidden=False):
Bindu Mahadev3876ae52017-12-19 14:22:19 -08001401 """Connection logic for open and psk wifi networks.
1402
1403 Args:
Jong Wook Kim92356922018-02-06 18:32:49 -08001404 ad: AndroidDevice to use for connection
1405 network: network info of the network to connect to
1406 assert_on_fail: If true, errors from wifi_connect will raise
1407 test failure signals.
Joe Brennan48c3f692019-04-11 08:30:16 -07001408 hidden: Is the Wifi network hidden.
Bindu Mahadev3876ae52017-12-19 14:22:19 -08001409 """
Joe Brennan48c3f692019-04-11 08:30:16 -07001410 if hidden:
1411 start_wifi_connection_scan_and_ensure_network_not_found(
1412 ad, network[WifiEnums.SSID_KEY])
1413 else:
1414 start_wifi_connection_scan_and_ensure_network_found(
1415 ad, network[WifiEnums.SSID_KEY])
Jong Wook Kim92356922018-02-06 18:32:49 -08001416 wifi_connect(ad,
1417 network,
1418 num_of_tries=3,
Bindu Mahadev27c2d292018-03-19 16:13:08 -07001419 assert_on_fail=assert_on_fail,
1420 check_connectivity=check_connectivity)
Bindu Mahadev3876ae52017-12-19 14:22:19 -08001421
1422
1423def connect_to_wifi_network_with_id(ad, network_id, network_ssid):
1424 """Connect to the given network using network id and verify SSID.
1425
1426 Args:
1427 network_id: int Network Id of the network.
1428 network_ssid: string SSID of the network.
1429
1430 Returns: True if connect using network id was successful;
1431 False otherwise.
1432
1433 """
Jong Wook Kim92356922018-02-06 18:32:49 -08001434 start_wifi_connection_scan_and_ensure_network_found(ad, network_ssid)
Bindu Mahadev3876ae52017-12-19 14:22:19 -08001435 wifi_connect_by_id(ad, network_id)
1436 connect_data = ad.droid.wifiGetConnectionInfo()
1437 connect_ssid = connect_data[WifiEnums.SSID_KEY]
1438 ad.log.debug("Expected SSID = %s Connected SSID = %s" %
Omar El Ayach8c017902020-10-18 10:26:57 -07001439 (network_ssid, connect_ssid))
Bindu Mahadev3876ae52017-12-19 14:22:19 -08001440 if connect_ssid != network_ssid:
1441 return False
1442 return True
1443
1444
Omar El Ayach8c017902020-10-18 10:26:57 -07001445def wifi_connect(ad,
1446 network,
1447 num_of_tries=1,
1448 assert_on_fail=True,
1449 check_connectivity=True):
Ang Li99d8c6d2015-12-09 15:56:13 -08001450 """Connect an Android device to a wifi network.
Ang Li73697b32015-12-03 00:41:53 +00001451
1452 Initiate connection to a wifi network, wait for the "connected" event, then
Ang Li99d8c6d2015-12-09 15:56:13 -08001453 confirm the connected ssid is the one requested.
Ang Li73697b32015-12-03 00:41:53 +00001454
Ang Li82522812016-06-02 13:57:21 -07001455 This will directly fail a test if anything goes wrong.
1456
Ang Li73697b32015-12-03 00:41:53 +00001457 Args:
1458 ad: android_device object to initiate connection on.
Ang Li99d8c6d2015-12-09 15:56:13 -08001459 network: A dictionary representing the network to connect to. The
Ang Li82522812016-06-02 13:57:21 -07001460 dictionary must have the key "SSID".
1461 num_of_tries: An integer that is the number of times to try before
1462 delaring failure. Default is 1.
1463 assert_on_fail: If True, error checks in this function will raise test
1464 failure signals.
1465
1466 Returns:
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001467 Returns a value only if assert_on_fail is false.
1468 Returns True if the connection was successful, False otherwise.
Ang Li73697b32015-12-03 00:41:53 +00001469 """
Omar El Ayach8c017902020-10-18 10:26:57 -07001470 return _assert_on_fail_handler(_wifi_connect,
1471 assert_on_fail,
1472 ad,
1473 network,
1474 num_of_tries=num_of_tries,
1475 check_connectivity=check_connectivity)
Ang Li82522812016-06-02 13:57:21 -07001476
1477
Oscar Shucb9af9b2019-05-02 20:01:49 +00001478def _wifi_connect(ad, network, num_of_tries=1, check_connectivity=True):
Ang Li82522812016-06-02 13:57:21 -07001479 """Connect an Android device to a wifi network.
1480
1481 Initiate connection to a wifi network, wait for the "connected" event, then
1482 confirm the connected ssid is the one requested.
1483
1484 This will directly fail a test if anything goes wrong.
1485
1486 Args:
1487 ad: android_device object to initiate connection on.
1488 network: A dictionary representing the network to connect to. The
1489 dictionary must have the key "SSID".
1490 num_of_tries: An integer that is the number of times to try before
1491 delaring failure. Default is 1.
1492 """
Omar El Ayach8c017902020-10-18 10:26:57 -07001493 asserts.assert_true(
1494 WifiEnums.SSID_KEY in network,
1495 "Key '%s' must be present in network definition." % WifiEnums.SSID_KEY)
Ang Li99d8c6d2015-12-09 15:56:13 -08001496 ad.droid.wifiStartTrackingStateChange()
Betty Zhoud35dab82016-12-06 15:24:23 -08001497 expected_ssid = network[WifiEnums.SSID_KEY]
Bindu Mahadev50374df2017-01-04 11:03:32 -08001498 ad.droid.wifiConnectByConfig(network)
1499 ad.log.info("Starting connection process to %s", expected_ssid)
Ang Li73697b32015-12-03 00:41:53 +00001500 try:
Bindu Mahadev50374df2017-01-04 11:03:32 -08001501 event = ad.ed.pop_event(wifi_constants.CONNECT_BY_CONFIG_SUCCESS, 30)
Omar El Ayach8c017902020-10-18 10:26:57 -07001502 connect_result = _wait_for_connect_event(ad,
1503 ssid=expected_ssid,
1504 tries=num_of_tries)
1505 asserts.assert_true(
1506 connect_result, "Failed to connect to Wi-Fi network %s on %s" %
1507 (network, ad.serial))
Ang Li31b00782016-06-21 13:04:23 -07001508 ad.log.debug("Wi-Fi connection result: %s.", connect_result)
Ang Li99d8c6d2015-12-09 15:56:13 -08001509 actual_ssid = connect_result['data'][WifiEnums.SSID_KEY]
Omar El Ayach8c017902020-10-18 10:26:57 -07001510 asserts.assert_equal(
1511 actual_ssid, expected_ssid,
1512 "Connected to the wrong network on %s." % ad.serial)
Ang Li31b00782016-06-21 13:04:23 -07001513 ad.log.info("Connected to Wi-Fi network %s.", actual_ssid)
Bindu Mahadev50374df2017-01-04 11:03:32 -08001514
Bindu Mahadev27c2d292018-03-19 16:13:08 -07001515 if check_connectivity:
Hsiu-Chang Chend7b3c572020-06-12 12:19:30 +08001516 internet = validate_connection(ad, DEFAULT_PING_ADDR)
Bindu Mahadev27c2d292018-03-19 16:13:08 -07001517 if not internet:
Omar El Ayach8c017902020-10-18 10:26:57 -07001518 raise signals.TestFailure(
1519 "Failed to connect to internet on %s" % expected_ssid)
Bindu Mahadev50374df2017-01-04 11:03:32 -08001520 except Empty:
1521 asserts.fail("Failed to start connection process to %s on %s" %
1522 (network, ad.serial))
Bindu Mahadev4e710362016-11-17 16:17:11 -08001523 except Exception as error:
Bindu Mahadev50374df2017-01-04 11:03:32 -08001524 ad.log.error("Failed to connect to %s with error %s", expected_ssid,
1525 error)
1526 raise signals.TestFailure("Failed to connect to %s network" % network)
1527
Ang Li73697b32015-12-03 00:41:53 +00001528 finally:
Ang Li99d8c6d2015-12-09 15:56:13 -08001529 ad.droid.wifiStopTrackingStateChange()
Ang Li73697b32015-12-03 00:41:53 +00001530
Bindu Mahadev50374df2017-01-04 11:03:32 -08001531
Oscar Shucb9af9b2019-05-02 20:01:49 +00001532def wifi_connect_by_id(ad, network_id, num_of_tries=3, assert_on_fail=True):
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001533 """Connect an Android device to a wifi network using network Id.
1534
1535 Start connection to the wifi network, with the given network Id, wait for
1536 the "connected" event, then verify the connected network is the one requested.
1537
1538 This will directly fail a test if anything goes wrong.
1539
1540 Args:
1541 ad: android_device object to initiate connection on.
1542 network_id: Integer specifying the network id of the network.
1543 num_of_tries: An integer that is the number of times to try before
1544 delaring failure. Default is 1.
1545 assert_on_fail: If True, error checks in this function will raise test
1546 failure signals.
1547
1548 Returns:
1549 Returns a value only if assert_on_fail is false.
1550 Returns True if the connection was successful, False otherwise.
1551 """
1552 _assert_on_fail_handler(_wifi_connect_by_id, assert_on_fail, ad,
Oscar Shucb9af9b2019-05-02 20:01:49 +00001553 network_id, num_of_tries)
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001554
1555
Oscar Shucb9af9b2019-05-02 20:01:49 +00001556def _wifi_connect_by_id(ad, network_id, num_of_tries=1):
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001557 """Connect an Android device to a wifi network using it's network id.
1558
1559 Start connection to the wifi network, with the given network id, wait for
1560 the "connected" event, then verify the connected network is the one requested.
1561
1562 Args:
1563 ad: android_device object to initiate connection on.
1564 network_id: Integer specifying the network id of the network.
1565 num_of_tries: An integer that is the number of times to try before
1566 delaring failure. Default is 1.
1567 """
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001568 ad.droid.wifiStartTrackingStateChange()
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001569 # Clear all previous events.
1570 ad.ed.clear_all_events()
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001571 ad.droid.wifiConnectByNetworkId(network_id)
1572 ad.log.info("Starting connection to network with id %d", network_id)
1573 try:
1574 event = ad.ed.pop_event(wifi_constants.CONNECT_BY_NETID_SUCCESS, 60)
Omar El Ayach8c017902020-10-18 10:26:57 -07001575 connect_result = _wait_for_connect_event(ad,
1576 id=network_id,
1577 tries=num_of_tries)
1578 asserts.assert_true(
1579 connect_result,
1580 "Failed to connect to Wi-Fi network using network id")
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001581 ad.log.debug("Wi-Fi connection result: %s", connect_result)
1582 actual_id = connect_result['data'][WifiEnums.NETID_KEY]
Omar El Ayach8c017902020-10-18 10:26:57 -07001583 asserts.assert_equal(
1584 actual_id, network_id, "Connected to the wrong network on %s."
1585 "Expected network id = %d, but got %d." %
1586 (ad.serial, network_id, actual_id))
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001587 expected_ssid = connect_result['data'][WifiEnums.SSID_KEY]
1588 ad.log.info("Connected to Wi-Fi network %s with %d network id.",
Omar El Ayach8c017902020-10-18 10:26:57 -07001589 expected_ssid, network_id)
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001590
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001591 internet = validate_connection(ad, DEFAULT_PING_ADDR)
1592 if not internet:
1593 raise signals.TestFailure("Failed to connect to internet on %s" %
1594 expected_ssid)
1595 except Empty:
1596 asserts.fail("Failed to connect to network with id %d on %s" %
Omar El Ayach8c017902020-10-18 10:26:57 -07001597 (network_id, ad.serial))
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001598 except Exception as error:
1599 ad.log.error("Failed to connect to network with id %d with error %s",
Omar El Ayach8c017902020-10-18 10:26:57 -07001600 network_id, error)
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001601 raise signals.TestFailure("Failed to connect to network with network"
1602 " id %d" % network_id)
1603 finally:
1604 ad.droid.wifiStopTrackingStateChange()
1605
Oscar Shu0b5ff4d2019-08-07 18:11:56 +00001606
Omar El Ayach8c017902020-10-18 10:26:57 -07001607def wifi_connect_using_network_request(ad,
1608 network,
1609 network_specifier,
Roshan Pius5561d232021-01-22 16:34:39 -08001610 num_of_tries=3):
Roshan Piusc999e5e2018-11-09 10:59:52 -08001611 """Connect an Android device to a wifi network using network request.
1612
1613 Trigger a network request with the provided network specifier,
1614 wait for the "onMatch" event, ensure that the scan results in "onMatch"
1615 event contain the specified network, then simulate the user granting the
1616 request with the specified network selected. Then wait for the "onAvailable"
1617 network callback indicating successful connection to network.
1618
1619 Args:
1620 ad: android_device object to initiate connection on.
1621 network_specifier: A dictionary representing the network specifier to
1622 use.
1623 network: A dictionary representing the network to connect to. The
1624 dictionary must have the key "SSID".
1625 num_of_tries: An integer that is the number of times to try before
1626 delaring failure.
Roshan Pius5fd42eb2021-01-21 12:26:31 -08001627 Returns:
1628 key: Key corresponding to network request.
Roshan Piusc999e5e2018-11-09 10:59:52 -08001629 """
Roshan Pius5fd42eb2021-01-21 12:26:31 -08001630 key = ad.droid.connectivityRequestWifiNetwork(network_specifier, 0)
1631 ad.log.info("Sent network request %s with %s " % (key, network_specifier))
Roshan Piusc999e5e2018-11-09 10:59:52 -08001632 # Need a delay here because UI interaction should only start once wifi
1633 # starts processing the request.
1634 time.sleep(wifi_constants.NETWORK_REQUEST_CB_REGISTER_DELAY_SEC)
Roshan Pius5fd42eb2021-01-21 12:26:31 -08001635 _wait_for_wifi_connect_after_network_request(ad, network, key, num_of_tries)
1636 return key
Roshan Piusc999e5e2018-11-09 10:59:52 -08001637
1638
Omar El Ayach8c017902020-10-18 10:26:57 -07001639def wait_for_wifi_connect_after_network_request(ad,
1640 network,
Roshan Pius5fd42eb2021-01-21 12:26:31 -08001641 key,
Omar El Ayach8c017902020-10-18 10:26:57 -07001642 num_of_tries=3,
Roshan Piusc999e5e2018-11-09 10:59:52 -08001643 assert_on_fail=True):
1644 """
1645 Simulate and verify the connection flow after initiating the network
1646 request.
1647
1648 Wait for the "onMatch" event, ensure that the scan results in "onMatch"
1649 event contain the specified network, then simulate the user granting the
1650 request with the specified network selected. Then wait for the "onAvailable"
1651 network callback indicating successful connection to network.
1652
1653 Args:
1654 ad: android_device object to initiate connection on.
1655 network: A dictionary representing the network to connect to. The
1656 dictionary must have the key "SSID".
Roshan Pius5fd42eb2021-01-21 12:26:31 -08001657 key: Key corresponding to network request.
Roshan Piusc999e5e2018-11-09 10:59:52 -08001658 num_of_tries: An integer that is the number of times to try before
1659 delaring failure.
1660 assert_on_fail: If True, error checks in this function will raise test
1661 failure signals.
1662
1663 Returns:
1664 Returns a value only if assert_on_fail is false.
1665 Returns True if the connection was successful, False otherwise.
1666 """
1667 _assert_on_fail_handler(_wait_for_wifi_connect_after_network_request,
Roshan Pius5fd42eb2021-01-21 12:26:31 -08001668 assert_on_fail, ad, network, key, num_of_tries)
Roshan Piusc999e5e2018-11-09 10:59:52 -08001669
1670
Roshan Pius5fd42eb2021-01-21 12:26:31 -08001671def _wait_for_wifi_connect_after_network_request(ad, network, key, num_of_tries=3):
Roshan Piusc999e5e2018-11-09 10:59:52 -08001672 """
1673 Simulate and verify the connection flow after initiating the network
1674 request.
1675
1676 Wait for the "onMatch" event, ensure that the scan results in "onMatch"
1677 event contain the specified network, then simulate the user granting the
1678 request with the specified network selected. Then wait for the "onAvailable"
1679 network callback indicating successful connection to network.
1680
1681 Args:
1682 ad: android_device object to initiate connection on.
1683 network: A dictionary representing the network to connect to. The
1684 dictionary must have the key "SSID".
Roshan Pius5fd42eb2021-01-21 12:26:31 -08001685 key: Key corresponding to network request.
Roshan Piusc999e5e2018-11-09 10:59:52 -08001686 num_of_tries: An integer that is the number of times to try before
1687 delaring failure.
1688 """
Omar El Ayach8c017902020-10-18 10:26:57 -07001689 asserts.assert_true(
1690 WifiEnums.SSID_KEY in network,
1691 "Key '%s' must be present in network definition." % WifiEnums.SSID_KEY)
Roshan Piusc999e5e2018-11-09 10:59:52 -08001692 ad.droid.wifiStartTrackingStateChange()
1693 expected_ssid = network[WifiEnums.SSID_KEY]
1694 ad.droid.wifiRegisterNetworkRequestMatchCallback()
1695 # Wait for the platform to scan and return a list of networks
1696 # matching the request
1697 try:
1698 matched_network = None
Omar El Ayach8c017902020-10-18 10:26:57 -07001699 for _ in [0, num_of_tries]:
Roshan Piusc999e5e2018-11-09 10:59:52 -08001700 on_match_event = ad.ed.pop_event(
1701 wifi_constants.WIFI_NETWORK_REQUEST_MATCH_CB_ON_MATCH, 60)
1702 asserts.assert_true(on_match_event,
1703 "Network request on match not received.")
1704 matched_scan_results = on_match_event["data"]
1705 ad.log.debug("Network request on match results %s",
1706 matched_scan_results)
1707 matched_network = match_networks(
1708 {WifiEnums.SSID_KEY: network[WifiEnums.SSID_KEY]},
1709 matched_scan_results)
Roshan Pius6cd4aaf2021-02-09 15:54:30 -08001710 ad.log.debug("Network request on match %s", matched_network)
Roshan Piusc999e5e2018-11-09 10:59:52 -08001711 if matched_network:
Omar El Ayach8c017902020-10-18 10:26:57 -07001712 break
Roshan Piusc999e5e2018-11-09 10:59:52 -08001713
Omar El Ayach8c017902020-10-18 10:26:57 -07001714 asserts.assert_true(matched_network,
1715 "Target network %s not found" % network)
Roshan Piusc999e5e2018-11-09 10:59:52 -08001716
1717 ad.droid.wifiSendUserSelectionForNetworkRequestMatch(network)
1718 ad.log.info("Sent user selection for network request %s",
1719 expected_ssid)
1720
1721 # Wait for the platform to connect to the network.
Roshan Pius5fd42eb2021-01-21 12:26:31 -08001722 autils.wait_for_event_with_keys(
1723 ad, cconsts.EVENT_NETWORK_CALLBACK,
1724 60,
1725 (cconsts.NETWORK_CB_KEY_ID, key),
1726 (cconsts.NETWORK_CB_KEY_EVENT, cconsts.NETWORK_CB_AVAILABLE))
1727 on_capabilities_changed = autils.wait_for_event_with_keys(
1728 ad, cconsts.EVENT_NETWORK_CALLBACK,
1729 10,
1730 (cconsts.NETWORK_CB_KEY_ID, key),
1731 (cconsts.NETWORK_CB_KEY_EVENT,
1732 cconsts.NETWORK_CB_CAPABILITIES_CHANGED))
Roshan Pius008fe7f2021-03-25 14:18:17 -07001733 connected_network = None
1734 # WifiInfo is attached to TransportInfo only in S.
1735 if ad.droid.isSdkAtLeastS():
1736 connected_network = (
1737 on_capabilities_changed["data"][
1738 cconsts.NETWORK_CB_KEY_TRANSPORT_INFO]
1739 )
1740 else:
1741 connected_network = ad.droid.wifiGetConnectionInfo()
Roshan Piusc999e5e2018-11-09 10:59:52 -08001742 ad.log.info("Connected to network %s", connected_network)
Omar El Ayach8c017902020-10-18 10:26:57 -07001743 asserts.assert_equal(
1744 connected_network[WifiEnums.SSID_KEY], expected_ssid,
1745 "Connected to the wrong network."
Roshan Pius5fd42eb2021-01-21 12:26:31 -08001746 "Expected %s, but got %s."
1747 % (network, connected_network))
Roshan Piusc999e5e2018-11-09 10:59:52 -08001748 except Empty:
1749 asserts.fail("Failed to connect to %s" % expected_ssid)
1750 except Exception as error:
Roshan Pius5fd42eb2021-01-21 12:26:31 -08001751 ad.log.error("Failed to connect to %s with error %s" %
Roshan Piusc999e5e2018-11-09 10:59:52 -08001752 (expected_ssid, error))
1753 raise signals.TestFailure("Failed to connect to %s network" % network)
1754 finally:
1755 ad.droid.wifiStopTrackingStateChange()
1756
1757
Omar El Ayach8c017902020-10-18 10:26:57 -07001758def wifi_passpoint_connect(ad,
1759 passpoint_network,
1760 num_of_tries=1,
Oscar Shucb9af9b2019-05-02 20:01:49 +00001761 assert_on_fail=True):
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001762 """Connect an Android device to a wifi network.
1763
1764 Initiate connection to a wifi network, wait for the "connected" event, then
1765 confirm the connected ssid is the one requested.
1766
1767 This will directly fail a test if anything goes wrong.
1768
1769 Args:
1770 ad: android_device object to initiate connection on.
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001771 passpoint_network: SSID of the Passpoint network to connect to.
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001772 num_of_tries: An integer that is the number of times to try before
1773 delaring failure. Default is 1.
1774 assert_on_fail: If True, error checks in this function will raise test
1775 failure signals.
1776
1777 Returns:
1778 If assert_on_fail is False, function returns network id, if the connect was
1779 successful, False otherwise. If assert_on_fail is True, no return value.
1780 """
Omar El Ayach8c017902020-10-18 10:26:57 -07001781 _assert_on_fail_handler(_wifi_passpoint_connect,
1782 assert_on_fail,
1783 ad,
1784 passpoint_network,
1785 num_of_tries=num_of_tries)
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001786
1787
Oscar Shucb9af9b2019-05-02 20:01:49 +00001788def _wifi_passpoint_connect(ad, passpoint_network, num_of_tries=1):
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001789 """Connect an Android device to a wifi network.
1790
1791 Initiate connection to a wifi network, wait for the "connected" event, then
1792 confirm the connected ssid is the one requested.
1793
1794 This will directly fail a test if anything goes wrong.
1795
1796 Args:
1797 ad: android_device object to initiate connection on.
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001798 passpoint_network: SSID of the Passpoint network to connect to.
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001799 num_of_tries: An integer that is the number of times to try before
1800 delaring failure. Default is 1.
1801 """
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001802 ad.droid.wifiStartTrackingStateChange()
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001803 expected_ssid = passpoint_network
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001804 ad.log.info("Starting connection process to passpoint %s", expected_ssid)
1805
1806 try:
Omar El Ayach8c017902020-10-18 10:26:57 -07001807 connect_result = _wait_for_connect_event(ad, expected_ssid,
1808 num_of_tries)
1809 asserts.assert_true(
1810 connect_result, "Failed to connect to WiFi passpoint network %s on"
1811 " %s" % (expected_ssid, ad.serial))
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001812 ad.log.info("Wi-Fi connection result: %s.", connect_result)
1813 actual_ssid = connect_result['data'][WifiEnums.SSID_KEY]
Omar El Ayach8c017902020-10-18 10:26:57 -07001814 asserts.assert_equal(
1815 actual_ssid, expected_ssid,
1816 "Connected to the wrong network on %s." % ad.serial)
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001817 ad.log.info("Connected to Wi-Fi passpoint network %s.", actual_ssid)
1818
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001819 internet = validate_connection(ad, DEFAULT_PING_ADDR)
1820 if not internet:
1821 raise signals.TestFailure("Failed to connect to internet on %s" %
1822 expected_ssid)
1823 except Exception as error:
1824 ad.log.error("Failed to connect to passpoint network %s with error %s",
Omar El Ayach8c017902020-10-18 10:26:57 -07001825 expected_ssid, error)
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001826 raise signals.TestFailure("Failed to connect to %s passpoint network" %
Omar El Ayach8c017902020-10-18 10:26:57 -07001827 expected_ssid)
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001828
1829 finally:
1830 ad.droid.wifiStopTrackingStateChange()
1831
1832
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001833def delete_passpoint(ad, fqdn):
1834 """Delete a required Passpoint configuration."""
1835 try:
1836 ad.droid.removePasspointConfig(fqdn)
1837 return True
1838 except Exception as error:
Omar El Ayach8c017902020-10-18 10:26:57 -07001839 ad.log.error(
1840 "Failed to remove passpoint configuration with FQDN=%s "
1841 "and error=%s", fqdn, error)
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001842 return False
1843
1844
Ang Li73697b32015-12-03 00:41:53 +00001845def start_wifi_single_scan(ad, scan_setting):
1846 """Starts wifi single shot scan.
1847
1848 Args:
1849 ad: android_device object to initiate connection on.
1850 scan_setting: A dict representing the settings of the scan.
1851
1852 Returns:
1853 If scan was started successfully, event data of success event is returned.
1854 """
Ang Li82522812016-06-02 13:57:21 -07001855 idx = ad.droid.wifiScannerStartScan(scan_setting)
1856 event = ad.ed.pop_event("WifiScannerScan%sonSuccess" % idx, SHORT_TIMEOUT)
Ang Li31b00782016-06-21 13:04:23 -07001857 ad.log.debug("Got event %s", event)
Ang Li73697b32015-12-03 00:41:53 +00001858 return event['data']
1859
Ang Li82522812016-06-02 13:57:21 -07001860
Ang Li73697b32015-12-03 00:41:53 +00001861def track_connection(ad, network_ssid, check_connection_count):
1862 """Track wifi connection to network changes for given number of counts
1863
1864 Args:
1865 ad: android_device object for forget network.
1866 network_ssid: network ssid to which connection would be tracked
1867 check_connection_count: Integer for maximum number network connection
Ang Li82522812016-06-02 13:57:21 -07001868 check.
Ang Li73697b32015-12-03 00:41:53 +00001869 Returns:
Ang Li73697b32015-12-03 00:41:53 +00001870 True if connection to given network happen, else return False.
1871 """
Girish Moturu40d7dc22016-11-02 12:14:56 -07001872 ad.droid.wifiStartTrackingStateChange()
Ang Li73697b32015-12-03 00:41:53 +00001873 while check_connection_count > 0:
Girish Moturu40d7dc22016-11-02 12:14:56 -07001874 connect_network = ad.ed.pop_event("WifiNetworkConnected", 120)
Ang Li31b00782016-06-21 13:04:23 -07001875 ad.log.info("Connected to network %s", connect_network)
Ang Li82522812016-06-02 13:57:21 -07001876 if (WifiEnums.SSID_KEY in connect_network['data'] and
1877 connect_network['data'][WifiEnums.SSID_KEY] == network_ssid):
1878 return True
Ang Li8e767182015-12-09 17:29:24 -08001879 check_connection_count -= 1
Girish Moturu40d7dc22016-11-02 12:14:56 -07001880 ad.droid.wifiStopTrackingStateChange()
Ang Li73697b32015-12-03 00:41:53 +00001881 return False
1882
Ang Li82522812016-06-02 13:57:21 -07001883
Ang Li73697b32015-12-03 00:41:53 +00001884def get_scan_time_and_channels(wifi_chs, scan_setting, stime_channel):
1885 """Calculate the scan time required based on the band or channels in scan
1886 setting
1887
1888 Args:
1889 wifi_chs: Object of channels supported
1890 scan_setting: scan setting used for start scan
1891 stime_channel: scan time per channel
1892
1893 Returns:
1894 scan_time: time required for completing a scan
1895 scan_channels: channel used for scanning
1896 """
1897 scan_time = 0
1898 scan_channels = []
1899 if "band" in scan_setting and "channels" not in scan_setting:
Ang Li8e767182015-12-09 17:29:24 -08001900 scan_channels = wifi_chs.band_to_freq(scan_setting["band"])
Ang Li73697b32015-12-03 00:41:53 +00001901 elif "channels" in scan_setting and "band" not in scan_setting:
Ang Li8e767182015-12-09 17:29:24 -08001902 scan_channels = scan_setting["channels"]
Ang Li73697b32015-12-03 00:41:53 +00001903 scan_time = len(scan_channels) * stime_channel
1904 for channel in scan_channels:
Ang Li8e767182015-12-09 17:29:24 -08001905 if channel in WifiEnums.DFS_5G_FREQUENCIES:
Ang Li82522812016-06-02 13:57:21 -07001906 scan_time += 132 #passive scan time on DFS
Ang Li73697b32015-12-03 00:41:53 +00001907 return scan_time, scan_channels
1908
Ang Li82522812016-06-02 13:57:21 -07001909
Ang Li73697b32015-12-03 00:41:53 +00001910def start_wifi_track_bssid(ad, track_setting):
1911 """Start tracking Bssid for the given settings.
1912
1913 Args:
1914 ad: android_device object.
1915 track_setting: Setting for which the bssid tracking should be started
1916
1917 Returns:
1918 If tracking started successfully, event data of success event is returned.
1919 """
Girish Moturu40d7dc22016-11-02 12:14:56 -07001920 idx = ad.droid.wifiScannerStartTrackingBssids(
Ang Li82522812016-06-02 13:57:21 -07001921 track_setting["bssidInfos"], track_setting["apLostThreshold"])
Girish Moturu40d7dc22016-11-02 12:14:56 -07001922 event = ad.ed.pop_event("WifiScannerBssid{}onSuccess".format(idx),
Betty Zhou3caa0982017-02-22 19:26:20 -08001923 SHORT_TIMEOUT)
Ang Li73697b32015-12-03 00:41:53 +00001924 return event['data']
1925
Ang Li82522812016-06-02 13:57:21 -07001926
Ang Li73697b32015-12-03 00:41:53 +00001927def convert_pem_key_to_pkcs8(in_file, out_file):
1928 """Converts the key file generated by us to the format required by
1929 Android using openssl.
1930
1931 The input file must have the extension "pem". The output file must
1932 have the extension "der".
1933
1934 Args:
1935 in_file: The original key file.
1936 out_file: The full path to the converted key file, including
1937 filename.
1938 """
Ang Li82522812016-06-02 13:57:21 -07001939 asserts.assert_true(in_file.endswith(".pem"), "Input file has to be .pem.")
Omar El Ayach8c017902020-10-18 10:26:57 -07001940 asserts.assert_true(out_file.endswith(".der"),
1941 "Output file has to be .der.")
Ang Li73697b32015-12-03 00:41:53 +00001942 cmd = ("openssl pkcs8 -inform PEM -in {} -outform DER -out {} -nocrypt"
1943 " -topk8").format(in_file, out_file)
Ang Lifee28402016-07-13 13:43:29 -07001944 utils.exe_cmd(cmd)
Ang Li73697b32015-12-03 00:41:53 +00001945
Ang Li82522812016-06-02 13:57:21 -07001946
Omar El Ayach8c017902020-10-18 10:26:57 -07001947def validate_connection(ad,
1948 ping_addr=DEFAULT_PING_ADDR,
1949 wait_time=15,
Girish Moturu804a3492020-02-17 14:32:02 -08001950 ping_gateway=True):
Ang Li73697b32015-12-03 00:41:53 +00001951 """Validate internet connection by pinging the address provided.
1952
1953 Args:
1954 ad: android_device object.
1955 ping_addr: address on internet for pinging.
Girish Moturua2a5bf22019-08-16 09:52:29 -07001956 wait_time: wait for some time before validating connection
Ang Li73697b32015-12-03 00:41:53 +00001957
1958 Returns:
Bindu Mahadev50374df2017-01-04 11:03:32 -08001959 ping output if successful, NULL otherwise.
Ang Li73697b32015-12-03 00:41:53 +00001960 """
Girish Moturua2a5bf22019-08-16 09:52:29 -07001961 # wait_time to allow for DHCP to complete.
Hsiu-Chang Chend7b3c572020-06-12 12:19:30 +08001962 for i in range(wait_time):
Girish Moturuacf35002020-11-09 23:37:35 -08001963 if ad.droid.connectivityNetworkIsConnected(
Omar El Ayach8c017902020-10-18 10:26:57 -07001964 ) and ad.droid.connectivityGetIPv4DefaultGateway():
Hsiu-Chang Chend7b3c572020-06-12 12:19:30 +08001965 break
1966 time.sleep(1)
Girish Moturu804a3492020-02-17 14:32:02 -08001967 ping = False
1968 try:
1969 ping = ad.droid.httpPing(ping_addr)
1970 ad.log.info("Http ping result: %s.", ping)
1971 except:
1972 pass
1973 if not ping and ping_gateway:
1974 ad.log.info("Http ping failed. Pinging default gateway")
1975 gw = ad.droid.connectivityGetIPv4DefaultGateway()
1976 result = ad.adb.shell("ping -c 6 {}".format(gw))
1977 ad.log.info("Default gateway ping result: %s" % result)
1978 ping = False if "100% packet loss" in result else True
Ang Li73697b32015-12-03 00:41:53 +00001979 return ping
1980
Ang Li82522812016-06-02 13:57:21 -07001981
Ang Li73697b32015-12-03 00:41:53 +00001982#TODO(angli): This can only verify if an actual value is exactly the same.
1983# Would be nice to be able to verify an actual value is one of serveral.
1984def verify_wifi_connection_info(ad, expected_con):
1985 """Verifies that the information of the currently connected wifi network is
1986 as expected.
1987
1988 Args:
1989 expected_con: A dict representing expected key-value pairs for wifi
1990 connection. e.g. {"SSID": "test_wifi"}
1991 """
1992 current_con = ad.droid.wifiGetConnectionInfo()
Ang Li374d7602016-02-08 17:27:27 -08001993 case_insensitive = ["BSSID", "supplicant_state"]
Ang Li31b00782016-06-21 13:04:23 -07001994 ad.log.debug("Current connection: %s", current_con)
Ang Li73697b32015-12-03 00:41:53 +00001995 for k, expected_v in expected_con.items():
Ang Li9a66de72016-02-08 15:26:38 -08001996 # Do not verify authentication related fields.
1997 if k == "password":
1998 continue
Ang Li82522812016-06-02 13:57:21 -07001999 msg = "Field %s does not exist in wifi connection info %s." % (
2000 k, current_con)
Ang Li374d7602016-02-08 17:27:27 -08002001 if k not in current_con:
2002 raise signals.TestFailure(msg)
2003 actual_v = current_con[k]
2004 if k in case_insensitive:
2005 actual_v = actual_v.lower()
2006 expected_v = expected_v.lower()
Ang Li73697b32015-12-03 00:41:53 +00002007 msg = "Expected %s to be %s, actual %s is %s." % (k, expected_v, k,
Ang Li82522812016-06-02 13:57:21 -07002008 actual_v)
Ang Li374d7602016-02-08 17:27:27 -08002009 if actual_v != expected_v:
2010 raise signals.TestFailure(msg)
Ang Li73697b32015-12-03 00:41:53 +00002011
Ang Li82522812016-06-02 13:57:21 -07002012
Omar El Ayach8c017902020-10-18 10:26:57 -07002013def check_autoconnect_to_open_network(
2014 ad, conn_timeout=WIFI_CONNECTION_TIMEOUT_DEFAULT):
Preetesh Barrettoe8c428b2019-02-14 09:15:44 -08002015 """Connects to any open WiFI AP
2016 Args:
2017 timeout value in sec to wait for UE to connect to a WiFi AP
2018 Returns:
2019 True if UE connects to WiFi AP (supplicant_state = completed)
2020 False if UE fails to complete connection within WIFI_CONNECTION_TIMEOUT time.
2021 """
2022 if ad.droid.wifiCheckState():
2023 return True
2024 ad.droid.wifiToggleState()
2025 wifi_connection_state = None
2026 timeout = time.time() + conn_timeout
2027 while wifi_connection_state != "completed":
Omar El Ayach8c017902020-10-18 10:26:57 -07002028 wifi_connection_state = ad.droid.wifiGetConnectionInfo(
2029 )['supplicant_state']
Preetesh Barrettoe8c428b2019-02-14 09:15:44 -08002030 if time.time() > timeout:
2031 ad.log.warning("Failed to connect to WiFi AP")
2032 return False
2033 return True
2034
2035
Ang Li73697b32015-12-03 00:41:53 +00002036def expand_enterprise_config_by_phase2(config):
2037 """Take an enterprise config and generate a list of configs, each with
2038 a different phase2 auth type.
2039
2040 Args:
2041 config: A dict representing enterprise config.
2042
2043 Returns
2044 A list of enterprise configs.
2045 """
2046 results = []
Ang Li0e7e58f2016-02-22 12:15:02 -08002047 phase2_types = WifiEnums.EapPhase2
2048 if config[WifiEnums.Enterprise.EAP] == WifiEnums.Eap.PEAP:
2049 # Skip unsupported phase2 types for PEAP.
2050 phase2_types = [WifiEnums.EapPhase2.GTC, WifiEnums.EapPhase2.MSCHAPV2]
2051 for phase2_type in phase2_types:
Ang Li73697b32015-12-03 00:41:53 +00002052 # Skip a special case for passpoint TTLS.
Omar El Ayach8c017902020-10-18 10:26:57 -07002053 if (WifiEnums.Enterprise.FQDN in config
2054 and phase2_type == WifiEnums.EapPhase2.GTC):
Ang Li73697b32015-12-03 00:41:53 +00002055 continue
2056 c = dict(config)
Girish Moturu150d32f2017-02-14 12:27:07 -08002057 c[WifiEnums.Enterprise.PHASE2] = phase2_type.value
Ang Li73697b32015-12-03 00:41:53 +00002058 results.append(c)
2059 return results
Ang Li2d3fe982016-06-08 10:00:43 -07002060
2061
Girish Moturub48a13c2017-02-27 11:36:42 -08002062def generate_eap_test_name(config, ad=None):
Girish Moturu150d32f2017-02-14 12:27:07 -08002063 """ Generates a test case name based on an EAP configuration.
2064
2065 Args:
2066 config: A dict representing an EAP credential.
Girish Moturub48a13c2017-02-27 11:36:42 -08002067 ad object: Redundant but required as the same param is passed
2068 to test_func in run_generated_tests
Girish Moturu150d32f2017-02-14 12:27:07 -08002069
2070 Returns:
2071 A string representing the name of a generated EAP test case.
2072 """
2073 eap = WifiEnums.Eap
2074 eap_phase2 = WifiEnums.EapPhase2
Girish Moturub48a13c2017-02-27 11:36:42 -08002075 Ent = WifiEnums.Enterprise
Girish Moturu150d32f2017-02-14 12:27:07 -08002076 name = "test_connect-"
2077 eap_name = ""
2078 for e in eap:
2079 if e.value == config[Ent.EAP]:
2080 eap_name = e.name
2081 break
2082 if "peap0" in config[WifiEnums.SSID_KEY].lower():
2083 eap_name = "PEAP0"
2084 if "peap1" in config[WifiEnums.SSID_KEY].lower():
2085 eap_name = "PEAP1"
2086 name += eap_name
2087 if Ent.PHASE2 in config:
2088 for e in eap_phase2:
2089 if e.value == config[Ent.PHASE2]:
2090 name += "-{}".format(e.name)
2091 break
2092 return name
2093
2094
Ang Li2d3fe982016-06-08 10:00:43 -07002095def group_attenuators(attenuators):
2096 """Groups a list of attenuators into attenuator groups for backward
2097 compatibility reasons.
2098
2099 Most legacy Wi-Fi setups have two attenuators each connected to a separate
2100 AP. The new Wi-Fi setup has four attenuators, each connected to one channel
2101 on an AP, so two of them are connected to one AP.
2102
2103 To make the existing scripts work in the new setup, when the script needs
2104 to attenuate one AP, it needs to set attenuation on both attenuators
2105 connected to the same AP.
2106
2107 This function groups attenuators properly so the scripts work in both
2108 legacy and new Wi-Fi setups.
2109
2110 Args:
2111 attenuators: A list of attenuator objects, either two or four in length.
2112
2113 Raises:
2114 signals.TestFailure is raised if the attenuator list does not have two
2115 or four objects.
2116 """
2117 attn0 = attenuator.AttenuatorGroup("AP0")
2118 attn1 = attenuator.AttenuatorGroup("AP1")
2119 # Legacy testbed setup has two attenuation channels.
2120 num_of_attns = len(attenuators)
2121 if num_of_attns == 2:
2122 attn0.add(attenuators[0])
2123 attn1.add(attenuators[1])
2124 elif num_of_attns == 4:
2125 attn0.add(attenuators[0])
2126 attn0.add(attenuators[1])
2127 attn1.add(attenuators[2])
2128 attn1.add(attenuators[3])
2129 else:
2130 asserts.fail(("Either two or four attenuators are required for this "
2131 "test, but found %s") % num_of_attns)
2132 return [attn0, attn1]
Jong Wook Kim92356922018-02-06 18:32:49 -08002133
Bindu Mahadevff295782019-02-08 16:17:48 -08002134
Girish Moturu36348a32019-12-10 08:41:54 -08002135def set_attns(attenuator, attn_val_name, roaming_attn=ROAMING_ATTN):
Bindu Mahadev7060a9f2018-05-04 13:48:12 -07002136 """Sets attenuation values on attenuators used in this test.
2137
2138 Args:
2139 attenuator: The attenuator object.
2140 attn_val_name: Name of the attenuation value pair to use.
Girish Moturu36348a32019-12-10 08:41:54 -08002141 roaming_attn: Dictionary specifying the attenuation params.
Bindu Mahadev7060a9f2018-05-04 13:48:12 -07002142 """
2143 logging.info("Set attenuation values to %s", roaming_attn[attn_val_name])
2144 try:
2145 attenuator[0].set_atten(roaming_attn[attn_val_name][0])
2146 attenuator[1].set_atten(roaming_attn[attn_val_name][1])
2147 attenuator[2].set_atten(roaming_attn[attn_val_name][2])
2148 attenuator[3].set_atten(roaming_attn[attn_val_name][3])
2149 except:
2150 logging.exception("Failed to set attenuation values %s.",
Omar El Ayach8c017902020-10-18 10:26:57 -07002151 attn_val_name)
Bindu Mahadev7060a9f2018-05-04 13:48:12 -07002152 raise
2153
Omar El Ayach8c017902020-10-18 10:26:57 -07002154
Girish Moturu36348a32019-12-10 08:41:54 -08002155def set_attns_steps(attenuators,
2156 atten_val_name,
2157 roaming_attn=ROAMING_ATTN,
2158 steps=10,
2159 wait_time=12):
Hsiu-Chang Chen73ea3342019-05-22 11:20:08 +08002160 """Set attenuation values on attenuators used in this test. It will change
2161 the attenuation values linearly from current value to target value step by
2162 step.
2163
2164 Args:
2165 attenuators: The list of attenuator objects that you want to change
2166 their attenuation value.
2167 atten_val_name: Name of the attenuation value pair to use.
Girish Moturu36348a32019-12-10 08:41:54 -08002168 roaming_attn: Dictionary specifying the attenuation params.
Hsiu-Chang Chen73ea3342019-05-22 11:20:08 +08002169 steps: Number of attenuator changes to reach the target value.
2170 wait_time: Sleep time for each change of attenuator.
2171 """
2172 logging.info("Set attenuation values to %s in %d step(s)",
Omar El Ayach8c017902020-10-18 10:26:57 -07002173 roaming_attn[atten_val_name], steps)
Hsiu-Chang Chen73ea3342019-05-22 11:20:08 +08002174 start_atten = [attenuator.get_atten() for attenuator in attenuators]
2175 target_atten = roaming_attn[atten_val_name]
2176 for current_step in range(steps):
2177 progress = (current_step + 1) / steps
2178 for i, attenuator in enumerate(attenuators):
2179 amount_since_start = (target_atten[i] - start_atten[i]) * progress
2180 attenuator.set_atten(round(start_atten[i] + amount_since_start))
2181 time.sleep(wait_time)
2182
Bindu Mahadev7060a9f2018-05-04 13:48:12 -07002183
Girish Moturu36348a32019-12-10 08:41:54 -08002184def trigger_roaming_and_validate(dut,
2185 attenuator,
2186 attn_val_name,
2187 expected_con,
2188 roaming_attn=ROAMING_ATTN):
Bindu Mahadev7060a9f2018-05-04 13:48:12 -07002189 """Sets attenuators to trigger roaming and validate the DUT connected
2190 to the BSSID expected.
2191
2192 Args:
2193 attenuator: The attenuator object.
2194 attn_val_name: Name of the attenuation value pair to use.
2195 expected_con: The network information of the expected network.
Girish Moturu36348a32019-12-10 08:41:54 -08002196 roaming_attn: Dictionary specifying the attenaution params.
Bindu Mahadev7060a9f2018-05-04 13:48:12 -07002197 """
2198 expected_con = {
2199 WifiEnums.SSID_KEY: expected_con[WifiEnums.SSID_KEY],
2200 WifiEnums.BSSID_KEY: expected_con["bssid"],
2201 }
Girish Moturu36348a32019-12-10 08:41:54 -08002202 set_attns_steps(attenuator, attn_val_name, roaming_attn)
Bindu Mahadev7060a9f2018-05-04 13:48:12 -07002203
Hsiu-Chang Chenef856402018-09-18 12:32:49 +08002204 verify_wifi_connection_info(dut, expected_con)
2205 expected_bssid = expected_con[WifiEnums.BSSID_KEY]
2206 logging.info("Roamed to %s successfully", expected_bssid)
2207 if not validate_connection(dut):
2208 raise signals.TestFailure("Fail to connect to internet on %s" %
Omar El Ayach8c017902020-10-18 10:26:57 -07002209 expected_bssid)
2210
Jong Wook Kim92356922018-02-06 18:32:49 -08002211
2212def create_softap_config():
2213 """Create a softap config with random ssid and password."""
2214 ap_ssid = "softap_" + utils.rand_ascii_str(8)
2215 ap_password = utils.rand_ascii_str(8)
2216 logging.info("softap setup: %s %s", ap_ssid, ap_password)
2217 config = {
2218 WifiEnums.SSID_KEY: ap_ssid,
2219 WifiEnums.PWD_KEY: ap_password,
2220 }
2221 return config
Girish Moturucf4dccd2018-08-27 12:22:00 -07002222
Omar El Ayach8c017902020-10-18 10:26:57 -07002223
Bindu Mahadevff295782019-02-08 16:17:48 -08002224def start_softap_and_verify(ad, band):
2225 """Bring-up softap and verify AP mode and in scan results.
2226
2227 Args:
2228 band: The band to use for softAP.
2229
2230 Returns: dict, the softAP config.
2231
2232 """
lesl2f0fb232019-11-05 16:35:28 +08002233 # Register before start the test.
2234 callbackId = ad.dut.droid.registerSoftApCallback()
2235 # Check softap info value is default
2236 frequency, bandwdith = get_current_softap_info(ad.dut, callbackId, True)
2237 asserts.assert_true(frequency == 0, "Softap frequency is not reset")
2238 asserts.assert_true(bandwdith == 0, "Softap bandwdith is not reset")
2239
Bindu Mahadevff295782019-02-08 16:17:48 -08002240 config = create_softap_config()
2241 start_wifi_tethering(ad.dut,
2242 config[WifiEnums.SSID_KEY],
Omar El Ayach8c017902020-10-18 10:26:57 -07002243 config[WifiEnums.PWD_KEY],
2244 band=band)
Bindu Mahadevff295782019-02-08 16:17:48 -08002245 asserts.assert_true(ad.dut.droid.wifiIsApEnabled(),
Omar El Ayach8c017902020-10-18 10:26:57 -07002246 "SoftAp is not reported as running")
2247 start_wifi_connection_scan_and_ensure_network_found(
2248 ad.dut_client, config[WifiEnums.SSID_KEY])
lesl2f0fb232019-11-05 16:35:28 +08002249
2250 # Check softap info can get from callback succeed and assert value should be
2251 # valid.
2252 frequency, bandwdith = get_current_softap_info(ad.dut, callbackId, True)
2253 asserts.assert_true(frequency > 0, "Softap frequency is not valid")
2254 asserts.assert_true(bandwdith > 0, "Softap bandwdith is not valid")
2255 # Unregister callback
2256 ad.dut.droid.unregisterSoftApCallback(callbackId)
2257
Bindu Mahadevff295782019-02-08 16:17:48 -08002258 return config
2259
Omar El Ayach8c017902020-10-18 10:26:57 -07002260
lesle8e3c0a2019-02-22 17:06:04 +08002261def wait_for_expected_number_of_softap_clients(ad, callbackId,
Omar El Ayach8c017902020-10-18 10:26:57 -07002262 expected_num_of_softap_clients):
lesle8e3c0a2019-02-22 17:06:04 +08002263 """Wait for the number of softap clients to be updated as expected.
2264 Args:
2265 callbackId: Id of the callback associated with registering.
2266 expected_num_of_softap_clients: expected number of softap clients.
2267 """
2268 eventStr = wifi_constants.SOFTAP_CALLBACK_EVENT + str(
Omar El Ayach8c017902020-10-18 10:26:57 -07002269 callbackId) + wifi_constants.SOFTAP_NUMBER_CLIENTS_CHANGED
James Mattis5a5dd492020-05-14 13:09:43 -07002270 clientData = ad.ed.pop_event(eventStr, SHORT_TIMEOUT)['data']
2271 clientCount = clientData[wifi_constants.SOFTAP_NUMBER_CLIENTS_CALLBACK_KEY]
Omar El Ayach8c017902020-10-18 10:26:57 -07002272 clientMacAddresses = clientData[
2273 wifi_constants.SOFTAP_CLIENTS_MACS_CALLBACK_KEY]
2274 asserts.assert_equal(
2275 clientCount, expected_num_of_softap_clients,
2276 "The number of softap clients doesn't match the expected number")
2277 asserts.assert_equal(
2278 len(clientMacAddresses), expected_num_of_softap_clients,
2279 "The number of mac addresses doesn't match the expected number")
James Mattis5a5dd492020-05-14 13:09:43 -07002280 for macAddress in clientMacAddresses:
Omar El Ayach8c017902020-10-18 10:26:57 -07002281 asserts.assert_true(checkMacAddress(macAddress),
2282 "An invalid mac address was returned")
2283
James Mattis5a5dd492020-05-14 13:09:43 -07002284
2285def checkMacAddress(input):
2286 """Validate whether a string is a valid mac address or not.
2287
2288 Args:
2289 input: The string to validate.
2290
2291 Returns: True/False, returns true for a valid mac address and false otherwise.
2292 """
2293 macValidationRegex = "[0-9a-f]{2}([-:]?)[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$"
2294 if re.match(macValidationRegex, input.lower()):
2295 return True
2296 return False
lesle8e3c0a2019-02-22 17:06:04 +08002297
Omar El Ayach8c017902020-10-18 10:26:57 -07002298
lesle8e3c0a2019-02-22 17:06:04 +08002299def wait_for_expected_softap_state(ad, callbackId, expected_softap_state):
2300 """Wait for the expected softap state change.
2301 Args:
2302 callbackId: Id of the callback associated with registering.
2303 expected_softap_state: The expected softap state.
2304 """
2305 eventStr = wifi_constants.SOFTAP_CALLBACK_EVENT + str(
Omar El Ayach8c017902020-10-18 10:26:57 -07002306 callbackId) + wifi_constants.SOFTAP_STATE_CHANGED
2307 asserts.assert_equal(
2308 ad.ed.pop_event(eventStr, SHORT_TIMEOUT)['data'][
2309 wifi_constants.SOFTAP_STATE_CHANGE_CALLBACK_KEY],
2310 expected_softap_state,
2311 "Softap state doesn't match with expected state")
2312
lesle8e3c0a2019-02-22 17:06:04 +08002313
2314def get_current_number_of_softap_clients(ad, callbackId):
2315 """pop up all of softap client updated event from queue.
2316 Args:
2317 callbackId: Id of the callback associated with registering.
2318
2319 Returns:
2320 If exist aleast callback, returns last updated number_of_softap_clients.
2321 Returns None when no any match callback event in queue.
2322 """
2323 eventStr = wifi_constants.SOFTAP_CALLBACK_EVENT + str(
Omar El Ayach8c017902020-10-18 10:26:57 -07002324 callbackId) + wifi_constants.SOFTAP_NUMBER_CLIENTS_CHANGED
lesle8e3c0a2019-02-22 17:06:04 +08002325 events = ad.ed.pop_all(eventStr)
2326 for event in events:
Omar El Ayach8c017902020-10-18 10:26:57 -07002327 num_of_clients = event['data'][
2328 wifi_constants.SOFTAP_NUMBER_CLIENTS_CALLBACK_KEY]
lesle8e3c0a2019-02-22 17:06:04 +08002329 if len(events) == 0:
2330 return None
2331 return num_of_clients
Bindu Mahadevff295782019-02-08 16:17:48 -08002332
Omar El Ayach8c017902020-10-18 10:26:57 -07002333
lesl2f0fb232019-11-05 16:35:28 +08002334def get_current_softap_info(ad, callbackId, least_one):
2335 """pop up all of softap info changed event from queue.
2336 Args:
2337 callbackId: Id of the callback associated with registering.
2338 least_one: Wait for the info callback event before pop all.
2339 Returns:
2340 Returns last updated information of softap.
2341 """
2342 eventStr = wifi_constants.SOFTAP_CALLBACK_EVENT + str(
Omar El Ayach8c017902020-10-18 10:26:57 -07002343 callbackId) + wifi_constants.SOFTAP_INFO_CHANGED
2344 ad.log.info("softap info dump from eventStr %s", eventStr)
lesl2f0fb232019-11-05 16:35:28 +08002345 frequency = 0
2346 bandwidth = 0
2347 if (least_one):
2348 event = ad.ed.pop_event(eventStr, SHORT_TIMEOUT)
Omar El Ayach8c017902020-10-18 10:26:57 -07002349 frequency = event['data'][
2350 wifi_constants.SOFTAP_INFO_FREQUENCY_CALLBACK_KEY]
2351 bandwidth = event['data'][
2352 wifi_constants.SOFTAP_INFO_BANDWIDTH_CALLBACK_KEY]
lesl2f0fb232019-11-05 16:35:28 +08002353 ad.log.info("softap info updated, frequency is %s, bandwidth is %s",
Omar El Ayach8c017902020-10-18 10:26:57 -07002354 frequency, bandwidth)
lesl2f0fb232019-11-05 16:35:28 +08002355
2356 events = ad.ed.pop_all(eventStr)
2357 for event in events:
Omar El Ayach8c017902020-10-18 10:26:57 -07002358 frequency = event['data'][
2359 wifi_constants.SOFTAP_INFO_FREQUENCY_CALLBACK_KEY]
2360 bandwidth = event['data'][
2361 wifi_constants.SOFTAP_INFO_BANDWIDTH_CALLBACK_KEY]
2362 ad.log.info("softap info, frequency is %s, bandwidth is %s", frequency,
2363 bandwidth)
lesl2f0fb232019-11-05 16:35:28 +08002364 return frequency, bandwidth
2365
2366
Hsiu-Chang Chenebb239d2020-09-16 15:12:34 +08002367def get_ssrdumps(ad):
Hsiu-Chang Chen6aac0d32019-05-15 14:21:08 +08002368 """Pulls dumps in the ssrdump dir
2369 Args:
2370 ad: android device object.
Hsiu-Chang Chen6aac0d32019-05-15 14:21:08 +08002371 """
2372 logs = ad.get_file_names("/data/vendor/ssrdump/")
2373 if logs:
2374 ad.log.info("Pulling ssrdumps %s", logs)
Hsiu-Chang Chenebb239d2020-09-16 15:12:34 +08002375 log_path = os.path.join(ad.device_log_path, "SSRDUMPS_%s" % ad.serial)
Mark De Ruyter72f8df92020-02-12 13:44:49 -08002376 os.makedirs(log_path, exist_ok=True)
Hsiu-Chang Chen6aac0d32019-05-15 14:21:08 +08002377 ad.pull_files(logs, log_path)
Hsiu-Chang Chen769bef12020-10-10 06:07:52 +00002378 ad.adb.shell("find /data/vendor/ssrdump/ -type f -delete",
Omar El Ayach8c017902020-10-18 10:26:57 -07002379 ignore_status=True)
2380
Hsiu-Chang Chen6aac0d32019-05-15 14:21:08 +08002381
Xianyuan Jia0e39e552019-01-24 17:17:47 -08002382def start_pcap(pcap, wifi_band, test_name):
Girish Moturucf4dccd2018-08-27 12:22:00 -07002383 """Start packet capture in monitor mode.
2384
2385 Args:
2386 pcap: packet capture object
2387 wifi_band: '2g' or '5g' or 'dual'
Bindu Mahadev76551c12018-12-13 19:42:14 +00002388 test_name: test name to be used for pcap file name
2389
2390 Returns:
xianyuanjia0431ba32018-12-14 09:56:42 -08002391 Dictionary with wifi band as key and the tuple
2392 (pcap Process object, log directory) as the value
Girish Moturucf4dccd2018-08-27 12:22:00 -07002393 """
Xianyuan Jia0e39e552019-01-24 17:17:47 -08002394 log_dir = os.path.join(
Xianyuan Jia5cd06bb2019-06-10 16:29:57 -07002395 context.get_current_context().get_full_output_path(), 'PacketCapture')
Mark De Ruyter72f8df92020-02-12 13:44:49 -08002396 os.makedirs(log_dir, exist_ok=True)
Girish Moturucf4dccd2018-08-27 12:22:00 -07002397 if wifi_band == 'dual':
2398 bands = [BAND_2G, BAND_5G]
2399 else:
2400 bands = [wifi_band]
xianyuanjia0431ba32018-12-14 09:56:42 -08002401 procs = {}
Girish Moturucf4dccd2018-08-27 12:22:00 -07002402 for band in bands:
xianyuanjia0431ba32018-12-14 09:56:42 -08002403 proc = pcap.start_packet_capture(band, log_dir, test_name)
2404 procs[band] = (proc, os.path.join(log_dir, test_name))
2405 return procs
Girish Moturucf4dccd2018-08-27 12:22:00 -07002406
Bindu Mahadevff295782019-02-08 16:17:48 -08002407
xianyuanjia0431ba32018-12-14 09:56:42 -08002408def stop_pcap(pcap, procs, test_status=None):
Bindu Mahadev76551c12018-12-13 19:42:14 +00002409 """Stop packet capture in monitor mode.
2410
2411 Since, the pcap logs in monitor mode can be very large, we will
2412 delete them if they are not required. 'test_status' if True, will delete
2413 the pcap files. If False, we will keep them.
Girish Moturucf4dccd2018-08-27 12:22:00 -07002414
2415 Args:
2416 pcap: packet capture object
xianyuanjia0431ba32018-12-14 09:56:42 -08002417 procs: dictionary returned by start_pcap
Bindu Mahadev76551c12018-12-13 19:42:14 +00002418 test_status: status of the test case
Girish Moturucf4dccd2018-08-27 12:22:00 -07002419 """
xianyuanjia0431ba32018-12-14 09:56:42 -08002420 for proc, fname in procs.values():
2421 pcap.stop_packet_capture(proc)
Bindu Mahadev76551c12018-12-13 19:42:14 +00002422
2423 if test_status:
xianyuanjia0431ba32018-12-14 09:56:42 -08002424 shutil.rmtree(os.path.dirname(fname))
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08002425
Omar El Ayach8c017902020-10-18 10:26:57 -07002426
Jaineel95887fd2019-10-16 16:19:01 -07002427def verify_mac_not_found_in_pcap(ad, mac, packets):
xshuf7267682019-06-03 14:41:56 -07002428 """Verify that a mac address is not found in the captured packets.
2429
2430 Args:
Jaineel95887fd2019-10-16 16:19:01 -07002431 ad: android device object
xshuf7267682019-06-03 14:41:56 -07002432 mac: string representation of the mac address
2433 packets: packets obtained by rdpcap(pcap_fname)
2434 """
2435 for pkt in packets:
2436 logging.debug("Packet Summary = %s", pkt.summary())
2437 if mac in pkt.summary():
Jaineel95887fd2019-10-16 16:19:01 -07002438 asserts.fail("Device %s caught Factory MAC: %s in packet sniffer."
2439 "Packet = %s" % (ad.serial, mac, pkt.show()))
Bindu Mahadevff295782019-02-08 16:17:48 -08002440
Omar El Ayach8c017902020-10-18 10:26:57 -07002441
Jaineel95887fd2019-10-16 16:19:01 -07002442def verify_mac_is_found_in_pcap(ad, mac, packets):
Nate Jiangc2c09c62019-06-05 17:26:08 -07002443 """Verify that a mac address is found in the captured packets.
2444
2445 Args:
Jaineel95887fd2019-10-16 16:19:01 -07002446 ad: android device object
Nate Jiangc2c09c62019-06-05 17:26:08 -07002447 mac: string representation of the mac address
2448 packets: packets obtained by rdpcap(pcap_fname)
2449 """
2450 for pkt in packets:
2451 if mac in pkt.summary():
2452 return
Jaineel95887fd2019-10-16 16:19:01 -07002453 asserts.fail("Did not find MAC = %s in packet sniffer."
2454 "for device %s" % (mac, ad.serial))
Nate Jiangc2c09c62019-06-05 17:26:08 -07002455
Omar El Ayach8c017902020-10-18 10:26:57 -07002456
Girish Moturuddc0d382020-08-24 12:08:41 -07002457def start_cnss_diags(ads, cnss_diag_file, pixel_models):
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08002458 for ad in ads:
Girish Moturuddc0d382020-08-24 12:08:41 -07002459 start_cnss_diag(ad, cnss_diag_file, pixel_models)
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08002460
Bindu Mahadevff295782019-02-08 16:17:48 -08002461
Girish Moturuddc0d382020-08-24 12:08:41 -07002462def start_cnss_diag(ad, cnss_diag_file, pixel_models):
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08002463 """Start cnss_diag to record extra wifi logs
2464
2465 Args:
2466 ad: android device object.
Girish Moturuddc0d382020-08-24 12:08:41 -07002467 cnss_diag_file: cnss diag config file to push to device.
2468 pixel_models: pixel devices.
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08002469 """
Girish Moturuddc0d382020-08-24 12:08:41 -07002470 if ad.model not in pixel_models:
2471 ad.log.info("Device not supported to collect pixel logger")
2472 return
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08002473 if ad.model in wifi_constants.DEVICES_USING_LEGACY_PROP:
2474 prop = wifi_constants.LEGACY_CNSS_DIAG_PROP
2475 else:
2476 prop = wifi_constants.CNSS_DIAG_PROP
2477 if ad.adb.getprop(prop) != 'true':
Omar El Ayach8c017902020-10-18 10:26:57 -07002478 if not int(
2479 ad.adb.shell("ls -l %s%s | wc -l" %
2480 (CNSS_DIAG_CONFIG_PATH, CNSS_DIAG_CONFIG_FILE))):
Girish Moturuddc0d382020-08-24 12:08:41 -07002481 ad.adb.push("%s %s" % (cnss_diag_file, CNSS_DIAG_CONFIG_PATH))
Omar El Ayach8c017902020-10-18 10:26:57 -07002482 ad.adb.shell(
2483 "find /data/vendor/wifi/cnss_diag/wlan_logs/ -type f -delete",
2484 ignore_status=True)
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08002485 ad.adb.shell("setprop %s true" % prop, ignore_status=True)
2486
Bindu Mahadevff295782019-02-08 16:17:48 -08002487
Girish Moturuddc0d382020-08-24 12:08:41 -07002488def stop_cnss_diags(ads, pixel_models):
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08002489 for ad in ads:
Girish Moturuddc0d382020-08-24 12:08:41 -07002490 stop_cnss_diag(ad, pixel_models)
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08002491
Bindu Mahadevff295782019-02-08 16:17:48 -08002492
Girish Moturuddc0d382020-08-24 12:08:41 -07002493def stop_cnss_diag(ad, pixel_models):
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08002494 """Stops cnss_diag
2495
2496 Args:
2497 ad: android device object.
Girish Moturuddc0d382020-08-24 12:08:41 -07002498 pixel_models: pixel devices.
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08002499 """
Girish Moturuddc0d382020-08-24 12:08:41 -07002500 if ad.model not in pixel_models:
2501 ad.log.info("Device not supported to collect pixel logger")
2502 return
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08002503 if ad.model in wifi_constants.DEVICES_USING_LEGACY_PROP:
2504 prop = wifi_constants.LEGACY_CNSS_DIAG_PROP
2505 else:
2506 prop = wifi_constants.CNSS_DIAG_PROP
2507 ad.adb.shell("setprop %s false" % prop, ignore_status=True)
2508
Bindu Mahadevff295782019-02-08 16:17:48 -08002509
Hsiu-Chang Chenebb239d2020-09-16 15:12:34 +08002510def get_cnss_diag_log(ad):
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08002511 """Pulls the cnss_diag logs in the wlan_logs dir
2512 Args:
2513 ad: android device object.
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08002514 """
2515 logs = ad.get_file_names("/data/vendor/wifi/cnss_diag/wlan_logs/")
2516 if logs:
2517 ad.log.info("Pulling cnss_diag logs %s", logs)
Xianyuan Jia0e39e552019-01-24 17:17:47 -08002518 log_path = os.path.join(ad.device_log_path, "CNSS_DIAG_%s" % ad.serial)
Mark De Ruyter72f8df92020-02-12 13:44:49 -08002519 os.makedirs(log_path, exist_ok=True)
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08002520 ad.pull_files(logs, log_path)
Bindu Mahadev7e5dc682019-02-01 16:53:34 -08002521
Bindu Mahadevff295782019-02-08 16:17:48 -08002522
Omar El Ayach8c017902020-10-18 10:26:57 -07002523LinkProbeResult = namedtuple(
2524 'LinkProbeResult',
2525 ('is_success', 'stdout', 'elapsed_time', 'failure_reason'))
David Sue4cd9c22019-03-26 18:07:26 -07002526
2527
2528def send_link_probe(ad):
2529 """Sends a link probe to the currently connected AP, and returns whether the
2530 probe succeeded or not.
2531
2532 Args:
2533 ad: android device object
2534 Returns:
2535 LinkProbeResult namedtuple
2536 """
2537 stdout = ad.adb.shell('cmd wifi send-link-probe')
2538 asserts.assert_false('Error' in stdout or 'Exception' in stdout,
2539 'Exception while sending link probe: ' + stdout)
2540
2541 is_success = False
2542 elapsed_time = None
2543 failure_reason = None
2544 if 'succeeded' in stdout:
2545 is_success = True
2546 elapsed_time = next(
2547 (int(token) for token in stdout.split() if token.isdigit()), None)
2548 elif 'failed with reason' in stdout:
2549 failure_reason = next(
2550 (int(token) for token in stdout.split() if token.isdigit()), None)
2551 else:
2552 asserts.fail('Unexpected link probe result: ' + stdout)
2553
Omar El Ayach8c017902020-10-18 10:26:57 -07002554 return LinkProbeResult(is_success=is_success,
2555 stdout=stdout,
2556 elapsed_time=elapsed_time,
2557 failure_reason=failure_reason)
David Sue4cd9c22019-03-26 18:07:26 -07002558
2559
2560def send_link_probes(ad, num_probes, delay_sec):
2561 """Sends a sequence of link probes to the currently connected AP, and
2562 returns whether the probes succeeded or not.
2563
2564 Args:
2565 ad: android device object
2566 num_probes: number of probes to perform
2567 delay_sec: delay time between probes, in seconds
2568 Returns:
2569 List[LinkProbeResult] one LinkProbeResults for each probe
2570 """
2571 logging.info('Sending link probes')
2572 results = []
2573 for _ in range(num_probes):
2574 # send_link_probe() will also fail the test if it sees an exception
2575 # in the stdout of the adb shell command
2576 result = send_link_probe(ad)
2577 logging.info('link probe results: ' + str(result))
2578 results.append(result)
2579 time.sleep(delay_sec)
2580
2581 return results
2582
2583
Bindu Mahadev7e5dc682019-02-01 16:53:34 -08002584def ap_setup(test, index, ap, network, bandwidth=80, channel=6):
Omar El Ayach8c017902020-10-18 10:26:57 -07002585 """Set up the AP with provided network info.
Bindu Mahadev7e5dc682019-02-01 16:53:34 -08002586
2587 Args:
2588 test: the calling test class object.
2589 index: int, index of the AP.
2590 ap: access_point object of the AP.
2591 network: dict with information of the network, including ssid,
2592 password and bssid.
2593 bandwidth: the operation bandwidth for the AP, default 80MHz.
2594 channel: the channel number for the AP.
2595 Returns:
2596 brconfigs: the bridge interface configs
2597 """
Omar El Ayach8c017902020-10-18 10:26:57 -07002598 bss_settings = []
2599 ssid = network[WifiEnums.SSID_KEY]
2600 test.access_points[index].close()
2601 time.sleep(5)
Bindu Mahadev7e5dc682019-02-01 16:53:34 -08002602
Omar El Ayach8c017902020-10-18 10:26:57 -07002603 # Configure AP as required.
2604 if "password" in network.keys():
2605 password = network["password"]
2606 security = hostapd_security.Security(security_mode="wpa",
2607 password=password)
2608 else:
2609 security = hostapd_security.Security(security_mode=None, password=None)
2610 config = hostapd_ap_preset.create_ap_preset(channel=channel,
2611 ssid=ssid,
2612 security=security,
2613 bss_settings=bss_settings,
2614 vht_bandwidth=bandwidth,
2615 profile_name='whirlwind',
2616 iface_wlan_2g=ap.wlan_2g,
2617 iface_wlan_5g=ap.wlan_5g)
2618 ap.start_ap(config)
2619 logging.info("AP started on channel {} with SSID {}".format(channel, ssid))
Bindu Mahadevff295782019-02-08 16:17:48 -08002620
2621
2622def turn_ap_off(test, AP):
2623 """Bring down hostapd on the Access Point.
2624 Args:
2625 test: The test class object.
2626 AP: int, indicating which AP to turn OFF.
2627 """
Omar El Ayach8c017902020-10-18 10:26:57 -07002628 hostapd_2g = test.access_points[AP - 1]._aps['wlan0'].hostapd
Bindu Mahadevff295782019-02-08 16:17:48 -08002629 if hostapd_2g.is_alive():
2630 hostapd_2g.stop()
2631 logging.debug('Turned WLAN0 AP%d off' % AP)
Omar El Ayach8c017902020-10-18 10:26:57 -07002632 hostapd_5g = test.access_points[AP - 1]._aps['wlan1'].hostapd
Bindu Mahadevff295782019-02-08 16:17:48 -08002633 if hostapd_5g.is_alive():
2634 hostapd_5g.stop()
2635 logging.debug('Turned WLAN1 AP%d off' % AP)
2636
2637
2638def turn_ap_on(test, AP):
2639 """Bring up hostapd on the Access Point.
2640 Args:
2641 test: The test class object.
2642 AP: int, indicating which AP to turn ON.
2643 """
Omar El Ayach8c017902020-10-18 10:26:57 -07002644 hostapd_2g = test.access_points[AP - 1]._aps['wlan0'].hostapd
Bindu Mahadevff295782019-02-08 16:17:48 -08002645 if not hostapd_2g.is_alive():
2646 hostapd_2g.start(hostapd_2g.config)
2647 logging.debug('Turned WLAN0 AP%d on' % AP)
Omar El Ayach8c017902020-10-18 10:26:57 -07002648 hostapd_5g = test.access_points[AP - 1]._aps['wlan1'].hostapd
Bindu Mahadevff295782019-02-08 16:17:48 -08002649 if not hostapd_5g.is_alive():
2650 hostapd_5g.start(hostapd_5g.config)
2651 logging.debug('Turned WLAN1 AP%d on' % AP)
Joe Brennan48c3f692019-04-11 08:30:16 -07002652
2653
2654def turn_location_off_and_scan_toggle_off(ad):
2655 """Turns off wifi location scans."""
2656 utils.set_location_service(ad, False)
2657 ad.droid.wifiScannerToggleAlwaysAvailable(False)
2658 msg = "Failed to turn off location service's scan."
2659 asserts.assert_true(not ad.droid.wifiScannerIsAlwaysAvailable(), msg)
Alfie Chen675be872020-06-04 10:48:14 +08002660
2661
2662def set_softap_channel(dut, ap_iface='wlan1', cs_count=10, channel=2462):
2663 """ Set SoftAP mode channel
2664
2665 Args:
2666 dut: android device object
2667 ap_iface: interface of SoftAP mode.
2668 cs_count: how many beacon frames before switch channel, default = 10
2669 channel: a wifi channel.
2670 """
2671 chan_switch_cmd = 'hostapd_cli -i {} chan_switch {} {}'
Omar El Ayach8c017902020-10-18 10:26:57 -07002672 chan_switch_cmd_show = chan_switch_cmd.format(ap_iface, cs_count, channel)
Alfie Chen675be872020-06-04 10:48:14 +08002673 dut.log.info('adb shell {}'.format(chan_switch_cmd_show))
Omar El Ayach8c017902020-10-18 10:26:57 -07002674 chan_switch_result = dut.adb.shell(
2675 chan_switch_cmd.format(ap_iface, cs_count, channel))
Alfie Chen675be872020-06-04 10:48:14 +08002676 if chan_switch_result == 'OK':
2677 dut.log.info('switch hotspot channel to {}'.format(channel))
2678 return chan_switch_result
2679
2680 asserts.fail("Failed to switch hotspot channel")