blob: 512ebd45757942b6ff11690ad407df9aa07c25d6 [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
xianyuanjia0431ba32018-12-14 09:56:42 -080019import shutil
Girish Moturucf4dccd2018-08-27 12:22:00 -070020import time
Ang Li73697b32015-12-03 00:41:53 +000021
22from enum import IntEnum
23from queue import Empty
24
Ang Li82522812016-06-02 13:57:21 -070025from acts import asserts
Xianyuan Jia0e39e552019-01-24 17:17:47 -080026from acts import context
Ang Li374d7602016-02-08 17:27:27 -080027from acts import signals
Ang Lifee28402016-07-13 13:43:29 -070028from acts import utils
Ang Li2d3fe982016-06-08 10:00:43 -070029from acts.controllers import attenuator
Bindu Mahadev7e5dc682019-02-01 16:53:34 -080030from acts.controllers.ap_lib import hostapd_security
31from acts.controllers.ap_lib import hostapd_ap_preset
Girish Moturucf4dccd2018-08-27 12:22:00 -070032from acts.controllers.ap_lib.hostapd_constants import BAND_2G
33from acts.controllers.ap_lib.hostapd_constants import BAND_5G
Bindu Mahadev4e710362016-11-17 16:17:11 -080034from acts.test_utils.wifi import wifi_constants
Rebecca Silberstein8c422e62016-07-19 15:04:46 -070035from acts.test_utils.tel import tel_defines
Ang Li73697b32015-12-03 00:41:53 +000036
Bindu Mahadev1d3991e2017-03-20 18:06:54 -070037# Default timeout used for reboot, toggle WiFi and Airplane mode,
38# for the system to settle down after the operation.
39DEFAULT_TIMEOUT = 10
Ang Li73697b32015-12-03 00:41:53 +000040# Number of seconds to wait for events that are supposed to happen quickly.
41# Like onSuccess for start background scan and confirmation on wifi state
42# change.
43SHORT_TIMEOUT = 30
Bindu Mahadev7060a9f2018-05-04 13:48:12 -070044ROAMING_TIMEOUT = 30
Preetesh Barrettoe8c428b2019-02-14 09:15:44 -080045WIFI_CONNECTION_TIMEOUT_DEFAULT = 30
Ang Li73697b32015-12-03 00:41:53 +000046# Speed of light in m/s.
47SPEED_OF_LIGHT = 299792458
48
Qi Jiang8b443672018-03-16 14:46:50 -070049DEFAULT_PING_ADDR = "https://www.google.com/robots.txt"
Ang Li73697b32015-12-03 00:41:53 +000050
Bindu Mahadev7060a9f2018-05-04 13:48:12 -070051roaming_attn = {
52 "AP1_on_AP2_off": [
53 0,
54 0,
Hsiu-Chang Chen038e93d2018-11-15 12:24:06 +080055 60,
56 60
Bindu Mahadev7060a9f2018-05-04 13:48:12 -070057 ],
58 "AP1_off_AP2_on": [
Hsiu-Chang Chen038e93d2018-11-15 12:24:06 +080059 60,
60 60,
Bindu Mahadev7060a9f2018-05-04 13:48:12 -070061 0,
62 0
63 ],
64 "default": [
65 0,
66 0,
67 0,
68 0
69 ]
70 }
Ang Li82522812016-06-02 13:57:21 -070071
Xianyuan Jia0e39e552019-01-24 17:17:47 -080072
Ang Li73697b32015-12-03 00:41:53 +000073class WifiEnums():
74
75 SSID_KEY = "SSID"
Bindu Mahadev3c54c492017-02-15 16:00:08 -080076 NETID_KEY = "network_id"
Ang Li73697b32015-12-03 00:41:53 +000077 BSSID_KEY = "BSSID"
78 PWD_KEY = "password"
79 frequency_key = "frequency"
80 APBAND_KEY = "apBand"
Roshan Piusce821342018-01-10 11:03:04 -080081 HIDDEN_KEY = "hiddenSSID"
Ang Li73697b32015-12-03 00:41:53 +000082
83 WIFI_CONFIG_APBAND_2G = 0
84 WIFI_CONFIG_APBAND_5G = 1
Bindu Mahadevd955aef2018-04-06 16:23:40 -070085 WIFI_CONFIG_APBAND_AUTO = -1
Ang Li73697b32015-12-03 00:41:53 +000086
Ang Li82522812016-06-02 13:57:21 -070087 WIFI_WPS_INFO_PBC = 0
88 WIFI_WPS_INFO_DISPLAY = 1
89 WIFI_WPS_INFO_KEYPAD = 2
90 WIFI_WPS_INFO_LABEL = 3
91 WIFI_WPS_INFO_INVALID = 4
Ang Li73697b32015-12-03 00:41:53 +000092
93 class CountryCode():
94 CHINA = "CN"
95 JAPAN = "JP"
96 UK = "GB"
97 US = "US"
98 UNKNOWN = "UNKNOWN"
99
100 # Start of Macros for EAP
101 # EAP types
102 class Eap(IntEnum):
103 NONE = -1
104 PEAP = 0
Ang Li82522812016-06-02 13:57:21 -0700105 TLS = 1
Ang Li73697b32015-12-03 00:41:53 +0000106 TTLS = 2
Ang Li82522812016-06-02 13:57:21 -0700107 PWD = 3
108 SIM = 4
109 AKA = 5
110 AKA_PRIME = 6
111 UNAUTH_TLS = 7
Ang Li73697b32015-12-03 00:41:53 +0000112
113 # EAP Phase2 types
114 class EapPhase2(IntEnum):
Ang Li82522812016-06-02 13:57:21 -0700115 NONE = 0
116 PAP = 1
117 MSCHAP = 2
118 MSCHAPV2 = 3
119 GTC = 4
Ang Li73697b32015-12-03 00:41:53 +0000120
121 class Enterprise:
Ang Li82522812016-06-02 13:57:21 -0700122 # Enterprise Config Macros
123 EMPTY_VALUE = "NULL"
124 EAP = "eap"
125 PHASE2 = "phase2"
126 IDENTITY = "identity"
127 ANON_IDENTITY = "anonymous_identity"
128 PASSWORD = "password"
129 SUBJECT_MATCH = "subject_match"
Ang Li73697b32015-12-03 00:41:53 +0000130 ALTSUBJECT_MATCH = "altsubject_match"
131 DOM_SUFFIX_MATCH = "domain_suffix_match"
Ang Li82522812016-06-02 13:57:21 -0700132 CLIENT_CERT = "client_cert"
133 CA_CERT = "ca_cert"
134 ENGINE = "engine"
135 ENGINE_ID = "engine_id"
136 PRIVATE_KEY_ID = "key_id"
137 REALM = "realm"
138 PLMN = "plmn"
139 FQDN = "FQDN"
140 FRIENDLY_NAME = "providerFriendlyName"
141 ROAMING_IDS = "roamingConsortiumIds"
Ang Li73697b32015-12-03 00:41:53 +0000142 # End of Macros for EAP
143
144 # Macros for wifi p2p.
145 WIFI_P2P_SERVICE_TYPE_ALL = 0
146 WIFI_P2P_SERVICE_TYPE_BONJOUR = 1
147 WIFI_P2P_SERVICE_TYPE_UPNP = 2
148 WIFI_P2P_SERVICE_TYPE_VENDOR_SPECIFIC = 255
149
150 class ScanResult:
151 CHANNEL_WIDTH_20MHZ = 0
152 CHANNEL_WIDTH_40MHZ = 1
153 CHANNEL_WIDTH_80MHZ = 2
154 CHANNEL_WIDTH_160MHZ = 3
155 CHANNEL_WIDTH_80MHZ_PLUS_MHZ = 4
156
157 # Macros for wifi rtt.
158 class RttType(IntEnum):
Ang Li82522812016-06-02 13:57:21 -0700159 TYPE_ONE_SIDED = 1
160 TYPE_TWO_SIDED = 2
Ang Li73697b32015-12-03 00:41:53 +0000161
162 class RttPeerType(IntEnum):
Ang Li82522812016-06-02 13:57:21 -0700163 PEER_TYPE_AP = 1
164 PEER_TYPE_STA = 2 # Requires NAN.
165 PEER_P2P_GO = 3
166 PEER_P2P_CLIENT = 4
167 PEER_NAN = 5
Ang Li73697b32015-12-03 00:41:53 +0000168
169 class RttPreamble(IntEnum):
Ang Li82522812016-06-02 13:57:21 -0700170 PREAMBLE_LEGACY = 0x01
171 PREAMBLE_HT = 0x02
172 PREAMBLE_VHT = 0x04
Ang Li73697b32015-12-03 00:41:53 +0000173
174 class RttBW(IntEnum):
Ang Li82522812016-06-02 13:57:21 -0700175 BW_5_SUPPORT = 0x01
176 BW_10_SUPPORT = 0x02
177 BW_20_SUPPORT = 0x04
178 BW_40_SUPPORT = 0x08
179 BW_80_SUPPORT = 0x10
Ang Li73697b32015-12-03 00:41:53 +0000180 BW_160_SUPPORT = 0x20
181
182 class Rtt(IntEnum):
Ang Li82522812016-06-02 13:57:21 -0700183 STATUS_SUCCESS = 0
184 STATUS_FAILURE = 1
185 STATUS_FAIL_NO_RSP = 2
186 STATUS_FAIL_REJECTED = 3
187 STATUS_FAIL_NOT_SCHEDULED_YET = 4
188 STATUS_FAIL_TM_TIMEOUT = 5
189 STATUS_FAIL_AP_ON_DIFF_CHANNEL = 6
190 STATUS_FAIL_NO_CAPABILITY = 7
191 STATUS_ABORTED = 8
192 STATUS_FAIL_INVALID_TS = 9
193 STATUS_FAIL_PROTOCOL = 10
194 STATUS_FAIL_SCHEDULE = 11
195 STATUS_FAIL_BUSY_TRY_LATER = 12
196 STATUS_INVALID_REQ = 13
197 STATUS_NO_WIFI = 14
198 STATUS_FAIL_FTM_PARAM_OVERRIDE = 15
Ang Li73697b32015-12-03 00:41:53 +0000199
Ang Li82522812016-06-02 13:57:21 -0700200 REASON_UNSPECIFIED = -1
201 REASON_NOT_AVAILABLE = -2
202 REASON_INVALID_LISTENER = -3
203 REASON_INVALID_REQUEST = -4
Ang Li73697b32015-12-03 00:41:53 +0000204
205 class RttParam:
206 device_type = "deviceType"
207 request_type = "requestType"
208 BSSID = "bssid"
209 channel_width = "channelWidth"
210 frequency = "frequency"
211 center_freq0 = "centerFreq0"
212 center_freq1 = "centerFreq1"
213 number_burst = "numberBurst"
214 interval = "interval"
215 num_samples_per_burst = "numSamplesPerBurst"
216 num_retries_per_measurement_frame = "numRetriesPerMeasurementFrame"
217 num_retries_per_FTMR = "numRetriesPerFTMR"
218 lci_request = "LCIRequest"
219 lcr_request = "LCRRequest"
220 burst_timeout = "burstTimeout"
221 preamble = "preamble"
222 bandwidth = "bandwidth"
223 margin = "margin"
224
225 RTT_MARGIN_OF_ERROR = {
226 RttBW.BW_80_SUPPORT: 2,
227 RttBW.BW_40_SUPPORT: 5,
228 RttBW.BW_20_SUPPORT: 5
229 }
230
231 # Macros as specified in the WifiScanner code.
Ang Li82522812016-06-02 13:57:21 -0700232 WIFI_BAND_UNSPECIFIED = 0 # not specified
233 WIFI_BAND_24_GHZ = 1 # 2.4 GHz band
234 WIFI_BAND_5_GHZ = 2 # 5 GHz band without DFS channels
235 WIFI_BAND_5_GHZ_DFS_ONLY = 4 # 5 GHz band with DFS channels
236 WIFI_BAND_5_GHZ_WITH_DFS = 6 # 5 GHz band with DFS channels
237 WIFI_BAND_BOTH = 3 # both bands without DFS channels
238 WIFI_BAND_BOTH_WITH_DFS = 7 # both bands with DFS channels
Ang Li73697b32015-12-03 00:41:53 +0000239
240 REPORT_EVENT_AFTER_BUFFER_FULL = 0
241 REPORT_EVENT_AFTER_EACH_SCAN = 1
242 REPORT_EVENT_FULL_SCAN_RESULT = 2
243
xshuaabcfeb2018-02-14 11:43:24 -0800244 SCAN_TYPE_LOW_LATENCY = 0
245 SCAN_TYPE_LOW_POWER = 1
246 SCAN_TYPE_HIGH_ACCURACY = 2
247
Ang Li73697b32015-12-03 00:41:53 +0000248 # US Wifi frequencies
249 ALL_2G_FREQUENCIES = [2412, 2417, 2422, 2427, 2432, 2437, 2442, 2447, 2452,
250 2457, 2462]
251 DFS_5G_FREQUENCIES = [5260, 5280, 5300, 5320, 5500, 5520, 5540, 5560, 5580,
252 5600, 5620, 5640, 5660, 5680, 5700, 5720]
253 NONE_DFS_5G_FREQUENCIES = [5180, 5200, 5220, 5240, 5745, 5765, 5785, 5805,
254 5825]
255 ALL_5G_FREQUENCIES = DFS_5G_FREQUENCIES + NONE_DFS_5G_FREQUENCIES
256
257 band_to_frequencies = {
Ang Li82522812016-06-02 13:57:21 -0700258 WIFI_BAND_24_GHZ: ALL_2G_FREQUENCIES,
259 WIFI_BAND_5_GHZ: NONE_DFS_5G_FREQUENCIES,
260 WIFI_BAND_5_GHZ_DFS_ONLY: DFS_5G_FREQUENCIES,
261 WIFI_BAND_5_GHZ_WITH_DFS: ALL_5G_FREQUENCIES,
262 WIFI_BAND_BOTH: ALL_2G_FREQUENCIES + NONE_DFS_5G_FREQUENCIES,
263 WIFI_BAND_BOTH_WITH_DFS: ALL_5G_FREQUENCIES + ALL_2G_FREQUENCIES
Ang Li73697b32015-12-03 00:41:53 +0000264 }
265
266 # All Wifi frequencies to channels lookup.
267 freq_to_channel = {
268 2412: 1,
269 2417: 2,
270 2422: 3,
271 2427: 4,
272 2432: 5,
273 2437: 6,
274 2442: 7,
275 2447: 8,
276 2452: 9,
277 2457: 10,
278 2462: 11,
279 2467: 12,
280 2472: 13,
281 2484: 14,
282 4915: 183,
283 4920: 184,
284 4925: 185,
285 4935: 187,
286 4940: 188,
287 4945: 189,
288 4960: 192,
289 4980: 196,
290 5035: 7,
291 5040: 8,
292 5045: 9,
293 5055: 11,
294 5060: 12,
295 5080: 16,
296 5170: 34,
297 5180: 36,
298 5190: 38,
299 5200: 40,
300 5210: 42,
301 5220: 44,
302 5230: 46,
303 5240: 48,
304 5260: 52,
305 5280: 56,
306 5300: 60,
307 5320: 64,
308 5500: 100,
309 5520: 104,
310 5540: 108,
311 5560: 112,
312 5580: 116,
313 5600: 120,
314 5620: 124,
315 5640: 128,
316 5660: 132,
317 5680: 136,
318 5700: 140,
319 5745: 149,
320 5765: 153,
321 5785: 157,
322 5805: 161,
323 5825: 165,
324 }
325
326 # All Wifi channels to frequencies lookup.
327 channel_2G_to_freq = {
328 1: 2412,
329 2: 2417,
330 3: 2422,
331 4: 2427,
332 5: 2432,
333 6: 2437,
334 7: 2442,
335 8: 2447,
336 9: 2452,
337 10: 2457,
338 11: 2462,
339 12: 2467,
340 13: 2472,
341 14: 2484
342 }
343
344 channel_5G_to_freq = {
345 183: 4915,
346 184: 4920,
347 185: 4925,
348 187: 4935,
349 188: 4940,
350 189: 4945,
351 192: 4960,
352 196: 4980,
353 7: 5035,
354 8: 5040,
355 9: 5045,
356 11: 5055,
357 12: 5060,
358 16: 5080,
359 34: 5170,
360 36: 5180,
361 38: 5190,
362 40: 5200,
363 42: 5210,
364 44: 5220,
365 46: 5230,
366 48: 5240,
367 52: 5260,
368 56: 5280,
369 60: 5300,
370 64: 5320,
371 100: 5500,
372 104: 5520,
373 108: 5540,
374 112: 5560,
375 116: 5580,
376 120: 5600,
377 124: 5620,
378 128: 5640,
379 132: 5660,
380 136: 5680,
381 140: 5700,
382 149: 5745,
383 153: 5765,
384 157: 5785,
385 161: 5805,
386 165: 5825
387 }
388
Ang Li82522812016-06-02 13:57:21 -0700389
Ang Li73697b32015-12-03 00:41:53 +0000390class WifiChannelBase:
391 ALL_2G_FREQUENCIES = []
392 DFS_5G_FREQUENCIES = []
393 NONE_DFS_5G_FREQUENCIES = []
394 ALL_5G_FREQUENCIES = DFS_5G_FREQUENCIES + NONE_DFS_5G_FREQUENCIES
395 MIX_CHANNEL_SCAN = []
396
397 def band_to_freq(self, band):
398 _band_to_frequencies = {
399 WifiEnums.WIFI_BAND_24_GHZ: self.ALL_2G_FREQUENCIES,
400 WifiEnums.WIFI_BAND_5_GHZ: self.NONE_DFS_5G_FREQUENCIES,
401 WifiEnums.WIFI_BAND_5_GHZ_DFS_ONLY: self.DFS_5G_FREQUENCIES,
402 WifiEnums.WIFI_BAND_5_GHZ_WITH_DFS: self.ALL_5G_FREQUENCIES,
Ang Li82522812016-06-02 13:57:21 -0700403 WifiEnums.WIFI_BAND_BOTH:
404 self.ALL_2G_FREQUENCIES + self.NONE_DFS_5G_FREQUENCIES,
405 WifiEnums.WIFI_BAND_BOTH_WITH_DFS:
406 self.ALL_5G_FREQUENCIES + self.ALL_2G_FREQUENCIES
Ang Li73697b32015-12-03 00:41:53 +0000407 }
408 return _band_to_frequencies[band]
409
Ang Li82522812016-06-02 13:57:21 -0700410
Ang Li73697b32015-12-03 00:41:53 +0000411class WifiChannelUS(WifiChannelBase):
412 # US Wifi frequencies
413 ALL_2G_FREQUENCIES = [2412, 2417, 2422, 2427, 2432, 2437, 2442, 2447, 2452,
414 2457, 2462]
415 NONE_DFS_5G_FREQUENCIES = [5180, 5200, 5220, 5240, 5745, 5765, 5785, 5805,
416 5825]
Ang Li82522812016-06-02 13:57:21 -0700417 MIX_CHANNEL_SCAN = [2412, 2437, 2462, 5180, 5200, 5280, 5260, 5300, 5500,
418 5320, 5520, 5560, 5700, 5745, 5805]
Ang Li73697b32015-12-03 00:41:53 +0000419
420 def __init__(self, model=None):
Girish Moturu0c567b02017-08-11 16:20:01 -0700421 self.DFS_5G_FREQUENCIES = [5260, 5280, 5300, 5320, 5500, 5520,
422 5540, 5560, 5580, 5600, 5620, 5640,
423 5660, 5680, 5700, 5720]
424 self.ALL_5G_FREQUENCIES = self.DFS_5G_FREQUENCIES + self.NONE_DFS_5G_FREQUENCIES
Ang Li73697b32015-12-03 00:41:53 +0000425
Bindu Mahadev36725332019-01-29 12:23:21 -0800426
Girish Moturuf02fa1d2017-05-21 09:51:23 +0530427class WifiReferenceNetworks:
428 """ Class to parse and return networks of different band and
429 auth type from reference_networks
430 """
431 def __init__(self, obj):
432 self.reference_networks = obj
433 self.WIFI_2G = "2g"
434 self.WIFI_5G = "5g"
435
436 self.secure_networks_2g = []
437 self.secure_networks_5g = []
438 self.open_networks_2g = []
439 self.open_networks_5g = []
440 self._parse_networks()
441
442 def _parse_networks(self):
443 for network in self.reference_networks:
444 for key in network:
445 if key == self.WIFI_2G:
446 if "password" in network[key]:
447 self.secure_networks_2g.append(network[key])
448 else:
449 self.open_networks_2g.append(network[key])
450 else:
451 if "password" in network[key]:
452 self.secure_networks_5g.append(network[key])
453 else:
454 self.open_networks_5g.append(network[key])
455
456 def return_2g_secure_networks(self):
457 return self.secure_networks_2g
458
459 def return_5g_secure_networks(self):
460 return self.secure_networks_5g
461
462 def return_2g_open_networks(self):
463 return self.open_networks_2g
464
465 def return_5g_open_networks(self):
466 return self.open_networks_5g
467
468 def return_secure_networks(self):
469 return self.secure_networks_2g + self.secure_networks_5g
470
471 def return_open_networks(self):
472 return self.open_networks_2g + self.open_networks_5g
473
Ang Li82522812016-06-02 13:57:21 -0700474
475def _assert_on_fail_handler(func, assert_on_fail, *args, **kwargs):
476 """Wrapper function that handles the bahevior of assert_on_fail.
477
478 When assert_on_fail is True, let all test signals through, which can
479 terminate test cases directly. When assert_on_fail is False, the wrapper
480 raises no test signals and reports operation status by returning True or
481 False.
482
483 Args:
484 func: The function to wrap. This function reports operation status by
485 raising test signals.
486 assert_on_fail: A boolean that specifies if the output of the wrapper
487 is test signal based or return value based.
488 args: Positional args for func.
489 kwargs: Name args for func.
490
491 Returns:
492 If assert_on_fail is True, returns True/False to signal operation
493 status, otherwise return nothing.
494 """
495 try:
496 func(*args, **kwargs)
497 if not assert_on_fail:
498 return True
499 except signals.TestSignal:
500 if assert_on_fail:
501 raise
502 return False
503
504
505def assert_network_in_list(target, network_list):
506 """Makes sure a specified target Wi-Fi network exists in a list of Wi-Fi
507 networks.
508
509 Args:
510 target: A dict representing a Wi-Fi network.
511 E.g. {WifiEnums.SSID_KEY: "SomeNetwork"}
512 network_list: A list of dicts, each representing a Wi-Fi network.
513 """
514 match_results = match_networks(target, network_list)
515 asserts.assert_true(
516 match_results, "Target network %s, does not exist in network list %s" %
517 (target, network_list))
518
519
Ang Li73697b32015-12-03 00:41:53 +0000520def match_networks(target_params, networks):
521 """Finds the WiFi networks that match a given set of parameters in a list
522 of WiFi networks.
523
Girish Moturubc48d9f2016-11-01 13:24:14 -0700524 To be considered a match, the network should contain every key-value pair
525 of target_params
Ang Li73697b32015-12-03 00:41:53 +0000526
527 Args:
Girish Moturubc48d9f2016-11-01 13:24:14 -0700528 target_params: A dict with 1 or more key-value pairs representing a Wi-Fi network.
529 E.g { 'SSID': 'wh_ap1_5g', 'BSSID': '30:b5:c2:33:e4:47' }
Ang Li73697b32015-12-03 00:41:53 +0000530 networks: A list of dict objects representing WiFi networks.
531
532 Returns:
533 The networks that match the target parameters.
534 """
535 results = []
Betty Zhou3caa0982017-02-22 19:26:20 -0800536 asserts.assert_true(target_params,
537 "Expected networks object 'target_params' is empty")
Ang Li73697b32015-12-03 00:41:53 +0000538 for n in networks:
Girish Moturubc48d9f2016-11-01 13:24:14 -0700539 add_network = 1
Ang Li9a66de72016-02-08 15:26:38 -0800540 for k, v in target_params.items():
541 if k not in n:
Girish Moturubc48d9f2016-11-01 13:24:14 -0700542 add_network = 0
543 break
Ang Li9a66de72016-02-08 15:26:38 -0800544 if n[k] != v:
Girish Moturubc48d9f2016-11-01 13:24:14 -0700545 add_network = 0
546 break
547 if add_network:
Ang Li73697b32015-12-03 00:41:53 +0000548 results.append(n)
549 return results
550
Bindu Mahadev36725332019-01-29 12:23:21 -0800551
Roshan Pius93b519c2018-05-09 12:07:11 -0700552def wait_for_wifi_state(ad, state, assert_on_fail=True):
553 """Waits for the device to transition to the specified wifi state
554
555 Args:
556 ad: An AndroidDevice object.
557 state: Wifi state to wait for.
558 assert_on_fail: If True, error checks in this function will raise test
559 failure signals.
560
561 Returns:
562 If assert_on_fail is False, function returns True if the device transitions
563 to the specified state, False otherwise. If assert_on_fail is True, no return value.
564 """
565 return _assert_on_fail_handler(
566 _wait_for_wifi_state, assert_on_fail, ad, state=state)
567
568
569def _wait_for_wifi_state(ad, state):
570 """Toggles the state of wifi.
571
572 TestFailure signals are raised when something goes wrong.
573
574 Args:
575 ad: An AndroidDevice object.
576 state: Wifi state to wait for.
577 """
578 if state == ad.droid.wifiCheckState():
579 # Check if the state is already achieved, so we don't wait for the
580 # state change event by mistake.
581 return
582 ad.droid.wifiStartTrackingStateChange()
583 fail_msg = "Device did not transition to Wi-Fi state to %s on %s." % (state,
584 ad.serial)
585 try:
586 ad.ed.wait_for_event(wifi_constants.WIFI_STATE_CHANGED,
587 lambda x: x["data"]["enabled"] == state,
588 SHORT_TIMEOUT)
589 except Empty:
590 asserts.assert_equal(state, ad.droid.wifiCheckState(), fail_msg)
591 finally:
592 ad.droid.wifiStopTrackingStateChange()
Ang Li82522812016-06-02 13:57:21 -0700593
Bindu Mahadev36725332019-01-29 12:23:21 -0800594
Ang Li82522812016-06-02 13:57:21 -0700595def wifi_toggle_state(ad, new_state=None, assert_on_fail=True):
Ang Li6b557182015-11-11 17:19:17 -0800596 """Toggles the state of wifi.
Ang Li73697b32015-12-03 00:41:53 +0000597
Ang Li6b557182015-11-11 17:19:17 -0800598 Args:
599 ad: An AndroidDevice object.
600 new_state: Wifi state to set to. If None, opposite of the current state.
Ang Li82522812016-06-02 13:57:21 -0700601 assert_on_fail: If True, error checks in this function will raise test
602 failure signals.
Ang Li73697b32015-12-03 00:41:53 +0000603
Ang Li6b557182015-11-11 17:19:17 -0800604 Returns:
Ang Li82522812016-06-02 13:57:21 -0700605 If assert_on_fail is False, function returns True if the toggle was
606 successful, False otherwise. If assert_on_fail is True, no return value.
607 """
Betty Zhou3caa0982017-02-22 19:26:20 -0800608 return _assert_on_fail_handler(
609 _wifi_toggle_state, assert_on_fail, ad, new_state=new_state)
Ang Li82522812016-06-02 13:57:21 -0700610
611
612def _wifi_toggle_state(ad, new_state=None):
613 """Toggles the state of wifi.
614
615 TestFailure signals are raised when something goes wrong.
616
617 Args:
618 ad: An AndroidDevice object.
619 new_state: The state to set Wi-Fi to. If None, opposite of the current
620 state will be set.
Ang Li6b557182015-11-11 17:19:17 -0800621 """
Ang Li31b00782016-06-21 13:04:23 -0700622 if new_state is None:
623 new_state = not ad.droid.wifiCheckState()
Ang Lie5c85c92016-07-27 15:38:09 -0700624 elif new_state == ad.droid.wifiCheckState():
625 # Check if the new_state is already achieved, so we don't wait for the
626 # state change event by mistake.
627 return
628 ad.droid.wifiStartTrackingStateChange()
Ang Li31b00782016-06-21 13:04:23 -0700629 ad.log.info("Setting Wi-Fi state to %s.", new_state)
Roshan Pius5a027fa2018-05-04 13:59:38 -0700630 ad.ed.clear_all_events()
Ang Li31b00782016-06-21 13:04:23 -0700631 # Setting wifi state.
Ang Li6b557182015-11-11 17:19:17 -0800632 ad.droid.wifiToggleState(new_state)
Ang Lie2e93a22016-06-22 16:43:28 -0700633 fail_msg = "Failed to set Wi-Fi state to %s on %s." % (new_state,
634 ad.serial)
Ang Li73697b32015-12-03 00:41:53 +0000635 try:
Roshan Pius5a027fa2018-05-04 13:59:38 -0700636 ad.ed.wait_for_event(wifi_constants.WIFI_STATE_CHANGED,
637 lambda x: x["data"]["enabled"] == new_state,
638 SHORT_TIMEOUT)
Ang Li73697b32015-12-03 00:41:53 +0000639 except Empty:
Ang Li82522812016-06-02 13:57:21 -0700640 asserts.assert_equal(new_state, ad.droid.wifiCheckState(), fail_msg)
Ang Li6b557182015-11-11 17:19:17 -0800641 finally:
642 ad.droid.wifiStopTrackingStateChange()
643
Ang Li82522812016-06-02 13:57:21 -0700644
Ang Li6b557182015-11-11 17:19:17 -0800645def reset_wifi(ad):
Ang Li1179fa72016-06-16 09:44:06 -0700646 """Clears all saved Wi-Fi networks on a device.
647
648 This will turn Wi-Fi on.
Ang Li6b557182015-11-11 17:19:17 -0800649
650 Args:
651 ad: An AndroidDevice object.
652
Ang Li6b557182015-11-11 17:19:17 -0800653 """
Ang Li6b557182015-11-11 17:19:17 -0800654 networks = ad.droid.wifiGetConfiguredNetworks()
655 if not networks:
656 return
657 for n in networks:
658 ad.droid.wifiForgetNetwork(n['networkId'])
659 try:
Bindu Mahadev4e710362016-11-17 16:17:11 -0800660 event = ad.ed.pop_event(wifi_constants.WIFI_FORGET_NW_SUCCESS,
Ang Li82522812016-06-02 13:57:21 -0700661 SHORT_TIMEOUT)
Ang Li6b557182015-11-11 17:19:17 -0800662 except Empty:
Ang Li1179fa72016-06-16 09:44:06 -0700663 logging.warning("Could not confirm the removal of network %s.", n)
664 # Check again to see if there's any network left.
Betty Zhou3caa0982017-02-22 19:26:20 -0800665 asserts.assert_true(
666 not ad.droid.wifiGetConfiguredNetworks(),
667 "Failed to remove these configured Wi-Fi networks: %s" % networks)
Ang Li82522812016-06-02 13:57:21 -0700668
Ang Li73697b32015-12-03 00:41:53 +0000669
Bindu Mahadev1d3991e2017-03-20 18:06:54 -0700670def toggle_airplane_mode_on_and_off(ad):
671 """Turn ON and OFF Airplane mode.
Bindu Mahadev3c54c492017-02-15 16:00:08 -0800672
Bindu Mahadev1d3991e2017-03-20 18:06:54 -0700673 ad: An AndroidDevice object.
674 Returns: Assert if turning on/off Airplane mode fails.
Bindu Mahadev3c54c492017-02-15 16:00:08 -0800675
Bindu Mahadev1d3991e2017-03-20 18:06:54 -0700676 """
677 ad.log.debug("Toggling Airplane mode ON.")
678 asserts.assert_true(
679 utils.force_airplane_mode(ad, True),
680 "Can not turn on airplane mode on: %s" % ad.serial)
681 time.sleep(DEFAULT_TIMEOUT)
682 ad.log.debug("Toggling Airplane mode OFF.")
683 asserts.assert_true(
684 utils.force_airplane_mode(ad, False),
685 "Can not turn on airplane mode on: %s" % ad.serial)
686 time.sleep(DEFAULT_TIMEOUT)
Bindu Mahadev3c54c492017-02-15 16:00:08 -0800687
688
Bindu Mahadev1d3991e2017-03-20 18:06:54 -0700689def toggle_wifi_off_and_on(ad):
690 """Turn OFF and ON WiFi.
Bindu Mahadev3c54c492017-02-15 16:00:08 -0800691
Bindu Mahadev1d3991e2017-03-20 18:06:54 -0700692 ad: An AndroidDevice object.
693 Returns: Assert if turning off/on WiFi fails.
Bindu Mahadev3c54c492017-02-15 16:00:08 -0800694
Bindu Mahadev1d3991e2017-03-20 18:06:54 -0700695 """
696 ad.log.debug("Toggling wifi OFF.")
697 wifi_toggle_state(ad, False)
698 time.sleep(DEFAULT_TIMEOUT)
699 ad.log.debug("Toggling wifi ON.")
700 wifi_toggle_state(ad, True)
701 time.sleep(DEFAULT_TIMEOUT)
Bindu Mahadev3c54c492017-02-15 16:00:08 -0800702
703
Ang Li73697b32015-12-03 00:41:53 +0000704def wifi_forget_network(ad, net_ssid):
Ang Li8e767182015-12-09 17:29:24 -0800705 """Remove configured Wifi network on an android device.
Ang Li73697b32015-12-03 00:41:53 +0000706
Ang Li8e767182015-12-09 17:29:24 -0800707 Args:
708 ad: android_device object for forget network.
709 net_ssid: ssid of network to be forget
Ang Li73697b32015-12-03 00:41:53 +0000710
Ang Li8e767182015-12-09 17:29:24 -0800711 """
Girish Moturu40d7dc22016-11-02 12:14:56 -0700712 networks = ad.droid.wifiGetConfiguredNetworks()
Ang Li8e767182015-12-09 17:29:24 -0800713 if not networks:
714 return
715 for n in networks:
716 if net_ssid in n[WifiEnums.SSID_KEY]:
Girish Moturu40d7dc22016-11-02 12:14:56 -0700717 ad.droid.wifiForgetNetwork(n['networkId'])
Ang Li8e767182015-12-09 17:29:24 -0800718 try:
Bindu Mahadev4e710362016-11-17 16:17:11 -0800719 event = ad.ed.pop_event(wifi_constants.WIFI_FORGET_NW_SUCCESS,
Betty Zhou3caa0982017-02-22 19:26:20 -0800720 SHORT_TIMEOUT)
Ang Li8e767182015-12-09 17:29:24 -0800721 except Empty:
Girish Moturu1bf82302016-11-01 13:27:00 -0700722 asserts.fail("Failed to remove network %s." % n)
Ang Li73697b32015-12-03 00:41:53 +0000723
Ang Li82522812016-06-02 13:57:21 -0700724
Ang Li73697b32015-12-03 00:41:53 +0000725def wifi_test_device_init(ad):
726 """Initializes an android device for wifi testing.
727
728 0. Make sure SL4A connection is established on the android device.
729 1. Disable location service's WiFi scan.
730 2. Turn WiFi on.
731 3. Clear all saved networks.
732 4. Set country code to US.
733 5. Enable WiFi verbose logging.
734 6. Sync device time with computer time.
735 7. Turn off cellular data.
Ang Lifee28402016-07-13 13:43:29 -0700736 8. Turn off ambient display.
Ang Li73697b32015-12-03 00:41:53 +0000737 """
Ang Lifee28402016-07-13 13:43:29 -0700738 utils.require_sl4a((ad, ))
Ang Li73697b32015-12-03 00:41:53 +0000739 ad.droid.wifiScannerToggleAlwaysAvailable(False)
740 msg = "Failed to turn off location service's scan."
Ang Li82522812016-06-02 13:57:21 -0700741 asserts.assert_true(not ad.droid.wifiScannerIsAlwaysAvailable(), msg)
742 wifi_toggle_state(ad, True)
Ang Li6b557182015-11-11 17:19:17 -0800743 reset_wifi(ad)
Ang Li73697b32015-12-03 00:41:53 +0000744 ad.droid.wifiEnableVerboseLogging(1)
Ang Li8e767182015-12-09 17:29:24 -0800745 msg = "Failed to enable WiFi verbose logging."
Ang Li82522812016-06-02 13:57:21 -0700746 asserts.assert_equal(ad.droid.wifiGetVerboseLoggingLevel(), 1, msg)
Ang Li73697b32015-12-03 00:41:53 +0000747 # We don't verify the following settings since they are not critical.
Ang Lie2e93a22016-06-22 16:43:28 -0700748 # Set wpa_supplicant log level to EXCESSIVE.
749 output = ad.adb.shell("wpa_cli -i wlan0 -p -g@android:wpa_wlan0 IFNAME="
750 "wlan0 log_level EXCESSIVE")
751 ad.log.info("wpa_supplicant log change status: %s", output)
Ang Lifee28402016-07-13 13:43:29 -0700752 utils.sync_device_time(ad)
Ang Li0bf8e022016-01-04 17:34:48 -0800753 ad.droid.telephonyToggleDataConnection(False)
Ang Li73697b32015-12-03 00:41:53 +0000754 # TODO(angli): need to verify the country code was actually set. No generic
755 # way to check right now.
756 ad.adb.shell("halutil -country %s" % WifiEnums.CountryCode.US)
Ang Lifee28402016-07-13 13:43:29 -0700757 utils.set_ambient_display(ad, False)
Ang Li73697b32015-12-03 00:41:53 +0000758
Ang Li82522812016-06-02 13:57:21 -0700759
Ang Li6b557182015-11-11 17:19:17 -0800760def start_wifi_connection_scan(ad):
Ang Li73697b32015-12-03 00:41:53 +0000761 """Starts a wifi connection scan and wait for results to become available.
762
763 Args:
Ang Li6b557182015-11-11 17:19:17 -0800764 ad: An AndroidDevice object.
Ang Li73697b32015-12-03 00:41:53 +0000765 """
Roshan Pius7f61f1c2018-01-24 18:36:49 -0800766 ad.ed.clear_all_events()
Ang Li6b557182015-11-11 17:19:17 -0800767 ad.droid.wifiStartScan()
Ang Li82522812016-06-02 13:57:21 -0700768 try:
769 ad.ed.pop_event("WifiManagerScanResultsAvailable", 60)
770 except Empty:
771 asserts.fail("Wi-Fi results did not become available within 60s.")
772
Ang Li73697b32015-12-03 00:41:53 +0000773
Roshan Piuscb9bc482018-02-01 14:27:09 -0800774def start_wifi_connection_scan_and_return_status(ad):
775 """
776 Starts a wifi connection scan and wait for results to become available
777 or a scan failure to be reported.
778
779 Args:
780 ad: An AndroidDevice object.
781 Returns:
782 True: if scan succeeded & results are available
783 False: if scan failed
784 """
785 ad.ed.clear_all_events()
786 ad.droid.wifiStartScan()
787 try:
788 events = ad.ed.pop_events(
789 "WifiManagerScan(ResultsAvailable|Failure)", 60)
790 except Empty:
791 asserts.fail(
792 "Wi-Fi scan results/failure did not become available within 60s.")
793 # If there are multiple matches, we check for atleast one success.
794 for event in events:
795 if event["name"] == "WifiManagerScanResultsAvailable":
796 return True
797 elif event["name"] == "WifiManagerScanFailure":
798 ad.log.debug("Scan failure received")
799 return False
800
801
Roshan Pius7f61f1c2018-01-24 18:36:49 -0800802def start_wifi_connection_scan_and_check_for_network(ad, network_ssid,
Roshan Piuscb9bc482018-02-01 14:27:09 -0800803 max_tries=3):
Roshan Pius7f61f1c2018-01-24 18:36:49 -0800804 """
805 Start connectivity scans & checks if the |network_ssid| is seen in
806 scan results. The method performs a max of |max_tries| connectivity scans
807 to find the network.
808
809 Args:
810 ad: An AndroidDevice object.
811 network_ssid: SSID of the network we are looking for.
812 max_tries: Number of scans to try.
813 Returns:
814 True: if network_ssid is found in scan results.
815 False: if network_ssid is not found in scan results.
816 """
817 for num_tries in range(max_tries):
Roshan Piuscb9bc482018-02-01 14:27:09 -0800818 if start_wifi_connection_scan_and_return_status(ad):
819 scan_results = ad.droid.wifiGetScanResults()
820 match_results = match_networks(
821 {WifiEnums.SSID_KEY: network_ssid}, scan_results)
822 if len(match_results) > 0:
823 return True
Roshan Pius7f61f1c2018-01-24 18:36:49 -0800824 return False
825
826
827def start_wifi_connection_scan_and_ensure_network_found(ad, network_ssid,
Roshan Piuscb9bc482018-02-01 14:27:09 -0800828 max_tries=3):
Roshan Pius7f61f1c2018-01-24 18:36:49 -0800829 """
830 Start connectivity scans & ensure the |network_ssid| is seen in
831 scan results. The method performs a max of |max_tries| connectivity scans
832 to find the network.
833 This method asserts on failure!
834
835 Args:
836 ad: An AndroidDevice object.
837 network_ssid: SSID of the network we are looking for.
838 max_tries: Number of scans to try.
839 """
840 ad.log.info("Starting scans to ensure %s is present", network_ssid)
841 assert_msg = "Failed to find " + network_ssid + " in scan results" \
842 " after " + str(max_tries) + " tries"
843 asserts.assert_true(start_wifi_connection_scan_and_check_for_network(
844 ad, network_ssid, max_tries), assert_msg)
845
846
847def start_wifi_connection_scan_and_ensure_network_not_found(ad, network_ssid,
Roshan Piuscb9bc482018-02-01 14:27:09 -0800848 max_tries=3):
Roshan Pius7f61f1c2018-01-24 18:36:49 -0800849 """
850 Start connectivity scans & ensure the |network_ssid| is not seen in
851 scan results. The method performs a max of |max_tries| connectivity scans
852 to find the network.
853 This method asserts on failure!
854
855 Args:
856 ad: An AndroidDevice object.
857 network_ssid: SSID of the network we are looking for.
858 max_tries: Number of scans to try.
859 """
860 ad.log.info("Starting scans to ensure %s is not present", network_ssid)
861 assert_msg = "Found " + network_ssid + " in scan results" \
862 " after " + str(max_tries) + " tries"
863 asserts.assert_false(start_wifi_connection_scan_and_check_for_network(
864 ad, network_ssid, max_tries), assert_msg)
865
866
Ang Li73697b32015-12-03 00:41:53 +0000867def start_wifi_background_scan(ad, scan_setting):
868 """Starts wifi background scan.
869
870 Args:
871 ad: android_device object to initiate connection on.
872 scan_setting: A dict representing the settings of the scan.
873
874 Returns:
875 If scan was started successfully, event data of success event is returned.
876 """
Girish Moturu40d7dc22016-11-02 12:14:56 -0700877 idx = ad.droid.wifiScannerStartBackgroundScan(scan_setting)
878 event = ad.ed.pop_event("WifiScannerScan{}onSuccess".format(idx),
Betty Zhou3caa0982017-02-22 19:26:20 -0800879 SHORT_TIMEOUT)
Ang Li73697b32015-12-03 00:41:53 +0000880 return event['data']
881
Ang Li82522812016-06-02 13:57:21 -0700882
Roshan Piusce821342018-01-10 11:03:04 -0800883def start_wifi_tethering(ad, ssid, password, band=None, hidden=None):
Ang Li73697b32015-12-03 00:41:53 +0000884 """Starts wifi tethering on an android_device.
885
886 Args:
887 ad: android_device to start wifi tethering on.
888 ssid: The SSID the soft AP should broadcast.
889 password: The password the soft AP should use.
890 band: The band the soft AP should be set on. It should be either
891 WifiEnums.WIFI_CONFIG_APBAND_2G or WifiEnums.WIFI_CONFIG_APBAND_5G.
Roshan Piusce821342018-01-10 11:03:04 -0800892 hidden: boolean to indicate if the AP needs to be hidden or not.
Ang Li73697b32015-12-03 00:41:53 +0000893
894 Returns:
Girish Moturu3581d612016-11-02 15:08:51 -0700895 No return value. Error checks in this function will raise test failure signals
Ang Li73697b32015-12-03 00:41:53 +0000896 """
Ang Li82522812016-06-02 13:57:21 -0700897 config = {WifiEnums.SSID_KEY: ssid}
Ang Li73697b32015-12-03 00:41:53 +0000898 if password:
899 config[WifiEnums.PWD_KEY] = password
900 if band:
901 config[WifiEnums.APBAND_KEY] = band
Roshan Piusce821342018-01-10 11:03:04 -0800902 if hidden:
903 config[WifiEnums.HIDDEN_KEY] = hidden
Betty Zhou3caa0982017-02-22 19:26:20 -0800904 asserts.assert_true(
905 ad.droid.wifiSetWifiApConfiguration(config),
906 "Failed to update WifiAp Configuration")
Girish Moturu40d7dc22016-11-02 12:14:56 -0700907 ad.droid.wifiStartTrackingTetherStateChange()
908 ad.droid.connectivityStartTethering(tel_defines.TETHERING_WIFI, False)
Rebecca Silbersteina2889852016-08-11 00:48:53 -0700909 try:
Girish Moturu40d7dc22016-11-02 12:14:56 -0700910 ad.ed.pop_event("ConnectivityManagerOnTetheringStarted")
911 ad.ed.wait_for_event("TetherStateChanged",
Betty Zhou3caa0982017-02-22 19:26:20 -0800912 lambda x: x["data"]["ACTIVE_TETHER"], 30)
Ang Li76216d12016-09-20 14:51:57 -0700913 ad.log.debug("Tethering started successfully.")
Rebecca Silbersteina2889852016-08-11 00:48:53 -0700914 except Empty:
915 msg = "Failed to receive confirmation of wifi tethering starting"
916 asserts.fail(msg)
917 finally:
Girish Moturu40d7dc22016-11-02 12:14:56 -0700918 ad.droid.wifiStopTrackingTetherStateChange()
Ang Li73697b32015-12-03 00:41:53 +0000919
Bindu Mahadev36725332019-01-29 12:23:21 -0800920
Girish Moturu528b5442018-06-07 10:48:14 -0700921def save_wifi_soft_ap_config(ad, wifi_config, band=None, hidden=None):
922 """ Save a soft ap configuration """
923 if band:
924 wifi_config[WifiEnums.APBAND_KEY] = band
925 if hidden:
926 wifi_config[WifiEnums.HIDDEN_KEY] = hidden
927 asserts.assert_true(ad.droid.wifiSetWifiApConfiguration(wifi_config),
928 "Failed to set WifiAp Configuration")
929
930 wifi_ap = ad.droid.wifiGetApConfiguration()
931 asserts.assert_true(
932 wifi_ap[WifiEnums.SSID_KEY] == wifi_config[WifiEnums.SSID_KEY],
933 "Hotspot SSID doesn't match with expected SSID")
934
Xianyuan Jia0e39e552019-01-24 17:17:47 -0800935
Girish Moturu528b5442018-06-07 10:48:14 -0700936def start_wifi_tethering_saved_config(ad):
937 """ Turn on wifi hotspot with a config that is already saved """
938 ad.droid.wifiStartTrackingTetherStateChange()
939 ad.droid.connectivityStartTethering(tel_defines.TETHERING_WIFI, False)
940 try:
941 ad.ed.pop_event("ConnectivityManagerOnTetheringStarted")
942 ad.ed.wait_for_event("TetherStateChanged",
943 lambda x: x["data"]["ACTIVE_TETHER"], 30)
944 except:
945 asserts.fail("Didn't receive wifi tethering starting confirmation")
946 finally:
947 ad.droid.wifiStopTrackingTetherStateChange()
Betty Zhou3caa0982017-02-22 19:26:20 -0800948
Bindu Mahadev36725332019-01-29 12:23:21 -0800949
Ang Li73697b32015-12-03 00:41:53 +0000950def stop_wifi_tethering(ad):
951 """Stops wifi tethering on an android_device.
952
953 Args:
954 ad: android_device to stop wifi tethering on.
955 """
Girish Moturu40d7dc22016-11-02 12:14:56 -0700956 ad.droid.wifiStartTrackingTetherStateChange()
957 ad.droid.connectivityStopTethering(tel_defines.TETHERING_WIFI)
Rebecca Silbersteina2889852016-08-11 00:48:53 -0700958 try:
Girish Moturu40d7dc22016-11-02 12:14:56 -0700959 ad.ed.pop_event("WifiManagerApDisabled", 30)
960 ad.ed.wait_for_event("TetherStateChanged",
Betty Zhou3caa0982017-02-22 19:26:20 -0800961 lambda x: not x["data"]["ACTIVE_TETHER"], 30)
Rebecca Silbersteina2889852016-08-11 00:48:53 -0700962 except Empty:
963 msg = "Failed to receive confirmation of wifi tethering stopping"
964 asserts.fail(msg)
965 finally:
Girish Moturu40d7dc22016-11-02 12:14:56 -0700966 ad.droid.wifiStopTrackingTetherStateChange()
Ang Li82522812016-06-02 13:57:21 -0700967
Ang Li76216d12016-09-20 14:51:57 -0700968
Roshan Pius58916a32016-06-16 16:26:44 -0700969def toggle_wifi_and_wait_for_reconnection(ad,
970 network,
971 num_of_tries=1,
972 assert_on_fail=True):
973 """Toggle wifi state and then wait for Android device to reconnect to
974 the provided wifi network.
975
976 This expects the device to be already connected to the provided network.
977
978 Logic steps are
979 1. Ensure that we're connected to the network.
980 2. Turn wifi off.
981 3. Wait for 10 seconds.
982 4. Turn wifi on.
983 5. Wait for the "connected" event, then confirm the connected ssid is the
984 one requested.
985
986 Args:
987 ad: android_device object to initiate connection on.
988 network: A dictionary representing the network to await connection. The
989 dictionary must have the key "SSID".
990 num_of_tries: An integer that is the number of times to try before
991 delaring failure. Default is 1.
992 assert_on_fail: If True, error checks in this function will raise test
993 failure signals.
994
995 Returns:
996 If assert_on_fail is False, function returns True if the toggle was
997 successful, False otherwise. If assert_on_fail is True, no return value.
998 """
Betty Zhou3caa0982017-02-22 19:26:20 -0800999 return _assert_on_fail_handler(
1000 _toggle_wifi_and_wait_for_reconnection,
1001 assert_on_fail,
1002 ad,
1003 network,
1004 num_of_tries=num_of_tries)
Roshan Pius58916a32016-06-16 16:26:44 -07001005
1006
1007def _toggle_wifi_and_wait_for_reconnection(ad, network, num_of_tries=1):
1008 """Toggle wifi state and then wait for Android device to reconnect to
1009 the provided wifi network.
1010
1011 This expects the device to be already connected to the provided network.
1012
1013 Logic steps are
1014 1. Ensure that we're connected to the network.
1015 2. Turn wifi off.
1016 3. Wait for 10 seconds.
1017 4. Turn wifi on.
1018 5. Wait for the "connected" event, then confirm the connected ssid is the
1019 one requested.
1020
1021 This will directly fail a test if anything goes wrong.
1022
1023 Args:
1024 ad: android_device object to initiate connection on.
1025 network: A dictionary representing the network to await connection. The
1026 dictionary must have the key "SSID".
1027 num_of_tries: An integer that is the number of times to try before
1028 delaring failure. Default is 1.
1029 """
Roshan Pius58916a32016-06-16 16:26:44 -07001030 expected_ssid = network[WifiEnums.SSID_KEY]
1031 # First ensure that we're already connected to the provided network.
1032 verify_con = {WifiEnums.SSID_KEY: expected_ssid}
1033 verify_wifi_connection_info(ad, verify_con)
1034 # Now toggle wifi state and wait for the connection event.
1035 wifi_toggle_state(ad, False)
1036 time.sleep(10)
1037 wifi_toggle_state(ad, True)
1038 ad.droid.wifiStartTrackingStateChange()
1039 try:
1040 connect_result = None
1041 for i in range(num_of_tries):
1042 try:
Bindu Mahadev4e710362016-11-17 16:17:11 -08001043 connect_result = ad.ed.pop_event(wifi_constants.WIFI_CONNECTED,
Roshan Pius58916a32016-06-16 16:26:44 -07001044 30)
1045 break
1046 except Empty:
1047 pass
1048 asserts.assert_true(connect_result,
1049 "Failed to connect to Wi-Fi network %s on %s" %
Girish Moturu40d7dc22016-11-02 12:14:56 -07001050 (network, ad.serial))
Betty Zhou3caa0982017-02-22 19:26:20 -08001051 logging.debug("Connection result on %s: %s.", ad.serial,
1052 connect_result)
Roshan Pius58916a32016-06-16 16:26:44 -07001053 actual_ssid = connect_result['data'][WifiEnums.SSID_KEY]
1054 asserts.assert_equal(actual_ssid, expected_ssid,
1055 "Connected to the wrong network on %s."
1056 "Expected %s, but got %s." %
Girish Moturu40d7dc22016-11-02 12:14:56 -07001057 (ad.serial, expected_ssid, actual_ssid))
Betty Zhou3caa0982017-02-22 19:26:20 -08001058 logging.info("Connected to Wi-Fi network %s on %s", actual_ssid,
1059 ad.serial)
Roshan Pius58916a32016-06-16 16:26:44 -07001060 finally:
1061 ad.droid.wifiStopTrackingStateChange()
1062
1063
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001064def wait_for_connect(ad, ssid=None, id=None, tries=1):
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001065 """Wait for a connect event on queue and pop when available.
1066
1067 Args:
1068 ad: An Android device object.
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001069 ssid: SSID of the network to connect to.
1070 id: Network Id of the network to connect to.
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001071 tries: An integer that is the number of times to try before failing.
1072
1073 Returns:
1074 A dict with details of the connection data, which looks like this:
1075 {
1076 'time': 1485460337798,
1077 'name': 'WifiNetworkConnected',
1078 'data': {
1079 'rssi': -27,
1080 'is_24ghz': True,
1081 'mac_address': '02:00:00:00:00:00',
1082 'network_id': 1,
1083 'BSSID': '30:b5:c2:33:d3:fc',
1084 'ip_address': 117483712,
1085 'link_speed': 54,
1086 'supplicant_state': 'completed',
1087 'hidden_ssid': False,
1088 'SSID': 'wh_ap1_2g',
1089 'is_5ghz': False}
1090 }
1091
1092 """
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001093 conn_result = None
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001094
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001095 # If ssid and network id is None, just wait for any connect event.
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001096 if id is None and ssid is None:
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001097 for i in range(tries):
1098 try:
1099 conn_result = ad.ed.pop_event(wifi_constants.WIFI_CONNECTED, 30)
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001100 break
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001101 except Empty:
1102 pass
1103 else:
1104 # If ssid or network id is specified, wait for specific connect event.
1105 for i in range(tries):
1106 try:
1107 conn_result = ad.ed.pop_event(wifi_constants.WIFI_CONNECTED, 30)
1108 if id and conn_result['data'][WifiEnums.NETID_KEY] == id:
1109 break
1110 elif ssid and conn_result['data'][WifiEnums.SSID_KEY] == ssid:
1111 break
1112 except Empty:
1113 pass
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001114
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001115 return conn_result
1116
1117
1118def wait_for_disconnect(ad):
1119 """Wait for a Disconnect event from the supplicant.
1120
1121 Args:
1122 ad: Android device object.
1123
1124 """
1125 try:
1126 ad.droid.wifiStartTrackingStateChange()
1127 event = ad.ed.pop_event("WifiNetworkDisconnected", 10)
1128 ad.droid.wifiStopTrackingStateChange()
Roshan Piusbf7e3982018-02-15 12:37:41 -08001129 except Empty:
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001130 raise signals.TestFailure("Device did not disconnect from the network")
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001131
1132
Bindu Mahadev27c2d292018-03-19 16:13:08 -07001133def connect_to_wifi_network(ad, network, assert_on_fail=True,
Joe Brennan48c3f692019-04-11 08:30:16 -07001134 check_connectivity=True, hidden=False):
Bindu Mahadev3876ae52017-12-19 14:22:19 -08001135 """Connection logic for open and psk wifi networks.
1136
1137 Args:
Jong Wook Kim92356922018-02-06 18:32:49 -08001138 ad: AndroidDevice to use for connection
1139 network: network info of the network to connect to
1140 assert_on_fail: If true, errors from wifi_connect will raise
1141 test failure signals.
Joe Brennan48c3f692019-04-11 08:30:16 -07001142 hidden: Is the Wifi network hidden.
Bindu Mahadev3876ae52017-12-19 14:22:19 -08001143 """
Joe Brennan48c3f692019-04-11 08:30:16 -07001144 if hidden:
1145 start_wifi_connection_scan_and_ensure_network_not_found(
1146 ad, network[WifiEnums.SSID_KEY])
1147 else:
1148 start_wifi_connection_scan_and_ensure_network_found(
1149 ad, network[WifiEnums.SSID_KEY])
Jong Wook Kim92356922018-02-06 18:32:49 -08001150 wifi_connect(ad,
1151 network,
1152 num_of_tries=3,
Bindu Mahadev27c2d292018-03-19 16:13:08 -07001153 assert_on_fail=assert_on_fail,
1154 check_connectivity=check_connectivity)
Bindu Mahadev3876ae52017-12-19 14:22:19 -08001155
1156
1157def connect_to_wifi_network_with_id(ad, network_id, network_ssid):
1158 """Connect to the given network using network id and verify SSID.
1159
1160 Args:
1161 network_id: int Network Id of the network.
1162 network_ssid: string SSID of the network.
1163
1164 Returns: True if connect using network id was successful;
1165 False otherwise.
1166
1167 """
Jong Wook Kim92356922018-02-06 18:32:49 -08001168 start_wifi_connection_scan_and_ensure_network_found(ad, network_ssid)
Bindu Mahadev3876ae52017-12-19 14:22:19 -08001169 wifi_connect_by_id(ad, network_id)
1170 connect_data = ad.droid.wifiGetConnectionInfo()
1171 connect_ssid = connect_data[WifiEnums.SSID_KEY]
1172 ad.log.debug("Expected SSID = %s Connected SSID = %s" %
1173 (network_ssid, connect_ssid))
1174 if connect_ssid != network_ssid:
1175 return False
1176 return True
1177
1178
Bindu Mahadev27c2d292018-03-19 16:13:08 -07001179def wifi_connect(ad, network, num_of_tries=1, assert_on_fail=True,
1180 check_connectivity=True):
Ang Li99d8c6d2015-12-09 15:56:13 -08001181 """Connect an Android device to a wifi network.
Ang Li73697b32015-12-03 00:41:53 +00001182
1183 Initiate connection to a wifi network, wait for the "connected" event, then
Ang Li99d8c6d2015-12-09 15:56:13 -08001184 confirm the connected ssid is the one requested.
Ang Li73697b32015-12-03 00:41:53 +00001185
Ang Li82522812016-06-02 13:57:21 -07001186 This will directly fail a test if anything goes wrong.
1187
Ang Li73697b32015-12-03 00:41:53 +00001188 Args:
1189 ad: android_device object to initiate connection on.
Ang Li99d8c6d2015-12-09 15:56:13 -08001190 network: A dictionary representing the network to connect to. The
Ang Li82522812016-06-02 13:57:21 -07001191 dictionary must have the key "SSID".
1192 num_of_tries: An integer that is the number of times to try before
1193 delaring failure. Default is 1.
1194 assert_on_fail: If True, error checks in this function will raise test
1195 failure signals.
1196
1197 Returns:
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001198 Returns a value only if assert_on_fail is false.
1199 Returns True if the connection was successful, False otherwise.
Ang Li73697b32015-12-03 00:41:53 +00001200 """
Betty Zhou3caa0982017-02-22 19:26:20 -08001201 return _assert_on_fail_handler(
Bindu Mahadev27c2d292018-03-19 16:13:08 -07001202 _wifi_connect, assert_on_fail, ad, network, num_of_tries=num_of_tries,
1203 check_connectivity=check_connectivity)
Ang Li82522812016-06-02 13:57:21 -07001204
1205
Bindu Mahadev27c2d292018-03-19 16:13:08 -07001206def _wifi_connect(ad, network, num_of_tries=1, check_connectivity=True):
Ang Li82522812016-06-02 13:57:21 -07001207 """Connect an Android device to a wifi network.
1208
1209 Initiate connection to a wifi network, wait for the "connected" event, then
1210 confirm the connected ssid is the one requested.
1211
1212 This will directly fail a test if anything goes wrong.
1213
1214 Args:
1215 ad: android_device object to initiate connection on.
1216 network: A dictionary representing the network to connect to. The
1217 dictionary must have the key "SSID".
1218 num_of_tries: An integer that is the number of times to try before
1219 delaring failure. Default is 1.
1220 """
Ang Li82522812016-06-02 13:57:21 -07001221 asserts.assert_true(WifiEnums.SSID_KEY in network,
1222 "Key '%s' must be present in network definition." %
1223 WifiEnums.SSID_KEY)
Ang Li99d8c6d2015-12-09 15:56:13 -08001224 ad.droid.wifiStartTrackingStateChange()
Betty Zhoud35dab82016-12-06 15:24:23 -08001225 expected_ssid = network[WifiEnums.SSID_KEY]
Bindu Mahadev50374df2017-01-04 11:03:32 -08001226 ad.droid.wifiConnectByConfig(network)
1227 ad.log.info("Starting connection process to %s", expected_ssid)
Ang Li73697b32015-12-03 00:41:53 +00001228 try:
Bindu Mahadev50374df2017-01-04 11:03:32 -08001229 event = ad.ed.pop_event(wifi_constants.CONNECT_BY_CONFIG_SUCCESS, 30)
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001230 connect_result = wait_for_connect(ad, ssid=expected_ssid, tries=num_of_tries)
Ang Li82522812016-06-02 13:57:21 -07001231 asserts.assert_true(connect_result,
1232 "Failed to connect to Wi-Fi network %s on %s" %
Girish Moturubc48d9f2016-11-01 13:24:14 -07001233 (network, ad.serial))
Ang Li31b00782016-06-21 13:04:23 -07001234 ad.log.debug("Wi-Fi connection result: %s.", connect_result)
Ang Li99d8c6d2015-12-09 15:56:13 -08001235 actual_ssid = connect_result['data'][WifiEnums.SSID_KEY]
Ang Li82522812016-06-02 13:57:21 -07001236 asserts.assert_equal(actual_ssid, expected_ssid,
Betty Zhou3caa0982017-02-22 19:26:20 -08001237 "Connected to the wrong network on %s." %
1238 ad.serial)
Ang Li31b00782016-06-21 13:04:23 -07001239 ad.log.info("Connected to Wi-Fi network %s.", actual_ssid)
Bindu Mahadev50374df2017-01-04 11:03:32 -08001240
1241 # Wait for data connection to stabilize.
1242 time.sleep(5)
1243
Bindu Mahadev27c2d292018-03-19 16:13:08 -07001244 if check_connectivity:
1245 internet = validate_connection(ad, DEFAULT_PING_ADDR)
1246 if not internet:
1247 raise signals.TestFailure("Failed to connect to internet on %s" %
1248 expected_ssid)
Bindu Mahadev50374df2017-01-04 11:03:32 -08001249 except Empty:
1250 asserts.fail("Failed to start connection process to %s on %s" %
1251 (network, ad.serial))
Bindu Mahadev4e710362016-11-17 16:17:11 -08001252 except Exception as error:
Bindu Mahadev50374df2017-01-04 11:03:32 -08001253 ad.log.error("Failed to connect to %s with error %s", expected_ssid,
1254 error)
1255 raise signals.TestFailure("Failed to connect to %s network" % network)
1256
Ang Li73697b32015-12-03 00:41:53 +00001257 finally:
Ang Li99d8c6d2015-12-09 15:56:13 -08001258 ad.droid.wifiStopTrackingStateChange()
Ang Li73697b32015-12-03 00:41:53 +00001259
Bindu Mahadev50374df2017-01-04 11:03:32 -08001260
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001261def wifi_connect_by_id(ad, network_id, num_of_tries=3, assert_on_fail=True):
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001262 """Connect an Android device to a wifi network using network Id.
1263
1264 Start connection to the wifi network, with the given network Id, wait for
1265 the "connected" event, then verify the connected network is the one requested.
1266
1267 This will directly fail a test if anything goes wrong.
1268
1269 Args:
1270 ad: android_device object to initiate connection on.
1271 network_id: Integer specifying the network id of the network.
1272 num_of_tries: An integer that is the number of times to try before
1273 delaring failure. Default is 1.
1274 assert_on_fail: If True, error checks in this function will raise test
1275 failure signals.
1276
1277 Returns:
1278 Returns a value only if assert_on_fail is false.
1279 Returns True if the connection was successful, False otherwise.
1280 """
1281 _assert_on_fail_handler(_wifi_connect_by_id, assert_on_fail, ad,
1282 network_id, num_of_tries)
1283
1284
1285def _wifi_connect_by_id(ad, network_id, num_of_tries=1):
1286 """Connect an Android device to a wifi network using it's network id.
1287
1288 Start connection to the wifi network, with the given network id, wait for
1289 the "connected" event, then verify the connected network is the one requested.
1290
1291 Args:
1292 ad: android_device object to initiate connection on.
1293 network_id: Integer specifying the network id of the network.
1294 num_of_tries: An integer that is the number of times to try before
1295 delaring failure. Default is 1.
1296 """
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001297 ad.droid.wifiStartTrackingStateChange()
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001298 # Clear all previous events.
1299 ad.ed.clear_all_events()
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001300 ad.droid.wifiConnectByNetworkId(network_id)
1301 ad.log.info("Starting connection to network with id %d", network_id)
1302 try:
1303 event = ad.ed.pop_event(wifi_constants.CONNECT_BY_NETID_SUCCESS, 60)
Bindu Mahadevaf983c92017-03-27 12:00:37 -07001304 connect_result = wait_for_connect(ad, id=network_id, tries=num_of_tries)
Bindu Mahadev3c54c492017-02-15 16:00:08 -08001305 asserts.assert_true(connect_result,
1306 "Failed to connect to Wi-Fi network using network id")
1307 ad.log.debug("Wi-Fi connection result: %s", connect_result)
1308 actual_id = connect_result['data'][WifiEnums.NETID_KEY]
1309 asserts.assert_equal(actual_id, network_id,
1310 "Connected to the wrong network on %s."
1311 "Expected network id = %d, but got %d." %
1312 (ad.serial, network_id, actual_id))
1313 expected_ssid = connect_result['data'][WifiEnums.SSID_KEY]
1314 ad.log.info("Connected to Wi-Fi network %s with %d network id.",
1315 expected_ssid, network_id)
1316
1317 # Wait for data connection to stabilize.
1318 time.sleep(5)
1319
1320 internet = validate_connection(ad, DEFAULT_PING_ADDR)
1321 if not internet:
1322 raise signals.TestFailure("Failed to connect to internet on %s" %
1323 expected_ssid)
1324 except Empty:
1325 asserts.fail("Failed to connect to network with id %d on %s" %
1326 (network_id, ad.serial))
1327 except Exception as error:
1328 ad.log.error("Failed to connect to network with id %d with error %s",
1329 network_id, error)
1330 raise signals.TestFailure("Failed to connect to network with network"
1331 " id %d" % network_id)
1332 finally:
1333 ad.droid.wifiStopTrackingStateChange()
1334
1335
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001336def wifi_passpoint_connect(ad, passpoint_network, num_of_tries=1,
1337 assert_on_fail=True):
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001338 """Connect an Android device to a wifi network.
1339
1340 Initiate connection to a wifi network, wait for the "connected" event, then
1341 confirm the connected ssid is the one requested.
1342
1343 This will directly fail a test if anything goes wrong.
1344
1345 Args:
1346 ad: android_device object to initiate connection on.
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001347 passpoint_network: SSID of the Passpoint network to connect to.
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001348 num_of_tries: An integer that is the number of times to try before
1349 delaring failure. Default is 1.
1350 assert_on_fail: If True, error checks in this function will raise test
1351 failure signals.
1352
1353 Returns:
1354 If assert_on_fail is False, function returns network id, if the connect was
1355 successful, False otherwise. If assert_on_fail is True, no return value.
1356 """
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001357 _assert_on_fail_handler(_wifi_passpoint_connect, assert_on_fail, ad,
1358 passpoint_network, num_of_tries = num_of_tries)
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001359
1360
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001361def _wifi_passpoint_connect(ad, passpoint_network, num_of_tries=1):
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001362 """Connect an Android device to a wifi network.
1363
1364 Initiate connection to a wifi network, wait for the "connected" event, then
1365 confirm the connected ssid is the one requested.
1366
1367 This will directly fail a test if anything goes wrong.
1368
1369 Args:
1370 ad: android_device object to initiate connection on.
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001371 passpoint_network: SSID of the Passpoint network to connect to.
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001372 num_of_tries: An integer that is the number of times to try before
1373 delaring failure. Default is 1.
1374 """
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001375 ad.droid.wifiStartTrackingStateChange()
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001376 expected_ssid = passpoint_network
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001377 ad.log.info("Starting connection process to passpoint %s", expected_ssid)
1378
1379 try:
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001380 connect_result = wait_for_connect(ad, expected_ssid, num_of_tries)
Bindu Mahadev9dd48172017-03-06 17:04:34 -08001381 asserts.assert_true(connect_result,
1382 "Failed to connect to WiFi passpoint network %s on"
1383 " %s" % (expected_ssid, ad.serial))
1384 ad.log.info("Wi-Fi connection result: %s.", connect_result)
1385 actual_ssid = connect_result['data'][WifiEnums.SSID_KEY]
1386 asserts.assert_equal(actual_ssid, expected_ssid,
1387 "Connected to the wrong network on %s." % ad.serial)
1388 ad.log.info("Connected to Wi-Fi passpoint network %s.", actual_ssid)
1389
1390 # Wait for data connection to stabilize.
1391 time.sleep(5)
1392
1393 internet = validate_connection(ad, DEFAULT_PING_ADDR)
1394 if not internet:
1395 raise signals.TestFailure("Failed to connect to internet on %s" %
1396 expected_ssid)
1397 except Exception as error:
1398 ad.log.error("Failed to connect to passpoint network %s with error %s",
1399 expected_ssid, error)
1400 raise signals.TestFailure("Failed to connect to %s passpoint network" %
1401 expected_ssid)
1402
1403 finally:
1404 ad.droid.wifiStopTrackingStateChange()
1405
1406
Bindu Mahadevd4542a82017-04-05 09:50:17 -07001407def delete_passpoint(ad, fqdn):
1408 """Delete a required Passpoint configuration."""
1409 try:
1410 ad.droid.removePasspointConfig(fqdn)
1411 return True
1412 except Exception as error:
1413 ad.log.error("Failed to remove passpoint configuration with FQDN=%s "
1414 "and error=%s" , fqdn, error)
1415 return False
1416
1417
Ang Li73697b32015-12-03 00:41:53 +00001418def start_wifi_single_scan(ad, scan_setting):
1419 """Starts wifi single shot scan.
1420
1421 Args:
1422 ad: android_device object to initiate connection on.
1423 scan_setting: A dict representing the settings of the scan.
1424
1425 Returns:
1426 If scan was started successfully, event data of success event is returned.
1427 """
Ang Li82522812016-06-02 13:57:21 -07001428 idx = ad.droid.wifiScannerStartScan(scan_setting)
1429 event = ad.ed.pop_event("WifiScannerScan%sonSuccess" % idx, SHORT_TIMEOUT)
Ang Li31b00782016-06-21 13:04:23 -07001430 ad.log.debug("Got event %s", event)
Ang Li73697b32015-12-03 00:41:53 +00001431 return event['data']
1432
Ang Li82522812016-06-02 13:57:21 -07001433
Ang Li73697b32015-12-03 00:41:53 +00001434def track_connection(ad, network_ssid, check_connection_count):
1435 """Track wifi connection to network changes for given number of counts
1436
1437 Args:
1438 ad: android_device object for forget network.
1439 network_ssid: network ssid to which connection would be tracked
1440 check_connection_count: Integer for maximum number network connection
Ang Li82522812016-06-02 13:57:21 -07001441 check.
Ang Li73697b32015-12-03 00:41:53 +00001442 Returns:
Ang Li73697b32015-12-03 00:41:53 +00001443 True if connection to given network happen, else return False.
1444 """
Girish Moturu40d7dc22016-11-02 12:14:56 -07001445 ad.droid.wifiStartTrackingStateChange()
Ang Li73697b32015-12-03 00:41:53 +00001446 while check_connection_count > 0:
Girish Moturu40d7dc22016-11-02 12:14:56 -07001447 connect_network = ad.ed.pop_event("WifiNetworkConnected", 120)
Ang Li31b00782016-06-21 13:04:23 -07001448 ad.log.info("Connected to network %s", connect_network)
Ang Li82522812016-06-02 13:57:21 -07001449 if (WifiEnums.SSID_KEY in connect_network['data'] and
1450 connect_network['data'][WifiEnums.SSID_KEY] == network_ssid):
1451 return True
Ang Li8e767182015-12-09 17:29:24 -08001452 check_connection_count -= 1
Girish Moturu40d7dc22016-11-02 12:14:56 -07001453 ad.droid.wifiStopTrackingStateChange()
Ang Li73697b32015-12-03 00:41:53 +00001454 return False
1455
Ang Li82522812016-06-02 13:57:21 -07001456
Ang Li73697b32015-12-03 00:41:53 +00001457def get_scan_time_and_channels(wifi_chs, scan_setting, stime_channel):
1458 """Calculate the scan time required based on the band or channels in scan
1459 setting
1460
1461 Args:
1462 wifi_chs: Object of channels supported
1463 scan_setting: scan setting used for start scan
1464 stime_channel: scan time per channel
1465
1466 Returns:
1467 scan_time: time required for completing a scan
1468 scan_channels: channel used for scanning
1469 """
1470 scan_time = 0
1471 scan_channels = []
1472 if "band" in scan_setting and "channels" not in scan_setting:
Ang Li8e767182015-12-09 17:29:24 -08001473 scan_channels = wifi_chs.band_to_freq(scan_setting["band"])
Ang Li73697b32015-12-03 00:41:53 +00001474 elif "channels" in scan_setting and "band" not in scan_setting:
Ang Li8e767182015-12-09 17:29:24 -08001475 scan_channels = scan_setting["channels"]
Ang Li73697b32015-12-03 00:41:53 +00001476 scan_time = len(scan_channels) * stime_channel
1477 for channel in scan_channels:
Ang Li8e767182015-12-09 17:29:24 -08001478 if channel in WifiEnums.DFS_5G_FREQUENCIES:
Ang Li82522812016-06-02 13:57:21 -07001479 scan_time += 132 #passive scan time on DFS
Ang Li73697b32015-12-03 00:41:53 +00001480 return scan_time, scan_channels
1481
Ang Li82522812016-06-02 13:57:21 -07001482
Ang Li73697b32015-12-03 00:41:53 +00001483def start_wifi_track_bssid(ad, track_setting):
1484 """Start tracking Bssid for the given settings.
1485
1486 Args:
1487 ad: android_device object.
1488 track_setting: Setting for which the bssid tracking should be started
1489
1490 Returns:
1491 If tracking started successfully, event data of success event is returned.
1492 """
Girish Moturu40d7dc22016-11-02 12:14:56 -07001493 idx = ad.droid.wifiScannerStartTrackingBssids(
Ang Li82522812016-06-02 13:57:21 -07001494 track_setting["bssidInfos"], track_setting["apLostThreshold"])
Girish Moturu40d7dc22016-11-02 12:14:56 -07001495 event = ad.ed.pop_event("WifiScannerBssid{}onSuccess".format(idx),
Betty Zhou3caa0982017-02-22 19:26:20 -08001496 SHORT_TIMEOUT)
Ang Li73697b32015-12-03 00:41:53 +00001497 return event['data']
1498
Ang Li82522812016-06-02 13:57:21 -07001499
Ang Li73697b32015-12-03 00:41:53 +00001500def convert_pem_key_to_pkcs8(in_file, out_file):
1501 """Converts the key file generated by us to the format required by
1502 Android using openssl.
1503
1504 The input file must have the extension "pem". The output file must
1505 have the extension "der".
1506
1507 Args:
1508 in_file: The original key file.
1509 out_file: The full path to the converted key file, including
1510 filename.
1511 """
Ang Li82522812016-06-02 13:57:21 -07001512 asserts.assert_true(in_file.endswith(".pem"), "Input file has to be .pem.")
1513 asserts.assert_true(
1514 out_file.endswith(".der"), "Output file has to be .der.")
Ang Li73697b32015-12-03 00:41:53 +00001515 cmd = ("openssl pkcs8 -inform PEM -in {} -outform DER -out {} -nocrypt"
1516 " -topk8").format(in_file, out_file)
Ang Lifee28402016-07-13 13:43:29 -07001517 utils.exe_cmd(cmd)
Ang Li73697b32015-12-03 00:41:53 +00001518
Ang Li82522812016-06-02 13:57:21 -07001519
Girish Moturu7f287522017-09-25 13:33:06 -07001520def validate_connection(ad, ping_addr=DEFAULT_PING_ADDR):
Ang Li73697b32015-12-03 00:41:53 +00001521 """Validate internet connection by pinging the address provided.
1522
1523 Args:
1524 ad: android_device object.
1525 ping_addr: address on internet for pinging.
1526
1527 Returns:
Bindu Mahadev50374df2017-01-04 11:03:32 -08001528 ping output if successful, NULL otherwise.
Ang Li73697b32015-12-03 00:41:53 +00001529 """
Bindu Mahadev795578e2019-04-11 16:46:50 -07001530 # Adding 2 secs timeout before pinging to allow for DHCP to complete.
1531 time.sleep(2)
Girish Moturu40d7dc22016-11-02 12:14:56 -07001532 ping = ad.droid.httpPing(ping_addr)
Ang Li31b00782016-06-21 13:04:23 -07001533 ad.log.info("Http ping result: %s.", ping)
Ang Li73697b32015-12-03 00:41:53 +00001534 return ping
1535
Ang Li82522812016-06-02 13:57:21 -07001536
Ang Li73697b32015-12-03 00:41:53 +00001537#TODO(angli): This can only verify if an actual value is exactly the same.
1538# Would be nice to be able to verify an actual value is one of serveral.
1539def verify_wifi_connection_info(ad, expected_con):
1540 """Verifies that the information of the currently connected wifi network is
1541 as expected.
1542
1543 Args:
1544 expected_con: A dict representing expected key-value pairs for wifi
1545 connection. e.g. {"SSID": "test_wifi"}
1546 """
1547 current_con = ad.droid.wifiGetConnectionInfo()
Ang Li374d7602016-02-08 17:27:27 -08001548 case_insensitive = ["BSSID", "supplicant_state"]
Ang Li31b00782016-06-21 13:04:23 -07001549 ad.log.debug("Current connection: %s", current_con)
Ang Li73697b32015-12-03 00:41:53 +00001550 for k, expected_v in expected_con.items():
Ang Li9a66de72016-02-08 15:26:38 -08001551 # Do not verify authentication related fields.
1552 if k == "password":
1553 continue
Ang Li82522812016-06-02 13:57:21 -07001554 msg = "Field %s does not exist in wifi connection info %s." % (
1555 k, current_con)
Ang Li374d7602016-02-08 17:27:27 -08001556 if k not in current_con:
1557 raise signals.TestFailure(msg)
1558 actual_v = current_con[k]
1559 if k in case_insensitive:
1560 actual_v = actual_v.lower()
1561 expected_v = expected_v.lower()
Ang Li73697b32015-12-03 00:41:53 +00001562 msg = "Expected %s to be %s, actual %s is %s." % (k, expected_v, k,
Ang Li82522812016-06-02 13:57:21 -07001563 actual_v)
Ang Li374d7602016-02-08 17:27:27 -08001564 if actual_v != expected_v:
1565 raise signals.TestFailure(msg)
Ang Li73697b32015-12-03 00:41:53 +00001566
Ang Li82522812016-06-02 13:57:21 -07001567
Preetesh Barrettoe8c428b2019-02-14 09:15:44 -08001568def check_autoconnect_to_open_network(ad, conn_timeout=WIFI_CONNECTION_TIMEOUT_DEFAULT):
1569 """Connects to any open WiFI AP
1570 Args:
1571 timeout value in sec to wait for UE to connect to a WiFi AP
1572 Returns:
1573 True if UE connects to WiFi AP (supplicant_state = completed)
1574 False if UE fails to complete connection within WIFI_CONNECTION_TIMEOUT time.
1575 """
1576 if ad.droid.wifiCheckState():
1577 return True
1578 ad.droid.wifiToggleState()
1579 wifi_connection_state = None
1580 timeout = time.time() + conn_timeout
1581 while wifi_connection_state != "completed":
1582 wifi_connection_state = ad.droid.wifiGetConnectionInfo()[
1583 'supplicant_state']
1584 if time.time() > timeout:
1585 ad.log.warning("Failed to connect to WiFi AP")
1586 return False
1587 return True
1588
1589
Ang Li73697b32015-12-03 00:41:53 +00001590def expand_enterprise_config_by_phase2(config):
1591 """Take an enterprise config and generate a list of configs, each with
1592 a different phase2 auth type.
1593
1594 Args:
1595 config: A dict representing enterprise config.
1596
1597 Returns
1598 A list of enterprise configs.
1599 """
1600 results = []
Ang Li0e7e58f2016-02-22 12:15:02 -08001601 phase2_types = WifiEnums.EapPhase2
1602 if config[WifiEnums.Enterprise.EAP] == WifiEnums.Eap.PEAP:
1603 # Skip unsupported phase2 types for PEAP.
1604 phase2_types = [WifiEnums.EapPhase2.GTC, WifiEnums.EapPhase2.MSCHAPV2]
1605 for phase2_type in phase2_types:
Ang Li73697b32015-12-03 00:41:53 +00001606 # Skip a special case for passpoint TTLS.
1607 if (WifiEnums.Enterprise.FQDN in config and
Ang Li82522812016-06-02 13:57:21 -07001608 phase2_type == WifiEnums.EapPhase2.GTC):
Ang Li73697b32015-12-03 00:41:53 +00001609 continue
1610 c = dict(config)
Girish Moturu150d32f2017-02-14 12:27:07 -08001611 c[WifiEnums.Enterprise.PHASE2] = phase2_type.value
Ang Li73697b32015-12-03 00:41:53 +00001612 results.append(c)
1613 return results
Ang Li2d3fe982016-06-08 10:00:43 -07001614
1615
Girish Moturub48a13c2017-02-27 11:36:42 -08001616def generate_eap_test_name(config, ad=None):
Girish Moturu150d32f2017-02-14 12:27:07 -08001617 """ Generates a test case name based on an EAP configuration.
1618
1619 Args:
1620 config: A dict representing an EAP credential.
Girish Moturub48a13c2017-02-27 11:36:42 -08001621 ad object: Redundant but required as the same param is passed
1622 to test_func in run_generated_tests
Girish Moturu150d32f2017-02-14 12:27:07 -08001623
1624 Returns:
1625 A string representing the name of a generated EAP test case.
1626 """
1627 eap = WifiEnums.Eap
1628 eap_phase2 = WifiEnums.EapPhase2
Girish Moturub48a13c2017-02-27 11:36:42 -08001629 Ent = WifiEnums.Enterprise
Girish Moturu150d32f2017-02-14 12:27:07 -08001630 name = "test_connect-"
1631 eap_name = ""
1632 for e in eap:
1633 if e.value == config[Ent.EAP]:
1634 eap_name = e.name
1635 break
1636 if "peap0" in config[WifiEnums.SSID_KEY].lower():
1637 eap_name = "PEAP0"
1638 if "peap1" in config[WifiEnums.SSID_KEY].lower():
1639 eap_name = "PEAP1"
1640 name += eap_name
1641 if Ent.PHASE2 in config:
1642 for e in eap_phase2:
1643 if e.value == config[Ent.PHASE2]:
1644 name += "-{}".format(e.name)
1645 break
1646 return name
1647
1648
Ang Li2d3fe982016-06-08 10:00:43 -07001649def group_attenuators(attenuators):
1650 """Groups a list of attenuators into attenuator groups for backward
1651 compatibility reasons.
1652
1653 Most legacy Wi-Fi setups have two attenuators each connected to a separate
1654 AP. The new Wi-Fi setup has four attenuators, each connected to one channel
1655 on an AP, so two of them are connected to one AP.
1656
1657 To make the existing scripts work in the new setup, when the script needs
1658 to attenuate one AP, it needs to set attenuation on both attenuators
1659 connected to the same AP.
1660
1661 This function groups attenuators properly so the scripts work in both
1662 legacy and new Wi-Fi setups.
1663
1664 Args:
1665 attenuators: A list of attenuator objects, either two or four in length.
1666
1667 Raises:
1668 signals.TestFailure is raised if the attenuator list does not have two
1669 or four objects.
1670 """
1671 attn0 = attenuator.AttenuatorGroup("AP0")
1672 attn1 = attenuator.AttenuatorGroup("AP1")
1673 # Legacy testbed setup has two attenuation channels.
1674 num_of_attns = len(attenuators)
1675 if num_of_attns == 2:
1676 attn0.add(attenuators[0])
1677 attn1.add(attenuators[1])
1678 elif num_of_attns == 4:
1679 attn0.add(attenuators[0])
1680 attn0.add(attenuators[1])
1681 attn1.add(attenuators[2])
1682 attn1.add(attenuators[3])
1683 else:
1684 asserts.fail(("Either two or four attenuators are required for this "
1685 "test, but found %s") % num_of_attns)
1686 return [attn0, attn1]
Jong Wook Kim92356922018-02-06 18:32:49 -08001687
Bindu Mahadev36725332019-01-29 12:23:21 -08001688
Bindu Mahadev7060a9f2018-05-04 13:48:12 -07001689def set_attns(attenuator, attn_val_name):
1690 """Sets attenuation values on attenuators used in this test.
1691
1692 Args:
1693 attenuator: The attenuator object.
1694 attn_val_name: Name of the attenuation value pair to use.
1695 """
1696 logging.info("Set attenuation values to %s", roaming_attn[attn_val_name])
1697 try:
1698 attenuator[0].set_atten(roaming_attn[attn_val_name][0])
1699 attenuator[1].set_atten(roaming_attn[attn_val_name][1])
1700 attenuator[2].set_atten(roaming_attn[attn_val_name][2])
1701 attenuator[3].set_atten(roaming_attn[attn_val_name][3])
1702 except:
1703 logging.exception("Failed to set attenuation values %s.",
1704 attn_val_name)
1705 raise
1706
Bindu Mahadev36725332019-01-29 12:23:21 -08001707
Hsiu-Chang Chen038e93d2018-11-15 12:24:06 +08001708def set_attns_steps(attenuator, attn_val_name, steps=10, wait_time=12):
1709 """Sets attenuation values on attenuators used in this test.
1710
1711 Args:
1712 attenuator: The attenuator object.
1713 attn_val_name: Name of the attenuation value pair to use.
1714 steps: Number of attenuator changes to reach the target value.
1715 wait_time: Sleep time for each change of attenuator.
1716 """
1717 logging.info("Set attenuation values to %s in %d step(s)", roaming_attn[attn_val_name], steps)
1718 current_atten = [
1719 attenuator[0].get_atten(), attenuator[1].get_atten(),
1720 attenuator[2].get_atten(), attenuator[3].get_atten()]
1721 target_atten = [
1722 roaming_attn[attn_val_name][0], roaming_attn[attn_val_name][1],
1723 roaming_attn[attn_val_name][2], roaming_attn[attn_val_name][3]]
1724 while steps > 0:
1725 next_atten = list(map(
1726 lambda x, y: round((y + (steps - 1) * x) / steps) , current_atten, target_atten))
1727 try:
1728 attenuator[0].set_atten(next_atten[0])
1729 attenuator[1].set_atten(next_atten[1])
1730 attenuator[2].set_atten(next_atten[2])
1731 attenuator[3].set_atten(next_atten[3])
1732 time.sleep(wait_time)
1733 except:
1734 logging.exception("Failed to set attenuation values %s.", attn_val_name)
1735 raise
1736 current_atten = next_atten
1737 steps = steps - 1
Bindu Mahadev7060a9f2018-05-04 13:48:12 -07001738
Bindu Mahadev36725332019-01-29 12:23:21 -08001739
Bindu Mahadev7060a9f2018-05-04 13:48:12 -07001740def trigger_roaming_and_validate(dut, attenuator, attn_val_name, expected_con):
1741 """Sets attenuators to trigger roaming and validate the DUT connected
1742 to the BSSID expected.
1743
1744 Args:
1745 attenuator: The attenuator object.
1746 attn_val_name: Name of the attenuation value pair to use.
1747 expected_con: The network information of the expected network.
1748 """
1749 expected_con = {
1750 WifiEnums.SSID_KEY: expected_con[WifiEnums.SSID_KEY],
1751 WifiEnums.BSSID_KEY: expected_con["bssid"],
1752 }
Hsiu-Chang Chen038e93d2018-11-15 12:24:06 +08001753 set_attns_steps(attenuator, attn_val_name)
Bindu Mahadev7060a9f2018-05-04 13:48:12 -07001754
Hsiu-Chang Chenef856402018-09-18 12:32:49 +08001755 verify_wifi_connection_info(dut, expected_con)
1756 expected_bssid = expected_con[WifiEnums.BSSID_KEY]
1757 logging.info("Roamed to %s successfully", expected_bssid)
1758 if not validate_connection(dut):
1759 raise signals.TestFailure("Fail to connect to internet on %s" %
1760 expected_bssid)
Jong Wook Kim92356922018-02-06 18:32:49 -08001761
Bindu Mahadev36725332019-01-29 12:23:21 -08001762
Jong Wook Kim92356922018-02-06 18:32:49 -08001763def create_softap_config():
1764 """Create a softap config with random ssid and password."""
1765 ap_ssid = "softap_" + utils.rand_ascii_str(8)
1766 ap_password = utils.rand_ascii_str(8)
1767 logging.info("softap setup: %s %s", ap_ssid, ap_password)
1768 config = {
1769 WifiEnums.SSID_KEY: ap_ssid,
1770 WifiEnums.PWD_KEY: ap_password,
1771 }
1772 return config
Girish Moturucf4dccd2018-08-27 12:22:00 -07001773
Bindu Mahadev36725332019-01-29 12:23:21 -08001774
1775def start_softap_and_verify(ad, band):
1776 """Bring-up softap and verify AP mode and in scan results.
1777
1778 Args:
1779 band: The band to use for softAP.
1780
1781 Returns: dict, the softAP config.
1782
1783 """
1784 config = create_softap_config()
1785 start_wifi_tethering(ad.dut,
1786 config[WifiEnums.SSID_KEY],
1787 config[WifiEnums.PWD_KEY], band=band)
1788 asserts.assert_true(ad.dut.droid.wifiIsApEnabled(),
1789 "SoftAp is not reported as running")
1790 start_wifi_connection_scan_and_ensure_network_found(ad.dut_client,
1791 config[WifiEnums.SSID_KEY])
1792 return config
1793
leslc9f0ab22019-02-22 17:06:04 +08001794def wait_for_expected_number_of_softap_clients(ad, callbackId,
1795 expected_num_of_softap_clients):
1796 """Wait for the number of softap clients to be updated as expected.
1797 Args:
1798 callbackId: Id of the callback associated with registering.
1799 expected_num_of_softap_clients: expected number of softap clients.
1800 """
1801 eventStr = wifi_constants.SOFTAP_CALLBACK_EVENT + str(
1802 callbackId) + wifi_constants.SOFTAP_NUMBER_CLIENTS_CHANGED
1803 asserts.assert_equal(ad.ed.pop_event(eventStr,
1804 SHORT_TIMEOUT)['data'][wifi_constants.
1805 SOFTAP_NUMBER_CLIENTS_CALLBACK_KEY],
1806 expected_num_of_softap_clients,
1807 "Number of softap clients doesn't match with expected number")
1808
1809def wait_for_expected_softap_state(ad, callbackId, expected_softap_state):
1810 """Wait for the expected softap state change.
1811 Args:
1812 callbackId: Id of the callback associated with registering.
1813 expected_softap_state: The expected softap state.
1814 """
1815 eventStr = wifi_constants.SOFTAP_CALLBACK_EVENT + str(
1816 callbackId) + wifi_constants.SOFTAP_STATE_CHANGED
1817 asserts.assert_equal(ad.ed.pop_event(eventStr,
1818 SHORT_TIMEOUT)['data'][wifi_constants.
1819 SOFTAP_STATE_CHANGE_CALLBACK_KEY],
1820 expected_softap_state,
1821 "Softap state doesn't match with expected state")
1822
1823def get_current_number_of_softap_clients(ad, callbackId):
1824 """pop up all of softap client updated event from queue.
1825 Args:
1826 callbackId: Id of the callback associated with registering.
1827
1828 Returns:
1829 If exist aleast callback, returns last updated number_of_softap_clients.
1830 Returns None when no any match callback event in queue.
1831 """
1832 eventStr = wifi_constants.SOFTAP_CALLBACK_EVENT + str(
1833 callbackId) + wifi_constants.SOFTAP_NUMBER_CLIENTS_CHANGED
1834 events = ad.ed.pop_all(eventStr)
1835 for event in events:
1836 num_of_clients = event['data'][wifi_constants.
1837 SOFTAP_NUMBER_CLIENTS_CALLBACK_KEY]
1838 if len(events) == 0:
1839 return None
1840 return num_of_clients
1841
Bindu Mahadev36725332019-01-29 12:23:21 -08001842
Xianyuan Jia0e39e552019-01-24 17:17:47 -08001843def start_pcap(pcap, wifi_band, test_name):
Girish Moturucf4dccd2018-08-27 12:22:00 -07001844 """Start packet capture in monitor mode.
1845
1846 Args:
1847 pcap: packet capture object
1848 wifi_band: '2g' or '5g' or 'dual'
Bindu Mahadev76551c12018-12-13 19:42:14 +00001849 test_name: test name to be used for pcap file name
1850
1851 Returns:
xianyuanjia0431ba32018-12-14 09:56:42 -08001852 Dictionary with wifi band as key and the tuple
1853 (pcap Process object, log directory) as the value
Girish Moturucf4dccd2018-08-27 12:22:00 -07001854 """
Xianyuan Jia0e39e552019-01-24 17:17:47 -08001855 log_dir = os.path.join(
1856 context.get_current_context.get_full_output_path(), 'PacketCapture')
Bindu Mahadev76551c12018-12-13 19:42:14 +00001857 utils.create_dir(log_dir)
Girish Moturucf4dccd2018-08-27 12:22:00 -07001858 if wifi_band == 'dual':
1859 bands = [BAND_2G, BAND_5G]
1860 else:
1861 bands = [wifi_band]
xianyuanjia0431ba32018-12-14 09:56:42 -08001862 procs = {}
Girish Moturucf4dccd2018-08-27 12:22:00 -07001863 for band in bands:
xianyuanjia0431ba32018-12-14 09:56:42 -08001864 proc = pcap.start_packet_capture(band, log_dir, test_name)
1865 procs[band] = (proc, os.path.join(log_dir, test_name))
1866 return procs
Girish Moturucf4dccd2018-08-27 12:22:00 -07001867
Bindu Mahadev36725332019-01-29 12:23:21 -08001868
xianyuanjia0431ba32018-12-14 09:56:42 -08001869def stop_pcap(pcap, procs, test_status=None):
Bindu Mahadev76551c12018-12-13 19:42:14 +00001870 """Stop packet capture in monitor mode.
1871
1872 Since, the pcap logs in monitor mode can be very large, we will
1873 delete them if they are not required. 'test_status' if True, will delete
1874 the pcap files. If False, we will keep them.
Girish Moturucf4dccd2018-08-27 12:22:00 -07001875
1876 Args:
1877 pcap: packet capture object
xianyuanjia0431ba32018-12-14 09:56:42 -08001878 procs: dictionary returned by start_pcap
Bindu Mahadev76551c12018-12-13 19:42:14 +00001879 test_status: status of the test case
Girish Moturucf4dccd2018-08-27 12:22:00 -07001880 """
xianyuanjia0431ba32018-12-14 09:56:42 -08001881 for proc, fname in procs.values():
1882 pcap.stop_packet_capture(proc)
Bindu Mahadev76551c12018-12-13 19:42:14 +00001883
1884 if test_status:
xianyuanjia0431ba32018-12-14 09:56:42 -08001885 shutil.rmtree(os.path.dirname(fname))
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08001886
Bindu Mahadev36725332019-01-29 12:23:21 -08001887
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08001888def start_cnss_diags(ads):
1889 for ad in ads:
1890 start_cnss_diag(ad)
1891
Bindu Mahadev36725332019-01-29 12:23:21 -08001892
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08001893def start_cnss_diag(ad):
1894 """Start cnss_diag to record extra wifi logs
1895
1896 Args:
1897 ad: android device object.
1898 """
1899 if ad.model in wifi_constants.DEVICES_USING_LEGACY_PROP:
1900 prop = wifi_constants.LEGACY_CNSS_DIAG_PROP
1901 else:
1902 prop = wifi_constants.CNSS_DIAG_PROP
1903 if ad.adb.getprop(prop) != 'true':
1904 ad.adb.shell("find /data/vendor/wifi/cnss_diag/wlan_logs/ -type f -delete")
1905 ad.adb.shell("setprop %s true" % prop, ignore_status=True)
1906
Bindu Mahadev36725332019-01-29 12:23:21 -08001907
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08001908def stop_cnss_diags(ads):
1909 for ad in ads:
1910 stop_cnss_diag(ad)
1911
Bindu Mahadev36725332019-01-29 12:23:21 -08001912
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08001913def stop_cnss_diag(ad):
1914 """Stops cnss_diag
1915
1916 Args:
1917 ad: android device object.
1918 """
1919 if ad.model in wifi_constants.DEVICES_USING_LEGACY_PROP:
1920 prop = wifi_constants.LEGACY_CNSS_DIAG_PROP
1921 else:
1922 prop = wifi_constants.CNSS_DIAG_PROP
1923 ad.adb.shell("setprop %s false" % prop, ignore_status=True)
1924
Bindu Mahadev36725332019-01-29 12:23:21 -08001925
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08001926def get_cnss_diag_log(ad, test_name=""):
1927 """Pulls the cnss_diag logs in the wlan_logs dir
1928 Args:
1929 ad: android device object.
1930 test_name: test case name
1931 """
1932 logs = ad.get_file_names("/data/vendor/wifi/cnss_diag/wlan_logs/")
1933 if logs:
1934 ad.log.info("Pulling cnss_diag logs %s", logs)
Xianyuan Jia0e39e552019-01-24 17:17:47 -08001935 log_path = os.path.join(ad.device_log_path, "CNSS_DIAG_%s" % ad.serial)
Hsiu-Chang Chenf8578472018-09-18 12:23:42 +08001936 utils.create_dir(log_path)
1937 ad.pull_files(logs, log_path)
Bindu Mahadev7e5dc682019-02-01 16:53:34 -08001938
Bindu Mahadev36725332019-01-29 12:23:21 -08001939
Bindu Mahadev7e5dc682019-02-01 16:53:34 -08001940def ap_setup(test, index, ap, network, bandwidth=80, channel=6):
1941 """Set up the AP with provided network info.
1942
1943 Args:
1944 test: the calling test class object.
1945 index: int, index of the AP.
1946 ap: access_point object of the AP.
1947 network: dict with information of the network, including ssid,
1948 password and bssid.
1949 bandwidth: the operation bandwidth for the AP, default 80MHz.
1950 channel: the channel number for the AP.
1951 Returns:
1952 brconfigs: the bridge interface configs
1953 """
1954 bss_settings = []
1955 ssid = network[WifiEnums.SSID_KEY]
1956 test.access_points[index].close()
1957 time.sleep(5)
1958
1959 # Configure AP as required.
1960 if "password" in network.keys():
1961 password = network["password"]
1962 security = hostapd_security.Security(
1963 security_mode="wpa", password=password)
1964 else:
1965 security = hostapd_security.Security(security_mode=None, password=None)
1966 config = hostapd_ap_preset.create_ap_preset(
1967 channel=channel,
1968 ssid=ssid,
1969 security=security,
1970 bss_settings=bss_settings,
1971 vht_bandwidth=bandwidth,
1972 profile_name='whirlwind',
1973 iface_wlan_2g=ap.wlan_2g,
1974 iface_wlan_5g=ap.wlan_5g)
1975 ap.start_ap(config)
1976 logging.info("AP started on channel {} with SSID {}".format(channel, ssid))
Bindu Mahadev36725332019-01-29 12:23:21 -08001977
1978
1979def turn_ap_off(test, AP):
1980 """Bring down hostapd on the Access Point.
1981 Args:
1982 test: The test class object.
1983 AP: int, indicating which AP to turn OFF.
1984 """
1985 hostapd_2g = test.access_points[AP-1]._aps['wlan0'].hostapd
1986 if hostapd_2g.is_alive():
1987 hostapd_2g.stop()
1988 logging.debug('Turned WLAN0 AP%d off' % AP)
1989 hostapd_5g = test.access_points[AP-1]._aps['wlan1'].hostapd
1990 if hostapd_5g.is_alive():
1991 hostapd_5g.stop()
1992 logging.debug('Turned WLAN1 AP%d off' % AP)
1993
1994
1995def turn_ap_on(test, AP):
1996 """Bring up hostapd on the Access Point.
1997 Args:
1998 test: The test class object.
1999 AP: int, indicating which AP to turn ON.
2000 """
2001 hostapd_2g = test.access_points[AP-1]._aps['wlan0'].hostapd
2002 if not hostapd_2g.is_alive():
2003 hostapd_2g.start(hostapd_2g.config)
2004 logging.debug('Turned WLAN0 AP%d on' % AP)
2005 hostapd_5g = test.access_points[AP-1]._aps['wlan1'].hostapd
2006 if not hostapd_5g.is_alive():
2007 hostapd_5g.start(hostapd_5g.config)
2008 logging.debug('Turned WLAN1 AP%d on' % AP)
Joe Brennan48c3f692019-04-11 08:30:16 -07002009
2010
2011def turn_location_off_and_scan_toggle_off(ad):
2012 """Turns off wifi location scans."""
2013 utils.set_location_service(ad, False)
2014 ad.droid.wifiScannerToggleAlwaysAvailable(False)
2015 msg = "Failed to turn off location service's scan."
2016 asserts.assert_true(not ad.droid.wifiScannerIsAlwaysAvailable(), msg)