1#!/usr/bin/env python3.4
2#
3#   Copyright 2016 - The Android Open Source Project
4#
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
17import itertools
18import queue
19import time
20import traceback
21
22from acts import asserts
23from acts import base_test
24from acts import utils
25from acts.test_decorators import test_tracker_info
26from acts.test_utils.wifi import wifi_constants
27from acts.test_utils.wifi import wifi_test_utils as wutils
28from acts.test_utils.wifi.WifiBaseTest import WifiBaseTest
29
30SCANTIME = 10000  #framework support only 10s as minimum scan interval
31NUMBSSIDPERSCAN = 8
32EVENT_TAG = "WifiScannerScan"
33SCAN_TIME_PASSIVE = 47  # dwell time plus 2ms
34SCAN_TIME_ACTIVE = 32  # dwell time plus 2ms
35SHORT_TIMEOUT = 30
36NETWORK_ID_ERROR = "Network don't have ID"
37NETWORK_ERROR = "Device is not connected to reference network"
38INVALID_RESULT = "Test fail because scan result reported are not valid"
39EMPTY_RESULT = "Test fail because empty scan result reported"
40KEY_RET = "ResultElapsedRealtime"
41ATTENUATOR = 0
42
43class WifiScannerScanError(Exception):
44    pass
45
46
47class WifiScannerScanTest(WifiBaseTest):
48    def __init__(self, controllers):
49        WifiBaseTest.__init__(self, controllers)
50        # TODO(angli): Remove this list.
51        # There are order dependencies among these tests so we'll have to leave
52        # it here for now. :(
53        self.tests = (
54            "test_available_channels_band_1",
55            "test_available_channels_band_2",
56            "test_available_channels_band_3",
57            "test_available_channels_band_4",
58            "test_available_channels_band_6",
59            "test_available_channels_band_7",
60            "test_wifi_scanner_single_scan_channel_sanity",
61            "test_wifi_scanner_with_wifi_off",
62            "test_single_scan_report_each_scan_for_channels_with_enumerated_params",
63            "test_single_scan_report_each_scan_for_band_with_enumerated_params",
64            "test_wifi_scanner_batch_scan_channel_sanity",
65            "test_wifi_scanner_batch_scan_period_too_short",
66            "test_batch_scan_report_buffer_full_for_channels_with_enumerated_params",
67            "test_batch_scan_report_buffer_full_for_band_with_enumerated_params",
68            "test_batch_scan_report_each_scan_for_channels_with_enumerated_params",
69            "test_batch_scan_report_each_scan_for_band_with_enumerated_params",
70            "test_single_scan_report_full_scan_for_channels_with_enumerated_params",
71            "test_single_scan_report_full_scan_for_band_with_enumerated_params",
72            "test_batch_scan_report_full_scan_for_channels_with_enumerated_params",
73            "test_batch_scan_report_full_scan_for_band_with_enumerated_params",
74            "test_wifi_connection_while_single_scan",
75            "test_single_scan_while_pno",
76            "test_wifi_connection_and_pno_while_batch_scan",
77            "test_wifi_scanner_single_scan_in_isolated",
78            "test_wifi_scanner_with_invalid_numBssidsPerScan",
79            "test_wifi_scanner_dual_radio_low_latency",
80            "test_wifi_scanner_dual_radio_low_power",
81            "test_wifi_scanner_dual_radio_high_accuracy")
82
83    def setup_class(self):
84        self.dut = self.android_devices[0]
85        wutils.wifi_test_device_init(self.dut)
86        req_params = ("run_extended_test", "ping_addr", "max_bugreports", "dbs_supported_models")
87        opt_param = ["reference_networks"]
88        self.unpack_userparams(
89            req_param_names=req_params, opt_param_names=opt_param)
90
91        if "AccessPoint" in self.user_params:
92            self.legacy_configure_ap_and_start()
93
94        self.leeway = 10
95        self.stime_channel = SCAN_TIME_PASSIVE
96        self.default_scan_setting = {
97            "band": wutils.WifiEnums.WIFI_BAND_BOTH,
98            "periodInMs": SCANTIME,
99            "reportEvents": wutils.WifiEnums.REPORT_EVENT_AFTER_EACH_SCAN
100        }
101        self.default_batch_scan_setting = {
102            "band": wutils.WifiEnums.WIFI_BAND_BOTH,
103            "periodInMs": SCANTIME,
104            "reportEvents": wutils.WifiEnums.REPORT_EVENT_AFTER_BUFFER_FULL
105        }
106        self.log.debug("Run extended test: {}".format(self.run_extended_test))
107        self.wifi_chs = wutils.WifiChannelUS(self.dut.model)
108        asserts.assert_true(self.dut.droid.wifiIsScannerSupported(),
109                            "Device %s doesn't support WifiScanner, abort." %
110                            self.dut.model)
111        self.attenuators = wutils.group_attenuators(self.attenuators)
112        self.attenuators[0].set_atten(0)
113        self.attenuators[1].set_atten(0)
114        self.dut.droid.wifiEnableWifiConnectivityManager(False)
115
116    def teardown_test(self):
117        base_test.BaseTestClass.teardown_test(self)
118        self.log.debug("Shut down all wifi scanner activities.")
119        self.dut.droid.wifiScannerShutdown()
120
121    def on_fail(self, test_name, begin_time):
122        if self.max_bugreports > 0:
123            self.dut.take_bug_report(test_name, begin_time)
124            self.max_bugreports -= 1
125        self.dut.cat_adb_log(test_name, begin_time)
126
127    def teardown_class(self):
128        self.dut.droid.wifiEnableWifiConnectivityManager(True)
129        if "AccessPoint" in self.user_params:
130            del self.user_params["reference_networks"]
131            del self.user_params["open_network"]
132
133    """ Helper Functions Begin """
134
135    def wifi_generate_scanner_scan_settings(self, extended, scan_type,
136                                            report_result):
137        """Generates all the combinations of different scan setting parameters.
138
139        Args:
140          extended: True for extended setting
141          scan_type: key for type of scan
142          report_result: event type of report scan results
143
144        Returns:
145          A list of dictionaries each representing a set of scan settings.
146        """
147        base_scan_time = [SCANTIME * 2]
148        if scan_type == "band":
149            scan_types_setting = [wutils.WifiEnums.WIFI_BAND_BOTH]
150        else:
151            scan_types_setting = [self.wifi_chs.MIX_CHANNEL_SCAN]
152        num_of_bssid = [NUMBSSIDPERSCAN * 4]
153        max_scan_cache = [0]
154        if extended:
155            base_scan_time.append(SCANTIME)
156            if scan_type == "band":
157                scan_types_setting.extend(
158                    [wutils.WifiEnums.WIFI_BAND_24_GHZ,
159                     wutils.WifiEnums.WIFI_BAND_5_GHZ_WITH_DFS,
160                     wutils.WifiEnums.WIFI_BAND_BOTH_WITH_DFS])
161            else:
162                scan_types_setting.extend(
163                    [self.wifi_chs.NONE_DFS_5G_FREQUENCIES, self.wifi_chs.
164                     ALL_2G_FREQUENCIES, self.wifi_chs.DFS_5G_FREQUENCIES,
165                     self.wifi_chs.ALL_5G_FREQUENCIES])
166            num_of_bssid.append(NUMBSSIDPERSCAN * 3)
167            max_scan_cache.append(5)
168            # Generate all the combinations of report types and scan types
169        if report_result == wutils.WifiEnums.REPORT_EVENT_FULL_SCAN_RESULT:
170            report_types = {"reportEvents": report_result}
171            setting_combinations = list(itertools.product(scan_types_setting,
172                                                          base_scan_time))
173            # Create scan setting strings based on the combinations
174            scan_settings = []
175            for combo in setting_combinations:
176                s = dict(report_types)
177                s[scan_type] = combo[0]
178                s["periodInMs"] = combo[1]
179                scan_settings.append(s)
180        else:
181            report_types = {"reportEvents": report_result}
182            setting_combinations = list(
183                itertools.product(scan_types_setting, base_scan_time,
184                                  num_of_bssid, max_scan_cache))
185            # Create scan setting strings based on the combinations
186            scan_settings = []
187            for combo in setting_combinations:
188                s = dict(report_types)
189                s[scan_type] = combo[0]
190                s["periodInMs"] = combo[1]
191                s["numBssidsPerScan"] = combo[2]
192                s["maxScansToCache"] = combo[3]
193                scan_settings.append(s)
194        return scan_settings
195
196    def proces_and_valid_batch_scan_result(self, scan_resutls, scan_rt,
197                                           result_rt, scan_setting):
198        """This function process scan results and validate against settings used
199        while starting the scan.
200
201        There are two steps for the verification. First it checks that all the
202        wifi networks in results are of the correct frequencies set by scan setting
203        params. Then it checks that the delta between the batch of scan results less
204        than the time required for scanning channel set by scan setting params.
205
206        Args:
207            scan_results: scan results reported.
208            scan_rt: Elapsed real time on start scan.
209            result_rt: Elapsed ral time on results reported.
210            scan_setting: The params for the single scan.
211
212        Returns:
213            bssids: total number of bssids scan result have
214            validity: True if the all scan result are valid.
215        """
216        bssids = 0
217        validity = True
218        scan_time_mic = 0
219        scan_channels = []
220        scan_time, scan_channels = wutils.get_scan_time_and_channels(
221            self.wifi_chs, scan_setting, self.stime_channel)
222        scan_time_mic = scan_time * 1000
223        for i, batch in enumerate(scan_resutls, start=1):
224            asserts.assert_true(
225                batch["ScanResults"],
226                "At least one scan result is required to validate")
227            max_scan_interval = batch["ScanResults"][0][
228                "timestamp"] + scan_time_mic
229            self.log.debug("max_scan_interval: %s", max_scan_interval)
230            for result in batch["ScanResults"]:
231                if (result["frequency"] not in scan_channels or
232                        result["timestamp"] > max_scan_interval or
233                        result["timestamp"] < scan_rt * 1000 or
234                        result["timestamp"] > result_rt * 1000):
235                    self.log.error("Result didn't match requirement: %s",
236                                   result)
237                    validity = False
238            self.log.info("Number of scan result in batch %s: %s", i,
239                          len(batch["ScanResults"]))
240            bssids += len(batch["ScanResults"])
241        return bssids, validity
242
243    def pop_scan_result_events(self, event_name):
244        """Function to pop all the scan result events.
245
246        Args:
247            event_name: event name.
248
249        Returns:
250            results: list  of scan result reported in events
251        """
252        results = []
253        try:
254            events = self.dut.ed.pop_all(event_name)
255            for event in events:
256                results.append(event["data"]["Results"])
257        except queue.Empty as error:
258            self.log.debug("Number of Full scan results %s", len(results))
259        return results
260
261    def wifi_scanner_single_scan(self, scan_setting):
262        """Common logic for an enumerated wifi scanner single scan test case.
263
264         1. Start WifiScanner single scan for scan_setting.
265         2. Wait for the scan result event, wait time depend on scan settings
266            parameter.
267         3. Verify that scan results match with scan settings parameters.
268         4. Also verify that only one scan result event trigger.
269
270        Args:
271            scan_setting: The params for the single scan.
272        """
273        data = wutils.start_wifi_single_scan(self.dut, scan_setting)
274        idx = data["Index"]
275        scan_rt = data["ScanElapsedRealtime"]
276        self.log.info(
277            "Wifi single shot scan started index: %s at real time: %s", idx,
278            scan_rt)
279        results = []
280        #generating event wait time from scan setting plus leeway
281        scan_time, scan_channels = wutils.get_scan_time_and_channels(
282            self.wifi_chs, scan_setting, self.stime_channel)
283        wait_time = int(scan_time / 1000) + self.leeway
284        validity = False
285        #track number of result received
286        result_received = 0
287        try:
288            for snumber in range(1, 3):
289                event_name = "{}{}onResults".format(EVENT_TAG, idx)
290                self.log.debug("Waiting for event: %s for time %s", event_name,
291                               wait_time)
292                event = self.dut.ed.pop_event(event_name, wait_time)
293                self.log.debug("Event received: %s", event)
294                results = event["data"]["Results"]
295                result_received += 1
296                bssids, validity = self.proces_and_valid_batch_scan_result(
297                    results, scan_rt, event["data"][KEY_RET], scan_setting)
298                asserts.assert_equal(
299                    len(results), 1,
300                    "Test fail because number of scan result %s" %
301                    len(results))
302                asserts.assert_true(bssids > 0, EMPTY_RESULT)
303                asserts.assert_true(validity, INVALID_RESULT)
304                self.log.info("Scan number Buckets: %s\nTotal BSSID: %s",
305                              len(results), bssids)
306        except queue.Empty as error:
307            asserts.assert_true(
308                result_received >= 1,
309                "Event did not triggered for single shot {}".format(error))
310        finally:
311            self.dut.droid.wifiScannerStopScan(idx)
312            #For single shot number of result received and length of result should be one
313            asserts.assert_true(
314                result_received == 1,
315                "Test fail because received result {}".format(result_received))
316
317    def wifi_scanner_single_scan_full(self, scan_setting):
318        """Common logic for single scan test case for full scan result.
319
320        1. Start WifiScanner single scan with scan_setting for full scan result.
321        2. Wait for the scan result event, wait time depend on scan settings
322           parameter.
323        3. Pop all full scan result events occurred earlier.
324        4. Verify that full scan results match with normal scan results.
325        5. If the scan type is included in scan_setting, verify that the
326           radioChainInfos length.
327
328        Args:
329            scan_setting: The parameters for the single scan.
330        """
331        self.dut.ed.clear_all_events()
332        data = wutils.start_wifi_single_scan(self.dut, scan_setting)
333        idx = data["Index"]
334        scan_rt = data["ScanElapsedRealtime"]
335        self.log.info("Wifi single shot scan started with index: %s", idx)
336        #generating event wait time from scan setting plus leeway
337        scan_time, scan_channels = wutils.get_scan_time_and_channels(
338            self.wifi_chs, scan_setting, self.stime_channel)
339        wait_time = int(scan_time / 1000) + self.leeway
340        results = []
341        validity = False
342        try:
343            event_name = "%s%sonResults" % (EVENT_TAG, idx)
344            self.log.debug("Waiting for event: %s for time %s", event_name,
345                           wait_time)
346            event = self.dut.ed.pop_event(event_name, wait_time)
347            self.log.info("Event received: %s", event)
348            bssids, validity = (self.proces_and_valid_batch_scan_result(
349                event["data"]["Results"], scan_rt, event["data"][KEY_RET],
350                scan_setting))
351            asserts.assert_true(bssids > 0, EMPTY_RESULT)
352            asserts.assert_true(validity, INVALID_RESULT)
353            event_name = "{}{}onFullResult".format(EVENT_TAG, idx)
354            results = self.pop_scan_result_events(event_name)
355            asserts.assert_true(
356                len(results) >= bssids,
357                "Full single shot result don't match {}".format(len(results)))
358            if 'type' in scan_setting.keys():
359                for item in results:
360                    self.verify_radio_chain_length(scan_setting['type'], item)
361        except queue.Empty as error:
362            raise AssertionError(
363                "Event did not triggered for single shot {}".format(error))
364        finally:
365            self.dut.droid.wifiScannerStopScan(idx)
366
367    def verify_radio_chain_length(self, scan_setting_type, scan_result):
368        llen = len(scan_result[0]["radioChainInfos"])
369        if scan_setting_type == wutils.WifiEnums.SCAN_TYPE_LOW_LATENCY \
370            or scan_setting_type == wutils.WifiEnums.SCAN_TYPE_LOW_POWER:
371            asserts.assert_true(llen == 1,
372                                "radioChainInfos len expected:{} "
373                                "actual:{}".format(1, llen))
374        else:
375            asserts.assert_true(llen == 2,
376                                "radioChainInfos len expected:{} "
377                                "actual:{}".format(2, llen))
378
379    def wifi_scanner_batch_scan_full(self, scan_setting):
380        """Common logic for batch scan test case for full scan result.
381
382        1. Start WifiScanner batch scan with scan_setting for full scan result.
383        2. Wait for the scan result event, wait time depend on scan settings
384           parameter.
385        3. Pop all full scan result events occurred earlier.
386        4. Verify that full scan results match with scan results.
387
388        Args:
389            scan_setting: The params for the batch scan.
390        """
391        self.dut.ed.clear_all_events()
392        data = wutils.start_wifi_background_scan(self.dut, scan_setting)
393        idx = data["Index"]
394        scan_rt = data["ScanElapsedRealtime"]
395        self.log.info("Wifi batch shot scan started with index: %s", idx)
396        #generating event wait time from scan setting plus leeway
397        scan_time, scan_channels = wutils.get_scan_time_and_channels(
398            self.wifi_chs, scan_setting, self.stime_channel)
399        # multiply scan period by two to account for scheduler changing period
400        scan_time += scan_setting[
401            'periodInMs'] * 2  #add scan period delay for next cycle
402        wait_time = scan_time / 1000 + self.leeway
403        validity = False
404        try:
405            for snumber in range(1, 3):
406                results = []
407                event_name = "%s%sonResults" % (EVENT_TAG, idx)
408                self.log.debug("Waiting for event: %s for time %s", event_name,
409                               wait_time)
410                event = self.dut.ed.pop_event(event_name, wait_time)
411                self.log.debug("Event received: %s", event)
412                bssids, validity = self.proces_and_valid_batch_scan_result(
413                    event["data"]["Results"], scan_rt, event["data"][KEY_RET],
414                    scan_setting)
415                event_name = "%s%sonFullResult" % (EVENT_TAG, idx)
416                results = self.pop_scan_result_events(event_name)
417                asserts.assert_true(
418                    len(results) >= bssids,
419                    "Full single shot result don't match %s" % len(results))
420                asserts.assert_true(bssids > 0, EMPTY_RESULT)
421                asserts.assert_true(validity, INVALID_RESULT)
422        except queue.Empty as error:
423            raise AssertionError("Event did not triggered for batch scan %s" %
424                                 error)
425        finally:
426            self.dut.droid.wifiScannerStopBackgroundScan(idx)
427            self.dut.ed.clear_all_events()
428
429    def wifi_scanner_batch_scan(self, scan_setting):
430        """Common logic for an enumerated wifi scanner batch scan test case.
431
432        1. Start WifiScanner batch scan for given scan_setting.
433        2. Wait for the scan result event, wait time depend on scan settings
434           parameter.
435        3. Verify that scan results match with scan settings parameters.
436        4. Also verify that multiple scan result events trigger.
437
438        Args:
439            scan_setting: The parameters for the batch scan.
440        """
441        data = wutils.start_wifi_background_scan(self.dut, scan_setting)
442        idx = data["Index"]
443        scan_rt = data["ScanElapsedRealtime"]
444        self.log.info(
445            "Wifi background scan started with index: %s real time %s", idx,
446            scan_rt)
447        scan_time, scan_channels = wutils.get_scan_time_and_channels(
448            self.wifi_chs, scan_setting, self.stime_channel)
449        #generating event wait time from scan setting plus leeway
450        time_cache = 0
451        number_bucket = 1  #bucket for Report result on each scan
452        check_get_result = False
453        if scan_setting[
454                'reportEvents'] == wutils.WifiEnums.REPORT_EVENT_AFTER_BUFFER_FULL:
455            check_get_result = True
456            if ('maxScansToCache' in scan_setting and
457                    scan_setting['maxScansToCache'] != 0):
458                time_cache = (scan_setting['maxScansToCache'] *
459                              scan_setting['periodInMs'])
460                number_bucket = scan_setting['maxScansToCache']
461            else:
462                time_cache = 10 * scan_setting['periodInMs'
463                                               ]  #10 as default max scan cache
464                number_bucket = 10
465        else:
466            time_cache = scan_setting[
467                'periodInMs'
468            ]  #need while waiting for seconds resutls
469        # multiply cache time by two to account for scheduler changing period
470        wait_time = (time_cache * 2 + scan_time) / 1000 + self.leeway
471        validity = False
472        try:
473            for snumber in range(1, 3):
474                event_name = "%s%sonResults" % (EVENT_TAG, idx)
475                self.log.info("Waiting for event: %s for time %s", event_name,
476                              wait_time)
477                event = self.dut.ed.pop_event(event_name, wait_time)
478                self.log.debug("Event received: %s", event)
479                results = event["data"]["Results"]
480                bssids, validity = (self.proces_and_valid_batch_scan_result(
481                    results, scan_rt, event["data"][KEY_RET], scan_setting))
482                self.log.info("Scan number: %s\n Buckets: %s\n  BSSID: %s",
483                              snumber, len(results), bssids)
484                asserts.assert_equal(
485                    len(results), number_bucket,
486                    "Test fail because number_bucket %s" % len(results))
487                asserts.assert_true(bssids >= 1, EMPTY_RESULT)
488                asserts.assert_true(validity, INVALID_RESULT)
489                if snumber % 2 == 1 and check_get_result:
490                    self.log.info("Get Scan result using GetScanResult API")
491                    time.sleep(wait_time / number_bucket)
492                    if self.dut.droid.wifiScannerGetScanResults():
493                        event = self.dut.ed.pop_event(event_name, 1)
494                        self.log.debug("Event onResults: %s", event)
495                        results = event["data"]["Results"]
496                        bssids, validity = self.proces_and_valid_batch_scan_result(
497                            results, scan_rt, event["data"][KEY_RET],
498                            scan_setting)
499                        self.log.info("Got Scan result number: %s BSSID: %s",
500                                      snumber, bssids)
501                        asserts.assert_true(bssids >= 1, EMPTY_RESULT)
502                        asserts.assert_true(validity, INVALID_RESULT)
503                    else:
504                        self.log.error("Error while fetching the scan result")
505        except queue.Empty as error:
506            raise AssertionError("Event did not triggered for batch scan %s" %
507                                 error)
508        finally:
509            self.dut.droid.wifiScannerStopBackgroundScan(idx)
510            self.dut.ed.clear_all_events()
511
512    def start_wifi_scanner_single_scan_expect_failure(self, scan_setting):
513        """Common logic to test wif scanner single scan with invalid settings
514           or environment
515
516         1. Start WifiScanner batch scan for setting parameters.
517         2. Verify that scan is not started.
518
519         Args:
520            scan_setting: The params for the single scan.
521        """
522        try:
523            idx = self.dut.droid.wifiScannerStartScan(scan_setting)
524            event = self.dut.ed.pop_event(
525                "{}{}onFailure".format(EVENT_TAG, idx), SHORT_TIMEOUT)
526        except queue.Empty as error:
527            raise AssertionError("Did not get expected onFailure {}".format(
528                error))
529
530    def start_wifi_scanner_background_scan_expect_failure(self, scan_setting):
531        """Common logic to test wif scanner batch scan with invalid settings
532           or environment
533
534         1. Start WifiScanner batch scan for setting parameters.
535         2. Verify that scan is not started.
536
537         Args:
538          scan_setting: The params for the single scan.
539        """
540        try:
541            idx = self.dut.droid.wifiScannerStartBackgroundScan(scan_setting)
542            event = self.dut.ed.pop_event(
543                "{}{}onFailure".format(EVENT_TAG, idx), SHORT_TIMEOUT)
544        except queue.Empty as error:
545            raise AssertionError("Did not get expected onFailure {}".format(
546                error))
547
548    def check_get_available_channels_with_one_band(self, band):
549        """Common logic to check available channels for a band.
550
551         1. Get available channels for band.
552         2. Verify that channels match with supported channels for band.
553
554         Args:
555            band: wifi band."""
556
557        r = self.dut.droid.wifiScannerGetAvailableChannels(band)
558        self.log.debug(band)
559        self.log.debug(r)
560        expected = self.wifi_chs.band_to_freq(band)
561        asserts.assert_equal(set(r), set(expected), "Band %s failed." % band)
562
563    def connect_to_reference_network(self):
564        """Connect to reference network and make sure that connection happen"""
565        self.dut.droid.wakeLockAcquireBright()
566        self.dut.droid.wakeUpNow()
567        try:
568            self.dut.droid.wifiConnectByConfig(self.reference_networks[0]["2g"])
569            connect_result = self.dut.ed.pop_event(
570                wifi_constants.CONNECT_BY_CONFIG_SUCCESS, SHORT_TIMEOUT)
571            self.log.info(connect_result)
572            return wutils.track_connection(self.dut,
573                self.reference_networks[0]["2g"]["SSID"], 1)
574        except Exception as error:
575            self.log.exception(traceback.format_exc())
576            self.log.error("Connection to network fail because %s", error)
577            return False
578        finally:
579            self.dut.droid.wifiLockRelease()
580            self.dut.droid.goToSleepNow()
581
582    """ Helper Functions End """
583    """ Tests Begin """
584
585    # Test channels
586    """ Test available channels for different bands.
587
588        1. Get available channels for different bands.
589        2. Verify that channels match with supported channels for respective band.
590    """
591    @test_tracker_info(uuid="7cca8142-529f-4951-ab6f-cd03b359b3cc")
592    def test_available_channels_band_1(self):
593        self.check_get_available_channels_with_one_band(1)
594
595    @test_tracker_info(uuid="612afda1-0d74-4d2f-bc37-72ef2b98310a")
596    def test_available_channels_band_2(self):
597        self.check_get_available_channels_with_one_band(2)
598
599    @test_tracker_info(uuid="a9275bb9-afa7-4dd4-b2e0-60296ffd33bb")
600    def test_available_channels_band_3(self):
601        self.check_get_available_channels_with_one_band(3)
602
603    @test_tracker_info(uuid="5413632e-ce72-4ecc-bf9b-33ac9e4bf3fc")
604    def test_available_channels_band_4(self):
605        self.check_get_available_channels_with_one_band(4)
606
607    @test_tracker_info(uuid="a8f40b4f-d79d-4d2f-bed8-3b139a082f6c")
608    def test_available_channels_band_6(self):
609        self.check_get_available_channels_with_one_band(6)
610
611    @test_tracker_info(uuid="84cdfc25-8e64-42c7-b7f9-0a04e45d78b6")
612    def test_available_channels_band_7(self):
613        self.check_get_available_channels_with_one_band(7)
614
615    @test_tracker_info(uuid="95069244-b76c-4834-b3a6-96b0d8da98d8")
616    def test_single_scan_report_each_scan_for_channels_with_enumerated_params(
617            self):
618        """Test WiFi scanner single scan for channels with enumerated settings.
619
620         1. Start WifiScanner single scan for different channels with enumerated
621            scan settings.
622         2. Verify that scan results match with respective scan settings.
623        """
624        scan_settings = self.wifi_generate_scanner_scan_settings(
625            self.run_extended_test, "channels",
626            wutils.WifiEnums.REPORT_EVENT_AFTER_EACH_SCAN)
627        self.log.debug("Scan settings: %s\n%s", len(scan_settings),
628                       scan_settings)
629        self.wifi_scanner_single_scan(scan_settings[0])
630
631    @test_tracker_info(uuid="5595ebe5-6d91-4379-a606-be59967e5ec9")
632    def test_single_scan_report_each_scan_for_band_with_enumerated_params(
633            self):
634        """Test WiFi scanner single scan for bands with enumerated settings.
635
636         1. Start WifiScanner single scan for different bands with enumerated
637            scan settings.
638         2. Verify that scan results match with respective scan settings.
639        """
640        scan_settings = self.wifi_generate_scanner_scan_settings(
641            self.run_extended_test, "band",
642            wutils.WifiEnums.REPORT_EVENT_AFTER_EACH_SCAN)
643        self.log.debug("Scan settings:%s\n%s", len(scan_settings),
644                       scan_settings)
645        self.wifi_scanner_single_scan(scan_settings[0])
646
647    @test_tracker_info(uuid="44989f93-e63b-4c2e-a90a-a483477303bb")
648    def test_batch_scan_report_buffer_full_for_channels_with_enumerated_params(
649            self):
650        """Test WiFi scanner batch scan using channels with enumerated settings
651           to report buffer full scan results.
652
653         1. Start WifiScanner batch scan using different channels with enumerated
654            scan settings to report buffer full scan results.
655         2. Verify that scan results match with respective scan settings.
656        """
657        scan_settings = self.wifi_generate_scanner_scan_settings(
658            self.run_extended_test, "channels",
659            wutils.WifiEnums.REPORT_EVENT_AFTER_BUFFER_FULL)
660        self.log.debug("Scan settings:%s\n%s", len(scan_settings),
661                       scan_settings)
662        self.wifi_scanner_batch_scan(scan_settings[0])
663
664    @test_tracker_info(uuid="63538df6-388a-4c16-964f-e9c19b750e07")
665    def test_batch_scan_report_buffer_full_for_band_with_enumerated_params(
666            self):
667        """Test WiFi scanner batch scan using band with enumerated settings
668           to report buffer full scan results.
669
670         1. Start WifiScanner batch scan using different bands with enumerated
671            scan settings to report buffer full scan results.
672         2. Verify that scan results match with respective scan settings.
673        """
674        scan_settings = self.wifi_generate_scanner_scan_settings(
675            self.run_extended_test, "band",
676            wutils.WifiEnums.REPORT_EVENT_AFTER_BUFFER_FULL)
677        self.log.debug("Scan settings:{}\n{}".format(
678            len(scan_settings), scan_settings))
679        self.wifi_scanner_batch_scan(scan_settings[0])
680
681    @test_tracker_info(uuid="bd4e8c53-16c8-4ed6-b680-55c1ba688ad8")
682    def test_batch_scan_report_each_scan_for_channels_with_enumerated_params(
683            self):
684        """Test WiFi scanner batch scan using channels with enumerated settings
685           to report each scan results.
686
687         1. Start WifiScanner batch scan using different channels with enumerated
688            scan settings to report each scan results.
689         2. Verify that scan results match with respective scan settings.
690        """
691        scan_settings = self.wifi_generate_scanner_scan_settings(
692            self.run_extended_test, "channels",
693            wutils.WifiEnums.REPORT_EVENT_AFTER_EACH_SCAN)
694        self.log.debug("Scan settings:{}\n{}".format(
695            len(scan_settings), scan_settings))
696        self.wifi_scanner_batch_scan(scan_settings[0])
697
698    @test_tracker_info(uuid="d11e8c09-97d0-49c1-bf09-b9ec672c2fa6")
699    def test_batch_scan_report_each_scan_for_band_with_enumerated_params(self):
700        """Test WiFi scanner batch scan using band with enumerated settings
701           to report each scan results.
702
703         1. Start WifiScanner batch scan using different bands with enumerated
704            scan settings to report each scan results.
705         2. Verify that scan results match with respective scan settings.
706        """
707        scan_settings = self.wifi_generate_scanner_scan_settings(
708            self.run_extended_test, "band",
709            wutils.WifiEnums.REPORT_EVENT_AFTER_EACH_SCAN)
710        self.log.debug("Scan settings:{}\n{}".format(
711            len(scan_settings), scan_settings))
712        self.wifi_scanner_batch_scan(scan_settings[0])
713
714    @test_tracker_info(uuid="7f967b0e-82fe-403e-9d74-0dee7f09a21d")
715    def test_single_scan_report_full_scan_for_channels_with_enumerated_params(
716            self):
717        """Test WiFi scanner single scan using channels with enumerated settings
718           to report full scan results.
719
720         1. Start WifiScanner single scan using different channels with enumerated
721            scan settings to report full scan results.
722         2. Verify that scan results match with respective scan settings.
723        """
724        scan_settings = self.wifi_generate_scanner_scan_settings(
725            self.run_extended_test, "channels",
726            wutils.WifiEnums.REPORT_EVENT_FULL_SCAN_RESULT)
727        self.log.debug("Full Scan settings:{}\n{}".format(
728            len(scan_settings), scan_settings))
729        self.wifi_scanner_single_scan_full(scan_settings[0])
730
731    @test_tracker_info(uuid="34d09f60-31bf-4952-8fb3-03fc93ec98fa")
732    def test_single_scan_report_full_scan_for_band_with_enumerated_params(
733            self):
734        """Test WiFi scanner single scan using band with enumerated settings
735           to report full scan results.
736
737         1. Start WifiScanner single scan using different bands with enumerated
738            scan settings to report full scan results.
739         2. Verify that scan results match with respective scan settings.
740        """
741        scan_settings = self.wifi_generate_scanner_scan_settings(
742            self.run_extended_test, "band",
743            wutils.WifiEnums.REPORT_EVENT_FULL_SCAN_RESULT)
744        self.log.debug("Full Scan settings:{}\n{}".format(
745            len(scan_settings), scan_settings))
746        self.wifi_scanner_single_scan_full(scan_settings[0])
747
748    @test_tracker_info(uuid="0ddccf2e-b518-45a7-ae75-96924070b841")
749    def test_batch_scan_report_full_scan_for_channels_with_enumerated_params(
750            self):
751        """Test WiFi scanner batch scan using channels with enumerated settings
752           to report full scan results.
753
754         1. Start WifiScanner batch scan using different channels with enumerated
755            scan settings to report full scan results.
756         2. Verify that scan results match with respective scan settings.
757        """
758        scan_settings = self.wifi_generate_scanner_scan_settings(
759            self.run_extended_test, "channels",
760            wutils.WifiEnums.REPORT_EVENT_FULL_SCAN_RESULT)
761        self.log.debug("Full Scan settings:{}\n{}".format(
762            len(scan_settings), scan_settings))
763        self.wifi_scanner_batch_scan_full(scan_settings[0])
764
765    @test_tracker_info(uuid="0685b667-8470-43a0-923d-dee71428f8ce")
766    def test_batch_scan_report_full_scan_for_band_with_enumerated_params(self):
767        """Test WiFi scanner batch scan using channels with enumerated settings
768           to report full scan results.
769
770         1. Start WifiScanner batch scan using different channels with enumerated
771            scan settings to report full scan results.
772         2. Verify that scan results match with respective scan settings.
773        """
774        scan_settings = self.wifi_generate_scanner_scan_settings(
775            self.run_extended_test, "band",
776            wutils.WifiEnums.REPORT_EVENT_FULL_SCAN_RESULT)
777        self.log.debug("Full Scan settings:{}\n{}".format(
778            len(scan_settings), scan_settings))
779        self.wifi_scanner_batch_scan_full(scan_settings[0])
780
781    @test_tracker_info(uuid="740e1c18-911a-43d2-9317-3827ecf71d3b")
782    def test_wifi_connection_while_single_scan(self):
783        """Test configuring a connection parallel to wifi scanner single scan.
784
785         1. Start WifiScanner single scan for both band with default scan settings.
786         2. Configure a connection to reference network.
787         3. Verify that connection to reference network occurred.
788         2. Verify that scanner report single scan results.
789        """
790        self.attenuators[ATTENUATOR].set_atten(0)
791        data = wutils.start_wifi_single_scan(self.dut,
792                                             self.default_scan_setting)
793        idx = data["Index"]
794        scan_rt = data["ScanElapsedRealtime"]
795        self.log.info("Wifi single shot scan started with index: {}".format(
796            idx))
797        asserts.assert_true(self.connect_to_reference_network(), NETWORK_ERROR)
798        time.sleep(10)  #wait for connection to be active
799        asserts.assert_true(
800            wutils.validate_connection(self.dut, self.ping_addr),
801            "Error, No internet connection for current network")
802        #generating event wait time from scan setting plus leeway
803        scan_time, scan_channels = wutils.get_scan_time_and_channels(
804            self.wifi_chs, self.default_scan_setting, self.stime_channel)
805        wait_time = int(scan_time / 1000) + self.leeway
806        validity = False
807        try:
808            event_name = "{}{}onResults".format(EVENT_TAG, idx)
809            self.log.debug("Waiting for event: {} for time {}".format(
810                event_name, wait_time))
811            event = self.dut.ed.pop_event(event_name, wait_time)
812            self.log.debug("Event received: {}".format(event))
813            results = event["data"]["Results"]
814            bssids, validity = self.proces_and_valid_batch_scan_result(
815                results, scan_rt, event["data"][KEY_RET],
816                self.default_scan_setting)
817            self.log.info("Scan number Buckets: {}\nTotal BSSID: {}".format(
818                len(results), bssids))
819            asserts.assert_true(
820                len(results) == 1 and bssids >= 1, EMPTY_RESULT)
821        except queue.Empty as error:
822            raise AssertionError(
823                "Event did not triggered for single scan {}".format(error))
824
825    @test_tracker_info(uuid="e9a7cfb5-21c4-4c40-8169-8d88b65a1dee")
826    def test_single_scan_while_pno(self):
827        """Test wifi scanner single scan parallel to PNO connection.
828
829         1. Check device have a saved network.
830         2. Trigger PNO by attenuate the signal to move out of range.
831         3. Start WifiScanner single scan for both band with default scan settings.
832         4. Verify that scanner report single scan results.
833         5. Attenuate the signal to move in range.
834         6. Verify connection occurred through PNO.
835        """
836        self.log.info("Check connection through PNO for reference network")
837        current_network = self.dut.droid.wifiGetConnectionInfo()
838        self.log.info("Current network: {}".format(current_network))
839        asserts.assert_true('network_id' in current_network, NETWORK_ID_ERROR)
840        asserts.assert_true(current_network['network_id'] >= 0, NETWORK_ERROR)
841        self.log.info("Kicking PNO for reference network")
842        self.attenuators[ATTENUATOR].set_atten(90)
843        time.sleep(10)  #wait for PNO to be kicked
844        self.log.info("Starting single scan while PNO")
845        self.wifi_scanner_single_scan(self.default_scan_setting)
846        self.attenuators[ATTENUATOR].set_atten(0)
847        self.log.info("Check connection through PNO for reference network")
848        time.sleep(30)  #wait for connection through PNO
849        current_network = self.dut.droid.wifiGetConnectionInfo()
850        self.log.info("Current network: {}".format(current_network))
851        asserts.assert_true('network_id' in current_network, NETWORK_ID_ERROR)
852        asserts.assert_true(current_network['network_id'] >= 0, NETWORK_ERROR)
853        time.sleep(10)  #wait for IP to be assigned
854        asserts.assert_true(
855            wutils.validate_connection(self.dut, self.ping_addr),
856            "Error, No internet connection for current network")
857        wutils.wifi_forget_network(self.dut,
858            self.reference_networks[0]["2g"]["SSID"])
859
860    @test_tracker_info(uuid="fc18d947-0b5a-42b4-98f3-dd1f2b52a7af")
861    def test_wifi_connection_and_pno_while_batch_scan(self):
862        """Test configuring a connection and PNO connection parallel to wifi
863           scanner batch scan.
864
865         1. Start WifiScanner batch scan with default batch scan settings.
866         2. Wait for scan result event for a time depend on scan settings.
867         3. Verify reported batch scan results.
868         4. Configure a connection to reference network.
869         5. Verify that connection to reference network occurred.
870         6. Wait for scan result event for a time depend on scan settings.
871         7. Verify reported batch scan results.
872         8. Trigger PNO by attenuate the signal to move out of range.
873         9. Wait for scan result event for a time depend on scan settings.
874         10. Verify reported batch scan results.
875         11. Attenuate the signal to move in range.
876         12. Verify connection occurred through PNO.
877        """
878        self.attenuators[ATTENUATOR].set_atten(0)
879        data = wutils.start_wifi_background_scan(
880            self.dut, self.default_batch_scan_setting)
881        idx = data["Index"]
882        scan_rt = data["ScanElapsedRealtime"]
883        self.log.info(
884            "Wifi background scan started with index: {} rt {}".format(
885                idx, scan_rt))
886        #generating event wait time from scan setting plus leeway
887        scan_time, scan_channels = wutils.get_scan_time_and_channels(
888            self.wifi_chs, self.default_batch_scan_setting, self.stime_channel)
889        #default number buckets
890        number_bucket = 10
891        time_cache = self.default_batch_scan_setting[
892            'periodInMs'] * number_bucket  #default cache
893        #add 2 seconds extra time for switch between the channel for connection scan
894        #multiply cache time by two to account for scheduler changing period
895        wait_time = (time_cache * 2 + scan_time) / 1000 + self.leeway + 2
896        result_flag = 0
897        try:
898            for snumber in range(1, 7):
899                event_name = "{}{}onResults".format(EVENT_TAG, idx)
900                self.log.info("Waiting for event: {}".format(event_name))
901                event = self.dut.ed.pop_event(event_name, wait_time)
902                self.log.debug("Event onResults: {}".format(event))
903                results = event["data"]["Results"]
904                bssids, validity = self.proces_and_valid_batch_scan_result(
905                    results, scan_rt, event["data"][KEY_RET],
906                    self.default_batch_scan_setting)
907                self.log.info(
908                    "Scan number: {}\n Buckets: {}\n BSSID: {}".format(
909                        snumber, len(results), bssids))
910                asserts.assert_true(bssids >= 1,
911                                    "Not able to fetch scan result")
912                if snumber == 1:
913                    self.log.info(
914                        "Try to connect AP while waiting for event: {}".format(
915                            event_name))
916                    asserts.assert_true(self.connect_to_reference_network(),
917                                        NETWORK_ERROR)
918                    time.sleep(10)  #wait for connection to be active
919                    asserts.assert_true(
920                        wutils.validate_connection(self.dut, self.ping_addr),
921                        "Error, No internet connection for current network")
922                elif snumber == 3:
923                    self.log.info("Kicking PNO for reference network")
924                    self.attenuators[ATTENUATOR].set_atten(90)
925                elif snumber == 4:
926                    self.log.info("Bring back device for PNO connection")
927                    current_network = self.dut.droid.wifiGetConnectionInfo()
928                    self.log.info("Current network: {}".format(
929                        current_network))
930                    asserts.assert_true('network_id' in current_network,
931                                        NETWORK_ID_ERROR)
932                    asserts.assert_true(
933                        current_network['network_id'] == -1,
934                        "Device is still connected to network  {}".format(
935                            current_network[wutils.WifiEnums.SSID_KEY]))
936                    self.attenuators[ATTENUATOR].set_atten(0)
937                    time.sleep(
938                        10
939                    )  #wait for connection to take place before waiting for scan result
940                elif snumber == 6:
941                    self.log.info(
942                        "Check connection through PNO for reference network")
943                    current_network = self.dut.droid.wifiGetConnectionInfo()
944                    self.log.info("Current network: {}".format(
945                        current_network))
946                    asserts.assert_true('network_id' in current_network,
947                                        NETWORK_ID_ERROR)
948                    asserts.assert_true(current_network['network_id'] >= 0,
949                                        NETWORK_ERROR)
950                    time.sleep(10)  #wait for connection to be active
951                    asserts.assert_true(
952                        wutils.validate_connection(self.dut, self.ping_addr),
953                        "Error, No internet connection for current network")
954                    wutils.wifi_forget_network(self.dut,
955                        self.reference_networks[0]["2g"]["SSID"])
956        except queue.Empty as error:
957            raise AssertionError(
958                "Event did not triggered for batch scan {}".format(error))
959        finally:
960            self.dut.droid.wifiScannerStopBackgroundScan(idx)
961            self.dut.ed.clear_all_events()
962
963    @test_tracker_info(uuid="7c25ce32-0fae-4a68-a7cb-fdf6d4d03caf")
964    def test_wifi_scanner_single_scan_channel_sanity(self):
965        """Test WiFi scanner single scan for mix channel with default setting
966           parameters.
967
968         1. Start WifiScanner single scan for mix channels with default setting
969            parameters.
970         2. Verify that scan results match with respective scan settings.
971        """
972        scan_setting = {"channels": self.wifi_chs.MIX_CHANNEL_SCAN,
973                        "periodInMs": SCANTIME,
974                        "reportEvents":
975                        wutils.WifiEnums.REPORT_EVENT_AFTER_EACH_SCAN}
976        self.wifi_scanner_single_scan(scan_setting)
977
978    @test_tracker_info(uuid="7c8da0c4-dec7-4d04-abd4-f8ea467a5c6d")
979    def test_wifi_scanner_dual_radio_low_latency(self):
980        """Test WiFi scanner single scan for mix channel with default setting
981           parameters.
982
983         1. Start WifiScanner single scan for type = SCAN_TYPE_LOW_LATENCY.
984         2. Verify that scan results match with respective scan settings.
985        """
986        if self.dut.model not in self.dbs_supported_models:
987            asserts.skip(
988                ("Device %s does not support dual radio scanning.")
989                % self.dut.model)
990        scan_setting = {"channels": self.wifi_chs.MIX_CHANNEL_SCAN,
991                        "periodInMs": SCANTIME,
992                        "reportEvents":
993                            wutils.WifiEnums.REPORT_EVENT_FULL_SCAN_RESULT,
994                        "type": wutils.WifiEnums.SCAN_TYPE_LOW_LATENCY}
995        self.wifi_scanner_single_scan_full(scan_setting)
996
997    @test_tracker_info(uuid="58b49b01-851b-4e45-b218-9fd27c0be921")
998    def test_wifi_scanner_dual_radio_low_power(self):
999        """Test WiFi scanner single scan for mix channel with default setting
1000           parameters.
1001
1002         1. Start WifiScanner single scan for type = SCAN_TYPE_LOW_POWER.
1003         2. Verify that scan results match with respective scan settings.
1004        """
1005        if self.dut.model not in self.dbs_supported_models:
1006            asserts.skip(
1007                ("Device %s does not support dual radio scanning.")
1008                % self.dut.model)
1009        scan_setting = {"channels": self.wifi_chs.MIX_CHANNEL_SCAN,
1010                        "periodInMs": SCANTIME,
1011                        "reportEvents":
1012                            wutils.WifiEnums.REPORT_EVENT_FULL_SCAN_RESULT,
1013                        "type": wutils.WifiEnums.SCAN_TYPE_LOW_POWER}
1014        self.wifi_scanner_single_scan_full(scan_setting)
1015
1016    @test_tracker_info(uuid="3e7288bc-45e4-497c-bf3a-977eec4e896e")
1017    def test_wifi_scanner_dual_radio_high_accuracy(self):
1018        """Test WiFi scanner single scan for mix channel with default setting
1019           parameters.
1020
1021         1. Start WifiScanner single scan for type = SCAN_TYPE_HIGH_ACCURACY.
1022         2. Verify that scan results match with respective scan settings.
1023        """
1024        if self.dut.model not in self.dbs_supported_models:
1025            asserts.skip(
1026                ("Device %s does not support dual radio scanning.")
1027                % self.dut.model)
1028        scan_setting = {"channels": self.wifi_chs.MIX_CHANNEL_SCAN,
1029                        "periodInMs": SCANTIME,
1030                        "reportEvents":
1031                            wutils.WifiEnums.REPORT_EVENT_FULL_SCAN_RESULT,
1032                        "type": wutils.WifiEnums.SCAN_TYPE_HIGH_ACCURACY}
1033        self.wifi_scanner_single_scan_full(scan_setting)
1034
1035    @test_tracker_info(uuid="e9f3aaad-4af3-4c54-9829-65dc1d6d4987")
1036    def test_wifi_scanner_batch_scan_channel_sanity(self):
1037        """Test WiFi scanner batch scan for mix channel with default setting
1038           parameters to report the result on buffer full.
1039
1040         1. Start WifiScanner batch scan for mix channels with default setting
1041            parameters.
1042         2. Verify that scan results match with respective scan settings.
1043        """
1044        scan_setting = {"channels": self.wifi_chs.MIX_CHANNEL_SCAN,
1045                        "periodInMs": SCANTIME,
1046                        "reportEvents":
1047                        wutils.WifiEnums.REPORT_EVENT_AFTER_BUFFER_FULL}
1048        self.wifi_scanner_batch_scan(scan_setting)
1049
1050    @test_tracker_info(uuid="49ba245a-52e2-4c9b-90ad-a2fbc97e3d9f")
1051    def test_wifi_scanner_batch_scan_period_too_short(self):
1052        """Test WiFi scanner batch scan for band with too short period time.
1053
1054         1. Start WifiScanner batch scan for both band with interval period as 5s.
1055         2. Verify that scan is not started."""
1056        scan_setting = {"band": wutils.WifiEnums.WIFI_BAND_BOTH_WITH_DFS,
1057                        "periodInMs": 5000,
1058                        "reportEvents":
1059                        wutils.WifiEnums.REPORT_EVENT_AFTER_BUFFER_FULL}
1060        self.start_wifi_scanner_background_scan_expect_failure(scan_setting)
1061
1062    @test_tracker_info(uuid="6fe45cd7-4fac-4ddd-a950-b9431e68f735")
1063    def test_wifi_scanner_single_scan_in_isolated(self):
1064        """Test WiFi scanner in isolated environment with default scan settings.
1065
1066         1. Created isolated environment by attenuating the single by 90db
1067         2. Start WifiScanner single scan for mix channels with default setting
1068            parameters.
1069         3. Verify that empty scan results reported.
1070        """
1071        self.attenuators[0].set_atten(90)
1072        self.attenuators[1].set_atten(90)
1073        data = wutils.start_wifi_single_scan(self.dut,
1074                                             self.default_scan_setting)
1075        idx = data["Index"]
1076        scan_rt = data["ScanElapsedRealtime"]
1077        self.log.info("Wifi single shot scan started with index: {}".format(
1078            idx))
1079        results = []
1080        #generating event wait time from scan setting plus leeway
1081        scan_time, scan_channels = wutils.get_scan_time_and_channels(
1082            self.wifi_chs, self.default_scan_setting, self.stime_channel)
1083        wait_time = int(scan_time / 1000) + self.leeway
1084        try:
1085            event_name = "{}{}onResults".format(EVENT_TAG, idx)
1086            self.log.debug("Waiting for event: {} for time {}".format(
1087                event_name, wait_time))
1088            event = self.dut.ed.pop_event(event_name, wait_time)
1089            self.log.debug("Event received: {}".format(event))
1090            results = event["data"]["Results"]
1091            for batch in results:
1092                asserts.assert_false(batch["ScanResults"],
1093                                     "Test fail because report scan "
1094                                     "results reported are not empty")
1095        except queue.Empty as error:
1096            raise AssertionError(
1097                "Event did not triggered for in isolated environment {}".format(
1098                    error))
1099        finally:
1100            self.dut.ed.clear_all_events()
1101            self.attenuators[0].set_atten(0)
1102            self.attenuators[1].set_atten(0)
1103
1104    @test_tracker_info(uuid="46f817b9-97a3-455e-af2c-56f9aea64f7e")
1105    def test_wifi_scanner_with_wifi_off(self):
1106        """Test WiFi scanner single scan when wifi is off.
1107
1108         1. Toggle wifi state to off.
1109         2. Start WifiScanner single scan for both band with default scan settings.
1110         3. Verify that scan is not started.
1111        """
1112        self.log.debug("Make sure wifi is off.")
1113        wutils.wifi_toggle_state(self.dut, False)
1114        self.start_wifi_scanner_single_scan_expect_failure(
1115            self.default_scan_setting)
1116        self.log.debug("Turning wifi back on.")
1117        wutils.wifi_toggle_state(self.dut, True)
1118
1119    @test_tracker_info(uuid="257ad734-c21f-49f4-b448-3986b70eba3d")
1120    def test_wifi_scanner_with_invalid_numBssidsPerScan(self):
1121        """Test WiFi scanner single scan with invalid number of bssids reported
1122           per scan.
1123
1124         1. Start WifiScanner single scan with invalid number of bssids reported
1125            per scan.
1126         2. Verify that scan results triggered for default supported number of
1127            bssids per scan.
1128        """
1129        scan_setting = {
1130            "band": wutils.WifiEnums.WIFI_BAND_BOTH_WITH_DFS,
1131            "periodInMs": SCANTIME,
1132            "reportEvents": wutils.WifiEnums.REPORT_EVENT_AFTER_EACH_SCAN,
1133            'numBssidsPerScan': 33
1134        }
1135        self.wifi_scanner_single_scan(scan_setting)
1136
1137    """ Tests End """
1138