def wireless_station_get_wlan_ip_addr():
    wifi_station = CM.get_station_instance()
    function_name = sys._getframe().f_code.co_name

    BTN.log(message="%s %s" % (MODULE_NAME, function_name), level="DEBUG")
    addr = wifi_station.get_addresses()
    ip_addr = addr["IP"]
    return ip_addr
def station_renew_and_verify_ip(sta_eth_ip,
                                sta_http_port,
                                is_allow=True,
                                check_timeout=120):
    """
        Renew wifi station ip address and verify it is correct.
    
        == Argument: ==
        - _sta_eth_ip_ : station ethernet ip address.
        - _sta_http_port_ : station http port.
        - _is_allow_ : allow get ip address or not. default is true.
        - _check_timeout_ : timeout for waiting get correct ip address. default is 120.
    
        == Return Value: ==
        - None
    
        == Example: ==
        | *Action* | *Argument* | *Argument* | *Argument* | *Argument* |
        | _Station Renew and Verify IP_ | 192.168.1.101 | 8888 | ${true} | ${240} |    
    
    """
    wifi_station = CM.get_station_instance()
    wifi_station.set_target(sta_eth_ip, sta_http_port)
    wifi_station.renew_wifi_ip_address()

    is_ipv4_correct = False
    sta_wifi_ip_addr = None
    start_time = time.time()
    while time.time() - start_time < check_timeout:
        sta_addr_dict = wifi_station.get_addresses()
        sta_wifi_ip_addr = sta_addr_dict['IP']
        logging.debug("Get station wifi IP address %s" % sta_wifi_ip_addr)

        ptn = '(\d{1,3}\.){3}\d{1,3}$'
        matcher = re.compile(ptn, re.I).match(sta_wifi_ip_addr)
        if matcher:
            if not (sta_wifi_ip_addr == '0.0.0.0'
                    or sta_wifi_ip_addr.startswith('169.254')):
                logging.debug("Station wifi IP address %s is correct" %
                              sta_wifi_ip_addr)
                is_ipv4_correct = True
                break

        time.sleep(5)

    logging.debug("Verify station wifi ip address, expect:%s, actual ip:%s" %
                  (is_allow, sta_wifi_ip_addr))
    if is_allow != is_ipv4_correct:
        if is_allow == True:
            raise AssertionError("Didn't get wifi station IP correctly: %s" %
                                 sta_wifi_ip_addr)
        else:
            raise AssertionError(
                "Get wifi station IP correctly expect is fail:%s" %
                sta_wifi_ip_addr)
    else:
        return sta_wifi_ip_addr
def wireless_station_restart_iperf_server(test_udp=False,
                                          tradeoff=False,
                                          compatibility=False):
    wifi_station = CM.get_station_instance()
    function_name = sys._getframe().f_code.co_name

    BTN.log(message="%s %s" % (MODULE_NAME, function_name), level="info")
    wifi_station.client_stop_iperf()
    wifi_station.client_start_iperf(test_udp=test_udp,
                                    packet_len=800,
                                    timeout=60)
def wireless_station_disconnect_wlan(check_status_timeout=90, retry=3):
    wifi_station = CM.get_station_instance()
    function_name = sys._getframe().f_code.co_name
    tested_retry = retry
    result = "fail"

    while (retry >= 0):
        try:
            wifi_station.disconnect_wlan()

            start_time = time.time()
            while True:
                status = wifi_station.get_wlan_status()
                if status == "disconnected":
                    result = "pass"
                    break

                time.sleep(1)
                if time.time() - start_time > check_status_timeout:
                    if retry > 0:
                        continue
                    else:
                        raise Exception(
                            "After %s retry, the station did not disconnect from wireless network within %d seconds"
                            % (tested_retry, check_status_timeout))

            if result == "pass":
                msg = "WiFi station disconnects from the wireless network successfully"
                BTN.log(message="%s %s" % (MODULE_NAME, function_name) + ' ' +
                        msg,
                        level="DEBUG")
                break
            else:
                retry -= 1
        except Exception, ex:
            retry -= 1
            if retry < 0:
                raise Exception("After %s retry for failed, exception:%s" %
                                (tested_retry, ex.message))
                break
            else:
                continue
def wireless_station_stop_iperf_server():
    wifi_station = CM.get_station_instance()
    function_name = sys._getframe().f_code.co_name

    BTN.log(message="%s %s" % (MODULE_NAME, function_name), level="info")
    wifi_station.client_stop_iperf()
def wireless_station_associate_wlan(wlan_cfg,
                                    check_status_timeout=90,
                                    retry=3,
                                    apcli_context_name=''):
    """
    Configure wireless station to associate WLAN. Please see
    RWWindowsTestAppliance.config_wlan to see the configuration detail.

    == Argument: ==
    - _wlan_cfg_ : A dictionary value of the configuration of WLAN profile
    - _check_status_timeout_: A integer value of associate WLAN idle timeout, default is 90 seconds.
    - _retry_: A integer value of retry if cannot get wireless station WiFi IP address, default is 3 times.

    == Return Value: ==
    - None

    == Example: ==
    | *Setting* | *Value*                                                          |
    | Resource  | R${RootTarget}/resources/keywords/qa/Windows_Basic_Keywords.html |
    
    | *Action*                          | *Argument*        | *Argument*   | *Argument* | *Argument*   |
    | ${cfg}=                           | Create Dictionary | ssid=rw-open | auth=OPEN  | encrypt=NONE |
    | _Wireless station associate WLAN_ | ${cfg}            |              |            |              |
    """
    function_name = sys._getframe().f_code.co_name
    BTN.log(message="%s %s" % (MODULE_NAME, function_name), level="DEBUG")
    wifi_station = CM.get_station_instance()
    ssid = wlan_cfg['ssid']
    result = "fail"
    tested_retry = retry
    try:
        apcli = CM.get_apcli_instance(context_name=apcli_context_name)
    except Exception:
        pass

    while (retry >= 0):
        try:
            start_time = time.time()
            wifi_station.config_wlan(wlan_cfg)
            wifi_station.connect_wlan(ssid)
            status = wifi_station.get_wlan_status()
            while (status != "connected"):
                time.sleep(3)
                current_time = time.time()
                status = wifi_station.get_wlan_status()
                if current_time - start_time > check_status_timeout:
                    if retry > 0:
                        break
                    else:
                        raise Exception(
                            "After %s retry, WiFi station cannot connect SSID: %s within %s seconds"
                            % (tested_retry, ssid, check_status_timeout))
                else:
                    continue

            if (status == "connected"):
                # wait 15 seconds for IP address
                for zz in RU.try_interval(15):
                    ipaddres = wifi_station.get_addresses()
                    ip = ipaddres["IP"]
                    ts_pattern = "((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d)(\.((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d)){3}"
                    res = re.search(ts_pattern, ip)
                    if res and res.group(0).find('169.254') != 0:
                        BTN.log(message="%s %s" %
                                (MODULE_NAME, function_name) +
                                " get IP: %s" % res.group(0),
                                level="DEBUG")
                        result = "pass"
                        break

            if result == "pass":
                break
            else:
                if retry >= 0:
                    retry -= 1

                if apcli:
                    wlan_list = apcli.get_wlan_list_with_ssid()
                    wlans = wifi_station.scan_wlans()
                    BTN.log(
                        message="%s %s" % (MODULE_NAME, function_name) +
                        " failed in %s run, currently WLAN list in AP CLI: %s, scanned WLANs in station: %s"
                        % (tested_retry - retry, json.dumps(
                            wlan_list, indent=1), json.dumps(wlans, indent=1)),
                        level="INFO")

                if retry < 0:
                    raise Exception(
                        "After %s retry for failed, wireless station cannot associate AP"
                        % (tested_retry))
                    break
                else:
                    remove_all_wlan_from_wireless_station(
                        check_status_timeout=check_status_timeout, retry=retry)
                    continue

        except Exception, ex:
            if retry >= 0:
                retry -= 1

            if apcli:
                wlan_list = apcli.get_wlan_list_with_ssid()
                wlans = wifi_station.scan_wlans()
                BTN.log(
                    message="%s %s" % (MODULE_NAME, function_name) +
                    " failed in %s run, currently WLAN list in AP CLI: %s, scanned WLANs in station: %s"
                    % (tested_retry - retry, json.dumps(
                        wlan_list, indent=1), json.dumps(wlans, indent=1)),
                    level="INFO")

            if retry < 0:
                raise Exception(
                    "After %s retry for failed in %s, exception:%s" %
                    (tested_retry, function_name, ex.message))
                break
            else:
                remove_all_wlan_from_wireless_station(
                    check_status_timeout=check_status_timeout, retry=retry)
                continue
def remove_all_wlan_from_wireless_station(check_status_timeout=60, retry=3):
    """
    Remove all WLAN from wireless station. Please see
    RWWindowsTestAppliance.remove_all_wlan_profiles to see the configuration detail.

    == Argument: ==
    - _check_status_timeout_: A integer value of check wireless station disconnected status idle timeout, default is 60 seconds.
    - _retry_: A integer value of retry if cannot remove all WLAN from wireless station, default is 3 times.

    == Return Value: ==
    - None

    == Example: ==    
    | *Setting* | *Value*                                                          |
    | Resource  | R${RootTarget}/resources/keywords/qa/Windows_Basic_Keywords.html |    
    
    | *Action*                                |
    | _Remove all WLAN from wireless station_ |
    """

    wifi_station = CM.get_station_instance()
    function_name = sys._getframe().f_code.co_name
    tested_retry = retry

    BTN.log(message="%s %s" % (MODULE_NAME, function_name), level="DEBUG")
    result = "fail"

    while (retry >= 0):
        try:
            wifi_station.remove_all_wlan_profiles()
            wifi_station.disconnect_wlan()

            start_time = time.time()
            while True:
                status = wifi_station.get_wlan_status()
                if status == "disconnected":
                    result = "pass"
                    break

                time.sleep(1)
                if time.time() - start_time > check_status_timeout:
                    if retry > 0:
                        continue
                    else:
                        raise Exception(
                            "After %s retry, the station did not disconnect from wireless network within %d seconds"
                            % (tested_retry, check_status_timeout))

            if result == "pass":
                msg = "Remove all WLAN profiles from the station and make sure it disconnects from the wireless network successfully"
                BTN.log(message="%s %s" % (MODULE_NAME, function_name) + ' ' +
                        msg,
                        level="DEBUG")
                break
            else:
                retry -= 1
        except Exception, ex:
            retry -= 1
            if retry < 0:
                raise Exception("After %s retry for failed, exception:%s" %
                                (tested_retry, ex.message))
                break
            else:
                continue