• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2#
3#   Copyright 2021 - Google
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 time
18from acts import signals
19from acts_contrib.test_utils.tel.tel_defines import CAPABILITY_VOLTE
20from acts_contrib.test_utils.tel.tel_defines import CAPABILITY_WFC
21from acts_contrib.test_utils.tel.tel_defines import CARRIER_FRE
22from acts_contrib.test_utils.tel.tel_defines import CARRIER_TMO
23from acts_contrib.test_utils.tel.tel_defines import CARRIER_VZW
24from acts_contrib.test_utils.tel.tel_defines import GEN_2G
25from acts_contrib.test_utils.tel.tel_defines import GEN_3G
26from acts_contrib.test_utils.tel.tel_defines import GEN_4G
27from acts_contrib.test_utils.tel.tel_defines import GEN_5G
28from acts_contrib.test_utils.tel.tel_defines import INVALID_SUB_ID
29from acts_contrib.test_utils.tel.tel_defines import MAX_WAIT_TIME_CALL_DROP
30from acts_contrib.test_utils.tel.tel_defines import MAX_WAIT_TIME_NW_SELECTION
31from acts_contrib.test_utils.tel.tel_defines import MAX_WAIT_TIME_VOLTE_ENABLED
32from acts_contrib.test_utils.tel.tel_defines import MAX_WAIT_TIME_WFC_ENABLED
33from acts_contrib.test_utils.tel.tel_defines import NETWORK_SERVICE_DATA
34from acts_contrib.test_utils.tel.tel_defines import NETWORK_SERVICE_VOICE
35from acts_contrib.test_utils.tel.tel_defines import NETWORK_MODE_CDMA
36from acts_contrib.test_utils.tel.tel_defines import NETWORK_MODE_GSM_ONLY
37from acts_contrib.test_utils.tel.tel_defines import NETWORK_MODE_GSM_UMTS
38from acts_contrib.test_utils.tel.tel_defines import NETWORK_MODE_LTE_CDMA_EVDO
39from acts_contrib.test_utils.tel.tel_defines import NETWORK_MODE_LTE_GSM_WCDMA
40from acts_contrib.test_utils.tel.tel_defines import NETWORK_MODE_LTE_ONLY
41from acts_contrib.test_utils.tel.tel_defines import RAT_1XRTT
42from acts_contrib.test_utils.tel.tel_defines import RAT_5G
43from acts_contrib.test_utils.tel.tel_defines import RAT_FAMILY_CDMA2000
44from acts_contrib.test_utils.tel.tel_defines import RAT_FAMILY_LTE
45from acts_contrib.test_utils.tel.tel_defines import RAT_FAMILY_GSM
46from acts_contrib.test_utils.tel.tel_defines import RAT_FAMILY_WCDMA
47from acts_contrib.test_utils.tel.tel_defines import RAT_FAMILY_WLAN
48from acts_contrib.test_utils.tel.tel_defines import RAT_UNKNOWN
49from acts_contrib.test_utils.tel.tel_defines import TELEPHONY_STATE_IDLE
50from acts_contrib.test_utils.tel.tel_defines import WAIT_TIME_1XRTT_VOICE_ATTACH
51from acts_contrib.test_utils.tel.tel_defines import WAIT_TIME_ANDROID_STATE_SETTLING
52from acts_contrib.test_utils.tel.tel_defines import WFC_MODE_DISABLED
53from acts_contrib.test_utils.tel.tel_defines import WFC_MODE_CELLULAR_PREFERRED
54from acts_contrib.test_utils.tel.tel_5g_utils import is_current_network_5g
55from acts_contrib.test_utils.tel.tel_ims_utils import toggle_volte
56from acts_contrib.test_utils.tel.tel_ims_utils import toggle_volte_for_subscription
57from acts_contrib.test_utils.tel.tel_ims_utils import set_wfc_mode
58from acts_contrib.test_utils.tel.tel_ims_utils import set_wfc_mode_for_subscription
59from acts_contrib.test_utils.tel.tel_ims_utils import wait_for_enhanced_4g_lte_setting
60from acts_contrib.test_utils.tel.tel_ims_utils import wait_for_volte_enabled
61from acts_contrib.test_utils.tel.tel_ims_utils import wait_for_wfc_enabled
62from acts_contrib.test_utils.tel.tel_ims_utils import wait_for_wfc_disabled
63from acts_contrib.test_utils.tel.tel_lookup_tables import network_preference_for_generation
64from acts_contrib.test_utils.tel.tel_lookup_tables import rat_families_for_network_preference
65from acts_contrib.test_utils.tel.tel_lookup_tables import rat_family_for_generation
66from acts_contrib.test_utils.tel.tel_lookup_tables import rat_family_from_rat
67from acts_contrib.test_utils.tel.tel_lookup_tables import rat_generation_from_rat
68from acts_contrib.test_utils.tel.tel_subscription_utils import get_outgoing_message_sub_id
69from acts_contrib.test_utils.tel.tel_subscription_utils import get_outgoing_voice_sub_id
70from acts_contrib.test_utils.tel.tel_subscription_utils import get_subid_from_slot_index
71from acts_contrib.test_utils.tel.tel_subscription_utils import get_default_data_sub_id
72from acts_contrib.test_utils.tel.tel_subscription_utils import set_default_sub_for_all_services
73from acts_contrib.test_utils.tel.tel_test_utils import _is_attached
74from acts_contrib.test_utils.tel.tel_test_utils import _is_attached_for_subscription
75from acts_contrib.test_utils.tel.tel_test_utils import _wait_for_droid_in_state
76from acts_contrib.test_utils.tel.tel_test_utils import _wait_for_droid_in_state_for_subscription
77from acts_contrib.test_utils.tel.tel_test_utils import get_capability_for_subscription
78from acts_contrib.test_utils.tel.tel_test_utils import get_cell_data_roaming_state_by_adb
79from acts_contrib.test_utils.tel.tel_test_utils import get_network_rat_for_subscription
80from acts_contrib.test_utils.tel.tel_test_utils import get_operator_name
81from acts_contrib.test_utils.tel.tel_test_utils import get_telephony_signal_strength
82from acts_contrib.test_utils.tel.tel_test_utils import is_droid_in_network_generation_for_subscription
83from acts_contrib.test_utils.tel.tel_test_utils import is_droid_in_rat_family_for_subscription
84from acts_contrib.test_utils.tel.tel_test_utils import is_droid_in_rat_family_list_for_subscription
85from acts_contrib.test_utils.tel.tel_test_utils import reset_preferred_network_type_to_allowable_range
86from acts_contrib.test_utils.tel.tel_test_utils import set_cell_data_roaming_state_by_adb
87from acts_contrib.test_utils.tel.tel_test_utils import set_preferred_network_mode_pref
88from acts_contrib.test_utils.tel.tel_test_utils import toggle_airplane_mode
89from acts_contrib.test_utils.tel.tel_test_utils import toggle_airplane_mode_by_adb
90from acts_contrib.test_utils.tel.tel_test_utils import wait_for_data_attach_for_subscription
91from acts_contrib.test_utils.tel.tel_wifi_utils import ensure_wifi_connected
92from acts_contrib.test_utils.tel.tel_wifi_utils import set_wifi_to_default
93from acts.libs.utils.multithread import multithread_func
94
95
96def phone_setup_iwlan(log,
97                      ad,
98                      is_airplane_mode,
99                      wfc_mode,
100                      wifi_ssid=None,
101                      wifi_pwd=None,
102                      nw_gen=None,
103                      nr_type=None):
104    """Phone setup function for epdg call test.
105    Set WFC mode according to wfc_mode.
106    Set airplane mode according to is_airplane_mode.
107    Make sure phone connect to WiFi. (If wifi_ssid is not None.)
108    Wait for phone to be in iwlan data network type.
109    Wait for phone to report wfc enabled flag to be true.
110    Args:
111        log: Log object.
112        ad: Android device object.
113        is_airplane_mode: True to turn on airplane mode. False to turn off airplane mode.
114        wfc_mode: WFC mode to set to.
115        wifi_ssid: WiFi network SSID. This is optional.
116            If wifi_ssid is None, then phone_setup_iwlan will not attempt to connect to wifi.
117        wifi_pwd: WiFi network password. This is optional.
118        nw_gen: network type selection. This is optional.
119            GEN_4G for 4G, GEN_5G for 5G or None for doing nothing.
120        nr_type: NR network type
121    Returns:
122        True if success. False if fail.
123    """
124    return phone_setup_iwlan_for_subscription(log, ad,
125                                              get_outgoing_voice_sub_id(ad),
126                                              is_airplane_mode, wfc_mode,
127                                              wifi_ssid, wifi_pwd, nw_gen, nr_type)
128
129
130def phone_setup_iwlan_for_subscription(log,
131                                       ad,
132                                       sub_id,
133                                       is_airplane_mode,
134                                       wfc_mode,
135                                       wifi_ssid=None,
136                                       wifi_pwd=None,
137                                       nw_gen=None,
138                                       nr_type=None):
139    """Phone setup function for epdg call test for subscription id.
140    Enable VoLTE. (b/235019060#comment20)
141    Set WFC mode according to wfc_mode.
142    Set airplane mode according to is_airplane_mode.
143    Make sure phone connect to WiFi. (If wifi_ssid is not None.)
144    Wait for phone to be in iwlan data network type.
145    Wait for phone to report wfc enabled flag to be true.
146    Args:
147        log: Log object.
148        ad: Android device object.
149        sub_id: subscription id.
150        is_airplane_mode: True to turn on airplane mode. False to turn off airplane mode.
151        wfc_mode: WFC mode to set to.
152        wifi_ssid: WiFi network SSID. This is optional.
153            If wifi_ssid is None, then phone_setup_iwlan will not attempt to connect to wifi.
154        wifi_pwd: WiFi network password. This is optional.
155        nw_gen: network type selection. This is optional.
156            GEN_4G for 4G, GEN_5G for 5G or None for doing nothing.
157        nr_type: NR network type
158    Returns:
159        True if success. False if fail.
160    """
161    if not get_capability_for_subscription(ad, CAPABILITY_WFC, sub_id):
162        ad.log.error("WFC is not supported, abort test.")
163        raise signals.TestSkip("WFC is not supported, abort test.")
164
165    if nw_gen:
166        if not ensure_network_generation_for_subscription(
167                log, ad, sub_id, nw_gen, voice_or_data=NETWORK_SERVICE_DATA,
168                nr_type=nr_type):
169            ad.log.error("Failed to set to %s data.", nw_gen)
170            return False
171    toggle_volte_for_subscription(log, ad, sub_id, True)
172    toggle_airplane_mode(log, ad, is_airplane_mode, strict_checking=False)
173
174    # Pause at least for 4 seconds is necessary after airplane mode was turned
175    # on due to the mechanism of deferring Wi-Fi (b/191481736)
176    if is_airplane_mode:
177        time.sleep(5)
178
179    # check if WFC supported phones
180    if wfc_mode != WFC_MODE_DISABLED and not ad.droid.imsIsWfcEnabledByPlatform(
181    ):
182        ad.log.error("WFC is not enabled on this device by checking "
183                     "ImsManager.isWfcEnabledByPlatform")
184        return False
185    if wifi_ssid is not None:
186        if not ensure_wifi_connected(log, ad, wifi_ssid, wifi_pwd, apm=is_airplane_mode):
187            ad.log.error("Fail to bring up WiFi connection on %s.", wifi_ssid)
188            return False
189    else:
190        ad.log.info("WiFi network SSID not specified, available user "
191                    "parameters are: wifi_network_ssid, wifi_network_ssid_2g, "
192                    "wifi_network_ssid_5g")
193    if not set_wfc_mode_for_subscription(ad, wfc_mode, sub_id):
194        ad.log.error("Unable to set WFC mode to %s.", wfc_mode)
195        return False
196
197    if wfc_mode != WFC_MODE_DISABLED:
198        if not wait_for_wfc_enabled(log, ad, max_time=MAX_WAIT_TIME_WFC_ENABLED):
199            ad.log.error("WFC is not enabled")
200            return False
201
202    return True
203
204
205def phone_setup_iwlan_cellular_preferred(log,
206                                         ad,
207                                         wifi_ssid=None,
208                                         wifi_pwd=None):
209    """Phone setup function for iwlan Non-APM CELLULAR_PREFERRED test.
210    Set WFC mode according to CELLULAR_PREFERRED.
211    Set airplane mode according to False.
212    Make sure phone connect to WiFi. (If wifi_ssid is not None.)
213    Make sure phone don't report iwlan data network type.
214    Make sure phone don't report wfc enabled flag to be true.
215
216    Args:
217        log: Log object.
218        ad: Android device object.
219        wifi_ssid: WiFi network SSID. This is optional.
220            If wifi_ssid is None, then phone_setup_iwlan will not attempt to connect to wifi.
221        wifi_pwd: WiFi network password. This is optional.
222
223    Returns:
224        True if success. False if fail.
225    """
226    toggle_airplane_mode(log, ad, False, strict_checking=False)
227    try:
228        toggle_volte(log, ad, True)
229        if not wait_for_network_generation(
230                log, ad, GEN_4G, voice_or_data=NETWORK_SERVICE_DATA):
231            if not ensure_network_generation(
232                    log, ad, GEN_4G, voice_or_data=NETWORK_SERVICE_DATA):
233                ad.log.error("Fail to ensure data in 4G")
234                return False
235    except Exception as e:
236        ad.log.error(e)
237        ad.droid.telephonyToggleDataConnection(True)
238    if wifi_ssid is not None:
239        if not ensure_wifi_connected(log, ad, wifi_ssid, wifi_pwd):
240            ad.log.error("Connect to WiFi failed.")
241            return False
242    if not set_wfc_mode(log, ad, WFC_MODE_CELLULAR_PREFERRED):
243        ad.log.error("Set WFC mode failed.")
244        return False
245    if not wait_for_not_network_rat(
246            log, ad, RAT_FAMILY_WLAN, voice_or_data=NETWORK_SERVICE_DATA):
247        ad.log.error("Data rat in iwlan mode.")
248        return False
249    elif not wait_for_wfc_disabled(log, ad, MAX_WAIT_TIME_WFC_ENABLED):
250        ad.log.error("Should report wifi calling disabled within %s.",
251                     MAX_WAIT_TIME_WFC_ENABLED)
252        return False
253    return True
254
255
256def phone_setup_data_for_subscription(log, ad, sub_id, network_generation,
257                                        nr_type=None):
258    """Setup Phone <sub_id> Data to <network_generation>
259
260    Args:
261        log: log object
262        ad: android device object
263        sub_id: subscription id
264        network_generation: network generation, e.g. GEN_2G, GEN_3G, GEN_4G, GEN_5G
265        nr_type: NR network type e.g. NSA, SA, MMWAVE
266
267    Returns:
268        True if success, False if fail.
269    """
270    toggle_airplane_mode(log, ad, False, strict_checking=False)
271    set_wifi_to_default(log, ad)
272    if not set_wfc_mode(log, ad, WFC_MODE_DISABLED):
273        ad.log.error("Disable WFC failed.")
274        return False
275    if not ensure_network_generation_for_subscription(
276            log,
277            ad,
278            sub_id,
279            network_generation,
280            voice_or_data=NETWORK_SERVICE_DATA,
281            nr_type=nr_type):
282        get_telephony_signal_strength(ad)
283        return False
284    return True
285
286
287def phone_setup_5g(log, ad, nr_type=None):
288    """Setup Phone default data sub_id data to 5G.
289
290    Args:
291        log: log object
292        ad: android device object
293
294    Returns:
295        True if success, False if fail.
296    """
297    return phone_setup_5g_for_subscription(log, ad,
298                                           get_default_data_sub_id(ad), nr_type=nr_type)
299
300
301def phone_setup_5g_for_subscription(log, ad, sub_id, nr_type=None):
302    """Setup Phone <sub_id> Data to 5G.
303
304    Args:
305        log: log object
306        ad: android device object
307        sub_id: subscription id
308        nr_type: NR network type e.g. NSA, SA, MMWAVE
309
310    Returns:
311        True if success, False if fail.
312    """
313    return phone_setup_data_for_subscription(log, ad, sub_id, GEN_5G,
314                                        nr_type=nr_type)
315
316
317def phone_setup_4g(log, ad):
318    """Setup Phone default data sub_id data to 4G.
319
320    Args:
321        log: log object
322        ad: android device object
323
324    Returns:
325        True if success, False if fail.
326    """
327    return phone_setup_4g_for_subscription(log, ad,
328                                           get_default_data_sub_id(ad))
329
330
331def phone_setup_4g_for_subscription(log, ad, sub_id):
332    """Setup Phone <sub_id> Data to 4G.
333
334    Args:
335        log: log object
336        ad: android device object
337        sub_id: subscription id
338
339    Returns:
340        True if success, False if fail.
341    """
342    return phone_setup_data_for_subscription(log, ad, sub_id, GEN_4G)
343
344
345def phone_setup_3g(log, ad):
346    """Setup Phone default data sub_id data to 3G.
347
348    Args:
349        log: log object
350        ad: android device object
351
352    Returns:
353        True if success, False if fail.
354    """
355    return phone_setup_3g_for_subscription(log, ad,
356                                           get_default_data_sub_id(ad))
357
358
359def phone_setup_3g_for_subscription(log, ad, sub_id):
360    """Setup Phone <sub_id> Data to 3G.
361
362    Args:
363        log: log object
364        ad: android device object
365        sub_id: subscription id
366
367    Returns:
368        True if success, False if fail.
369    """
370    return phone_setup_data_for_subscription(log, ad, sub_id, GEN_3G)
371
372
373def phone_setup_2g(log, ad):
374    """Setup Phone default data sub_id data to 2G.
375
376    Args:
377        log: log object
378        ad: android device object
379
380    Returns:
381        True if success, False if fail.
382    """
383    return phone_setup_2g_for_subscription(log, ad,
384                                           get_default_data_sub_id(ad))
385
386
387def phone_setup_2g_for_subscription(log, ad, sub_id):
388    """Setup Phone <sub_id> Data to 3G.
389
390    Args:
391        log: log object
392        ad: android device object
393        sub_id: subscription id
394
395    Returns:
396        True if success, False if fail.
397    """
398    return phone_setup_data_for_subscription(log, ad, sub_id, GEN_2G)
399
400
401def phone_setup_csfb(log, ad, nw_gen=GEN_4G, nr_type=None):
402    """Setup phone for CSFB call test.
403
404    Setup Phone to be in 4G mode.
405    Disabled VoLTE.
406
407    Args:
408        log: log object
409        ad: Android device object.
410        nw_gen: GEN_4G or GEN_5G
411
412    Returns:
413        True if setup successfully.
414        False for errors.
415    """
416    return phone_setup_csfb_for_subscription(log, ad,
417                                        get_outgoing_voice_sub_id(ad), nw_gen, nr_type=nr_type)
418
419
420def phone_setup_csfb_for_subscription(log, ad, sub_id, nw_gen=GEN_4G, nr_type=None):
421    """Setup phone for CSFB call test for subscription id.
422
423    Setup Phone to be in 4G mode.
424    Disabled VoLTE.
425
426    Args:
427        log: log object
428        ad: Android device object.
429        sub_id: subscription id.
430        nw_gen: GEN_4G or GEN_5G
431        nr_type: NR network type e.g. NSA, SA, MMWAVE
432
433    Returns:
434        True if setup successfully.
435        False for errors.
436    """
437    capabilities = ad.telephony["subscription"][sub_id].get("capabilities", [])
438    if capabilities:
439        if "hide_enhanced_4g_lte" in capabilities:
440            show_enhanced_4g_lte_mode = getattr(ad, "show_enhanced_4g_lte_mode", False)
441            if show_enhanced_4g_lte_mode in ["false", "False", False]:
442                ad.log.warning("'VoLTE' option is hidden. Test will be skipped.")
443                raise signals.TestSkip("'VoLTE' option is hidden. Test will be skipped.")
444
445    if nw_gen == GEN_4G:
446        if not phone_setup_4g_for_subscription(log, ad, sub_id):
447            ad.log.error("Failed to set to 4G data.")
448            return False
449    elif nw_gen == GEN_5G:
450        if not phone_setup_5g_for_subscription(log, ad, sub_id, nr_type=nr_type):
451            ad.log.error("Failed to set to 5G data.")
452            return False
453
454    if ad.telephony["subscription"][sub_id]["operator"] != CARRIER_VZW \
455            and ad.telephony["subscription"][sub_id]["operator"] != CARRIER_TMO :
456        if not toggle_volte_for_subscription(log, ad, sub_id, False):
457            return False
458
459    if not wait_for_voice_attach_for_subscription(log, ad, sub_id,
460                                                  MAX_WAIT_TIME_NW_SELECTION):
461        return False
462
463    return phone_idle_csfb_for_subscription(log, ad, sub_id, nw_gen)
464
465
466def phone_setup_volte(log, ad, nw_gen=GEN_4G, nr_type=None):
467    """Setup VoLTE enable.
468
469    Args:
470        log: log object
471        ad: android device object.
472        nw_gen: GEN_4G or GEN_5G
473
474    Returns:
475        True: if VoLTE is enabled successfully.
476        False: for errors
477    """
478    if not get_capability_for_subscription(ad, CAPABILITY_VOLTE,
479        get_outgoing_voice_sub_id(ad)):
480        ad.log.error("VoLTE is not supported, abort test.")
481        raise signals.TestSkip("VoLTE is not supported, abort test.")
482    return phone_setup_volte_for_subscription(log, ad,
483                        get_outgoing_voice_sub_id(ad), nw_gen, nr_type= nr_type)
484
485
486def phone_setup_volte_for_subscription(log, ad, sub_id, nw_gen=GEN_4G,
487                                        nr_type=None):
488    """Setup VoLTE enable for subscription id.
489    Args:
490        log: log object
491        ad: android device object.
492        sub_id: subscription id.
493        nw_gen: GEN_4G or GEN_5G.
494        nr_type: NR network type.
495
496    Returns:
497        True: if VoLTE is enabled successfully.
498        False: for errors
499    """
500    if not get_capability_for_subscription(ad, CAPABILITY_VOLTE,
501        get_outgoing_voice_sub_id(ad)):
502        ad.log.error("VoLTE is not supported, abort test.")
503        raise signals.TestSkip("VoLTE is not supported, abort test.")
504
505    if nw_gen == GEN_4G:
506        if not phone_setup_4g_for_subscription(log, ad, sub_id):
507            ad.log.error("Failed to set to 4G data.")
508            return False
509    elif nw_gen == GEN_5G:
510        if not phone_setup_5g_for_subscription(log, ad, sub_id,
511                                        nr_type=nr_type):
512            ad.log.error("Failed to set to 5G data.")
513            return False
514    operator_name = get_operator_name(log, ad, sub_id)
515    if not wait_for_enhanced_4g_lte_setting(log, ad, sub_id):
516        ad.log.error("Enhanced 4G LTE setting is not available")
517        return False
518    toggle_volte_for_subscription(log, ad, sub_id, True)
519    return phone_idle_volte_for_subscription(log, ad, sub_id, nw_gen,
520                                        nr_type=nr_type)
521
522
523def phone_setup_voice_3g(log, ad):
524    """Setup phone voice to 3G.
525
526    Args:
527        log: log object
528        ad: Android device object.
529
530    Returns:
531        True if setup successfully.
532        False for errors.
533    """
534    return phone_setup_voice_3g_for_subscription(log, ad,
535                                                 get_outgoing_voice_sub_id(ad))
536
537
538def phone_setup_voice_3g_for_subscription(log, ad, sub_id):
539    """Setup phone voice to 3G for subscription id.
540
541    Args:
542        log: log object
543        ad: Android device object.
544        sub_id: subscription id.
545
546    Returns:
547        True if setup successfully.
548        False for errors.
549    """
550    if not phone_setup_3g_for_subscription(log, ad, sub_id):
551        ad.log.error("Failed to set to 3G data.")
552        return False
553    if not wait_for_voice_attach_for_subscription(log, ad, sub_id,
554                                                  MAX_WAIT_TIME_NW_SELECTION):
555        return False
556    return phone_idle_3g_for_subscription(log, ad, sub_id)
557
558
559def phone_setup_voice_2g(log, ad):
560    """Setup phone voice to 2G.
561
562    Args:
563        log: log object
564        ad: Android device object.
565
566    Returns:
567        True if setup successfully.
568        False for errors.
569    """
570    return phone_setup_voice_2g_for_subscription(log, ad,
571                                                 get_outgoing_voice_sub_id(ad))
572
573
574def phone_setup_voice_2g_for_subscription(log, ad, sub_id):
575    """Setup phone voice to 2G for subscription id.
576
577    Args:
578        log: log object
579        ad: Android device object.
580        sub_id: subscription id.
581
582    Returns:
583        True if setup successfully.
584        False for errors.
585    """
586    if not phone_setup_2g_for_subscription(log, ad, sub_id):
587        ad.log.error("Failed to set to 2G data.")
588        return False
589    if not wait_for_voice_attach_for_subscription(log, ad, sub_id,
590                                                  MAX_WAIT_TIME_NW_SELECTION):
591        return False
592    return phone_idle_2g_for_subscription(log, ad, sub_id)
593
594
595def phone_setup_voice_general(log, ad):
596    """Setup phone for voice general call test.
597
598    Make sure phone attached to voice.
599    Make necessary delay.
600
601    Args:
602        ad: Android device object.
603
604    Returns:
605        True if setup successfully.
606        False for errors.
607    """
608    return phone_setup_voice_general_for_subscription(
609        log, ad, get_outgoing_voice_sub_id(ad))
610
611
612def phone_setup_voice_general_for_slot(log,ad,slot_id):
613    return phone_setup_voice_general_for_subscription(
614        log, ad, get_subid_from_slot_index(log,ad,slot_id))
615
616
617def phone_setup_voice_general_for_subscription(log, ad, sub_id):
618    """Setup phone for voice general call test for subscription id.
619
620    Make sure phone attached to voice.
621    Make necessary delay.
622
623    Args:
624        ad: Android device object.
625        sub_id: subscription id.
626
627    Returns:
628        True if setup successfully.
629        False for errors.
630    """
631    toggle_airplane_mode(log, ad, False, strict_checking=False)
632    if not wait_for_voice_attach_for_subscription(log, ad, sub_id,
633                                                  MAX_WAIT_TIME_NW_SELECTION):
634        # if phone can not attach voice, try phone_setup_voice_3g
635        return phone_setup_voice_3g_for_subscription(log, ad, sub_id)
636    return True
637
638
639def phone_setup_data_general(log, ad):
640    """Setup phone for data general test.
641
642    Make sure phone attached to data.
643    Make necessary delay.
644
645    Args:
646        ad: Android device object.
647
648    Returns:
649        True if setup successfully.
650        False for errors.
651    """
652    return phone_setup_data_general_for_subscription(
653        log, ad, ad.droid.subscriptionGetDefaultDataSubId())
654
655
656def phone_setup_data_general_for_subscription(log, ad, sub_id):
657    """Setup phone for data general test for subscription id.
658
659    Make sure phone attached to data.
660    Make necessary delay.
661
662    Args:
663        ad: Android device object.
664        sub_id: subscription id.
665
666    Returns:
667        True if setup successfully.
668        False for errors.
669    """
670    toggle_airplane_mode(log, ad, False, strict_checking=False)
671    if not wait_for_data_attach_for_subscription(log, ad, sub_id,
672                                                 MAX_WAIT_TIME_NW_SELECTION):
673        # if phone can not attach data, try reset network preference settings
674        reset_preferred_network_type_to_allowable_range(log, ad)
675
676    return wait_for_data_attach_for_subscription(log, ad, sub_id,
677                                                 MAX_WAIT_TIME_NW_SELECTION)
678
679
680def phone_setup_rat_for_subscription(log, ad, sub_id, network_preference,
681                                     rat_family):
682    toggle_airplane_mode(log, ad, False, strict_checking=False)
683    set_wifi_to_default(log, ad)
684    if not set_wfc_mode(log, ad, WFC_MODE_DISABLED):
685        ad.log.error("Disable WFC failed.")
686        return False
687    return ensure_network_rat_for_subscription(log, ad, sub_id,
688                                               network_preference, rat_family)
689
690
691def phone_setup_lte_gsm_wcdma(log, ad):
692    return phone_setup_lte_gsm_wcdma_for_subscription(
693        log, ad, ad.droid.subscriptionGetDefaultSubId())
694
695
696def phone_setup_lte_gsm_wcdma_for_subscription(log, ad, sub_id):
697    return phone_setup_rat_for_subscription(
698        log, ad, sub_id, NETWORK_MODE_LTE_GSM_WCDMA, RAT_FAMILY_LTE)
699
700
701def phone_setup_gsm_umts(log, ad):
702    return phone_setup_gsm_umts_for_subscription(
703        log, ad, ad.droid.subscriptionGetDefaultSubId())
704
705
706def phone_setup_gsm_umts_for_subscription(log, ad, sub_id):
707    return phone_setup_rat_for_subscription(
708        log, ad, sub_id, NETWORK_MODE_GSM_UMTS, RAT_FAMILY_WCDMA)
709
710
711def phone_setup_gsm_only(log, ad):
712    return phone_setup_gsm_only_for_subscription(
713        log, ad, ad.droid.subscriptionGetDefaultSubId())
714
715
716def phone_setup_gsm_only_for_subscription(log, ad, sub_id):
717    return phone_setup_rat_for_subscription(
718        log, ad, sub_id, NETWORK_MODE_GSM_ONLY, RAT_FAMILY_GSM)
719
720
721def phone_setup_lte_cdma_evdo(log, ad):
722    return phone_setup_lte_cdma_evdo_for_subscription(
723        log, ad, ad.droid.subscriptionGetDefaultSubId())
724
725
726def phone_setup_lte_cdma_evdo_for_subscription(log, ad, sub_id):
727    return phone_setup_rat_for_subscription(
728        log, ad, sub_id, NETWORK_MODE_LTE_CDMA_EVDO, RAT_FAMILY_LTE)
729
730
731def phone_setup_cdma(log, ad):
732    return phone_setup_cdma_for_subscription(
733        log, ad, ad.droid.subscriptionGetDefaultSubId())
734
735
736def phone_setup_cdma_for_subscription(log, ad, sub_id):
737    return phone_setup_rat_for_subscription(log, ad, sub_id, NETWORK_MODE_CDMA,
738                                            RAT_FAMILY_CDMA2000)
739
740
741def phone_idle_volte(log, ad):
742    """Return if phone is idle for VoLTE call test.
743
744    Args:
745        ad: Android device object.
746    """
747    return phone_idle_volte_for_subscription(log, ad,
748                                             get_outgoing_voice_sub_id(ad))
749
750
751def phone_idle_volte_for_subscription(log, ad, sub_id, nw_gen=GEN_4G,
752                                    nr_type=None):
753    """Return if phone is idle for VoLTE call test for subscription id.
754    Args:
755        ad: Android device object.
756        sub_id: subscription id.
757        nw_gen: GEN_4G or GEN_5G.
758        nr_type: NR network type e.g. NSA, SA, MMWAVE
759    """
760    if nw_gen == GEN_5G:
761        if not is_current_network_5g(ad, sub_id=sub_id, nr_type=nr_type):
762            ad.log.error("Not in 5G coverage.")
763            return False
764    else:
765        if not wait_for_network_rat_for_subscription(
766                log, ad, sub_id, RAT_FAMILY_LTE,
767                voice_or_data=NETWORK_SERVICE_VOICE):
768            ad.log.error("Voice rat not in LTE mode.")
769            return False
770    if not wait_for_volte_enabled(log, ad, MAX_WAIT_TIME_VOLTE_ENABLED, sub_id):
771        ad.log.error(
772            "Failed to <report volte enabled true> within %s seconds.",
773            MAX_WAIT_TIME_VOLTE_ENABLED)
774        return False
775    return True
776
777
778def phone_idle_iwlan(log, ad):
779    """Return if phone is idle for WiFi calling call test.
780
781    Args:
782        ad: Android device object.
783    """
784    return phone_idle_iwlan_for_subscription(log, ad,
785                                             get_outgoing_voice_sub_id(ad))
786
787
788def phone_idle_iwlan_for_subscription(log, ad, sub_id):
789    """Return if phone is idle for WiFi calling call test for subscription id.
790
791    Args:
792        ad: Android device object.
793        sub_id: subscription id.
794    """
795    if not wait_for_wfc_enabled(log, ad, MAX_WAIT_TIME_WFC_ENABLED):
796        ad.log.error("Failed to <report wfc enabled true> within %s seconds.",
797                     MAX_WAIT_TIME_WFC_ENABLED)
798        return False
799    return True
800
801
802def phone_idle_not_iwlan(log, ad):
803    """Return if phone is idle for non WiFi calling call test.
804
805    Args:
806        ad: Android device object.
807    """
808    return phone_idle_not_iwlan_for_subscription(log, ad,
809                                                 get_outgoing_voice_sub_id(ad))
810
811
812def phone_idle_not_iwlan_for_subscription(log, ad, sub_id):
813    """Return if phone is idle for non WiFi calling call test for sub id.
814
815    Args:
816        ad: Android device object.
817        sub_id: subscription id.
818    """
819    if not wait_for_not_network_rat_for_subscription(
820            log, ad, sub_id, RAT_FAMILY_WLAN,
821            voice_or_data=NETWORK_SERVICE_DATA):
822        log.error("{} data rat in iwlan mode.".format(ad.serial))
823        return False
824    return True
825
826
827def phone_idle_csfb(log, ad):
828    """Return if phone is idle for CSFB call test.
829
830    Args:
831        ad: Android device object.
832    """
833    return phone_idle_csfb_for_subscription(log, ad,
834                                            get_outgoing_voice_sub_id(ad))
835
836
837def phone_idle_csfb_for_subscription(log, ad, sub_id, nw_gen=GEN_4G, nr_type=None):
838    """Return if phone is idle for CSFB call test for subscription id.
839
840    Args:
841        ad: Android device object.
842        sub_id: subscription id.
843        nw_gen: GEN_4G or GEN_5G
844    """
845    if nw_gen == GEN_5G:
846        if not is_current_network_5g(ad, sub_id=sub_id, nr_type=nr_type):
847            ad.log.error("Not in 5G coverage.")
848            return False
849    else:
850        if not wait_for_network_rat_for_subscription(
851                log, ad, sub_id, RAT_FAMILY_LTE,
852                voice_or_data=NETWORK_SERVICE_DATA):
853            ad.log.error("Data rat not in lte mode.")
854            return False
855    return True
856
857
858def phone_idle_3g(log, ad):
859    """Return if phone is idle for 3G call test.
860
861    Args:
862        ad: Android device object.
863    """
864    return phone_idle_3g_for_subscription(log, ad,
865                                          get_outgoing_voice_sub_id(ad))
866
867
868def phone_idle_3g_for_subscription(log, ad, sub_id):
869    """Return if phone is idle for 3G call test for subscription id.
870
871    Args:
872        ad: Android device object.
873        sub_id: subscription id.
874    """
875    return wait_for_network_generation_for_subscription(
876        log, ad, sub_id, GEN_3G, voice_or_data=NETWORK_SERVICE_VOICE)
877
878
879def phone_idle_2g(log, ad):
880    """Return if phone is idle for 2G call test.
881
882    Args:
883        ad: Android device object.
884    """
885    return phone_idle_2g_for_subscription(log, ad,
886                                          get_outgoing_voice_sub_id(ad))
887
888
889def phone_idle_2g_for_subscription(log, ad, sub_id):
890    """Return if phone is idle for 2G call test for subscription id.
891
892    Args:
893        ad: Android device object.
894        sub_id: subscription id.
895    """
896    return wait_for_network_generation_for_subscription(
897        log, ad, sub_id, GEN_2G, voice_or_data=NETWORK_SERVICE_VOICE)
898
899
900def phone_setup_on_rat(
901    log,
902    ad,
903    rat='volte',
904    sub_id=None,
905    is_airplane_mode=False,
906    wfc_mode=None,
907    wifi_ssid=None,
908    wifi_pwd=None,
909    only_return_fn=None,
910    sub_id_type='voice',
911    nr_type='nsa'):
912
913    if sub_id is None:
914        if sub_id_type == 'sms':
915            sub_id = get_outgoing_message_sub_id(ad)
916        else:
917            sub_id = get_outgoing_voice_sub_id(ad)
918
919    if get_default_data_sub_id(ad) != sub_id and '5g' in rat.lower():
920        ad.log.warning('Default data sub ID is NOT given sub ID %s.', sub_id)
921        network_preference = network_preference_for_generation(
922            GEN_5G,
923            ad.telephony["subscription"][sub_id]["operator"],
924            ad.telephony["subscription"][sub_id]["phone_type"])
925
926        ad.log.info("Network preference for %s is %s", GEN_5G,
927                    network_preference)
928
929        if not set_preferred_network_mode_pref(log, ad, sub_id,
930            network_preference):
931            return False
932
933        if not wait_for_network_generation_for_subscription(
934            log,
935            ad,
936            sub_id,
937            GEN_5G,
938            max_wait_time=30,
939            voice_or_data=NETWORK_SERVICE_DATA,
940            nr_type=nr_type):
941
942            ad.log.warning('Non-DDS slot (sub ID: %s) cannot attach 5G network.', sub_id)
943            ad.log.info('Check if sub ID %s can attach LTE network.', sub_id)
944
945            if not wait_for_network_generation_for_subscription(
946                log,
947                ad,
948                sub_id,
949                GEN_4G,
950                voice_or_data=NETWORK_SERVICE_DATA):
951                return False
952
953            if "volte" in rat.lower():
954                phone_setup_volte_for_subscription(log, ad, sub_id, None)
955            elif "wfc" in rat.lower():
956                return phone_setup_iwlan_for_subscription(
957                    log,
958                    ad,
959                    sub_id,
960                    is_airplane_mode,
961                    wfc_mode,
962                    wifi_ssid,
963                    wifi_pwd)
964            elif "csfb" in rat.lower():
965                return phone_setup_csfb_for_subscription(log, ad, sub_id, None)
966            return True
967
968    if rat.lower() == '5g_volte':
969        if only_return_fn:
970            return phone_setup_volte_for_subscription
971        else:
972            return phone_setup_volte_for_subscription(log, ad, sub_id, GEN_5G, nr_type='nsa')
973
974    elif rat.lower() == '5g_nsa_mmw_volte':
975        if only_return_fn:
976            return phone_setup_volte_for_subscription
977        else:
978            return phone_setup_volte_for_subscription(log, ad, sub_id, GEN_5G,
979                                                    nr_type='mmwave')
980
981    elif rat.lower() == '5g_csfb':
982        if only_return_fn:
983            return phone_setup_csfb_for_subscription
984        else:
985            return phone_setup_csfb_for_subscription(log, ad, sub_id, GEN_5G, nr_type='nsa')
986
987    elif rat.lower() == '5g_wfc':
988        if only_return_fn:
989            return phone_setup_iwlan_for_subscription
990        else:
991            return phone_setup_iwlan_for_subscription(
992                log,
993                ad,
994                sub_id,
995                is_airplane_mode,
996                wfc_mode,
997                wifi_ssid,
998                wifi_pwd,
999                GEN_5G,
1000                nr_type='nsa')
1001
1002    elif rat.lower() == '5g_nsa_mmw_wfc':
1003        if only_return_fn:
1004            return phone_setup_iwlan_for_subscription
1005        else:
1006            return phone_setup_iwlan_for_subscription(
1007                log,
1008                ad,
1009                sub_id,
1010                is_airplane_mode,
1011                wfc_mode,
1012                wifi_ssid,
1013                wifi_pwd,
1014                GEN_5G,
1015                nr_type='mmwave')
1016
1017    elif rat.lower() == 'volte':
1018        if only_return_fn:
1019            return phone_setup_volte_for_subscription
1020        else:
1021            return phone_setup_volte_for_subscription(log, ad, sub_id)
1022
1023    elif rat.lower() == 'csfb':
1024        if only_return_fn:
1025            return phone_setup_csfb_for_subscription
1026        else:
1027            return phone_setup_csfb_for_subscription(log, ad, sub_id)
1028
1029    elif rat.lower() == '5g':
1030        if only_return_fn:
1031            return phone_setup_5g_for_subscription
1032        else:
1033            return phone_setup_5g_for_subscription(log, ad, sub_id, nr_type='nsa')
1034
1035    elif rat.lower() == '5g_nsa_mmwave':
1036        if only_return_fn:
1037            return phone_setup_5g_for_subscription
1038        else:
1039            return phone_setup_5g_for_subscription(log, ad, sub_id,
1040                                            nr_type='mmwave')
1041
1042    elif rat.lower() == '3g':
1043        if only_return_fn:
1044            return phone_setup_voice_3g_for_subscription
1045        else:
1046            return phone_setup_voice_3g_for_subscription(log, ad, sub_id)
1047
1048    elif rat.lower() == '2g':
1049        if only_return_fn:
1050            return phone_setup_voice_2g_for_subscription
1051        else:
1052            return phone_setup_voice_2g_for_subscription(log, ad, sub_id)
1053
1054    elif rat.lower() == 'wfc':
1055        if only_return_fn:
1056            return phone_setup_iwlan_for_subscription
1057        else:
1058            return phone_setup_iwlan_for_subscription(
1059                log,
1060                ad,
1061                sub_id,
1062                is_airplane_mode,
1063                wfc_mode,
1064                wifi_ssid,
1065                wifi_pwd)
1066    elif rat.lower() == 'default':
1067        if only_return_fn:
1068            return ensure_phone_default_state
1069        else:
1070            return ensure_phone_default_state(log, ad)
1071    else:
1072        if only_return_fn:
1073            return phone_setup_voice_general_for_subscription
1074        else:
1075            return phone_setup_voice_general_for_subscription(log, ad, sub_id)
1076
1077
1078def wait_for_network_idle(
1079    log,
1080    ad,
1081    rat,
1082    sub_id,
1083    nr_type='nsa'):
1084    """Wait for attaching to network with assigned RAT and IMS/WFC registration
1085
1086    This function can be used right after network service recovery after turning
1087    off airplane mode or switching DDS. It will ensure DUT has attached to the
1088    network with assigned RAT, and VoLTE/WFC has been ready.
1089
1090    Args:
1091        log: log object
1092        ad: Android object
1093        rat: following RAT are supported:
1094            - 5g
1095            - 5g_volte
1096            - 5g_csfb
1097            - 5g_wfc
1098            - 4g (LTE)
1099            - volte (LTE)
1100            - csfb (LTE)
1101            - wfc (LTE)
1102
1103    Returns:
1104        True or False
1105    """
1106    if get_default_data_sub_id(ad) != sub_id and '5g' in rat.lower():
1107        ad.log.warning('Default data sub ID is NOT given sub ID %s.', sub_id)
1108        network_preference = network_preference_for_generation(
1109            GEN_5G,
1110            ad.telephony["subscription"][sub_id]["operator"],
1111            ad.telephony["subscription"][sub_id]["phone_type"])
1112
1113        ad.log.info("Network preference for %s is %s", GEN_5G,
1114                    network_preference)
1115
1116        if not set_preferred_network_mode_pref(log, ad, sub_id,
1117            network_preference):
1118            return False
1119
1120        if not wait_for_network_generation_for_subscription(
1121            log,
1122            ad,
1123            sub_id,
1124            GEN_5G,
1125            max_wait_time=30,
1126            voice_or_data=NETWORK_SERVICE_DATA,
1127            nr_type=nr_type):
1128
1129            ad.log.warning('Non-DDS slot (sub ID: %s) cannot attach 5G network.', sub_id)
1130            ad.log.info('Check if sub ID %s can attach LTE network.', sub_id)
1131
1132            if not wait_for_network_generation_for_subscription(
1133                log,
1134                ad,
1135                sub_id,
1136                GEN_4G,
1137                voice_or_data=NETWORK_SERVICE_DATA):
1138                return False
1139
1140            if rat.lower() == '5g':
1141                rat = '4g'
1142            elif rat.lower() == '5g_volte':
1143                rat = 'volte'
1144            elif rat.lower() == '5g_wfc':
1145                rat = 'wfc'
1146            elif rat.lower() == '5g_csfb':
1147                rat = 'csfb'
1148
1149    if rat.lower() == '5g_volte':
1150        if not phone_idle_volte_for_subscription(log, ad, sub_id, GEN_5G, nr_type=nr_type):
1151            return False
1152    elif rat.lower() == '5g_csfb':
1153        if not phone_idle_csfb_for_subscription(log, ad, sub_id, GEN_5G, nr_type=nr_type):
1154            return False
1155    elif rat.lower() == '5g_wfc':
1156        if not wait_for_network_generation_for_subscription(
1157            log,
1158            ad,
1159            sub_id,
1160            GEN_5G,
1161            voice_or_data=NETWORK_SERVICE_DATA,
1162            nr_type=nr_type):
1163            return False
1164        if not wait_for_wfc_enabled(log, ad):
1165            return False
1166    elif rat.lower() == '5g':
1167        if not wait_for_network_generation_for_subscription(
1168            log,
1169            ad,
1170            sub_id,
1171            GEN_5G,
1172            voice_or_data=NETWORK_SERVICE_DATA,
1173            nr_type=nr_type):
1174            return False
1175    elif rat.lower() == 'volte':
1176        if not phone_idle_volte_for_subscription(log, ad, sub_id, GEN_4G):
1177            return False
1178    elif rat.lower() == 'csfb':
1179        if not phone_idle_csfb_for_subscription(log, ad, sub_id, GEN_4G):
1180            return False
1181    elif rat.lower() == 'wfc':
1182        if not wait_for_network_generation_for_subscription(
1183            log,
1184            ad,
1185            sub_id,
1186            GEN_4G,
1187            voice_or_data=NETWORK_SERVICE_DATA):
1188            return False
1189        if not wait_for_wfc_enabled(log, ad):
1190            return False
1191    elif rat.lower() == '4g':
1192        if not wait_for_network_generation_for_subscription(
1193            log,
1194            ad,
1195            sub_id,
1196            GEN_4G,
1197            voice_or_data=NETWORK_SERVICE_DATA):
1198            return False
1199    return True
1200
1201
1202def ensure_preferred_network_type_for_subscription(
1203        ad,
1204        network_preference
1205        ):
1206    sub_id = ad.droid.subscriptionGetDefaultSubId()
1207    if not ad.droid.telephonySetPreferredNetworkTypesForSubscription(
1208            network_preference, sub_id):
1209        ad.log.error("Set sub_id %s Preferred Networks Type %s failed.",
1210                     sub_id, network_preference)
1211    return True
1212
1213
1214def ensure_network_rat(log,
1215                       ad,
1216                       network_preference,
1217                       rat_family,
1218                       voice_or_data=None,
1219                       max_wait_time=MAX_WAIT_TIME_NW_SELECTION,
1220                       toggle_apm_after_setting=False):
1221    """Ensure ad's current network is in expected rat_family.
1222    """
1223    return ensure_network_rat_for_subscription(
1224        log, ad, ad.droid.subscriptionGetDefaultSubId(), network_preference,
1225        rat_family, voice_or_data, max_wait_time, toggle_apm_after_setting)
1226
1227
1228def ensure_network_rat_for_subscription(
1229        log,
1230        ad,
1231        sub_id,
1232        network_preference,
1233        rat_family,
1234        voice_or_data=None,
1235        max_wait_time=MAX_WAIT_TIME_NW_SELECTION,
1236        toggle_apm_after_setting=False):
1237    """Ensure ad's current network is in expected rat_family.
1238    """
1239    if not ad.droid.telephonySetPreferredNetworkTypesForSubscription(
1240            network_preference, sub_id):
1241        ad.log.error("Set sub_id %s Preferred Networks Type %s failed.",
1242                     sub_id, network_preference)
1243        return False
1244    if is_droid_in_rat_family_for_subscription(log, ad, sub_id, rat_family,
1245                                               voice_or_data):
1246        ad.log.info("Sub_id %s in RAT %s for %s", sub_id, rat_family,
1247                    voice_or_data)
1248        return True
1249
1250    if toggle_apm_after_setting:
1251        toggle_airplane_mode(log, ad, new_state=True, strict_checking=False)
1252        time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
1253        toggle_airplane_mode(log, ad, new_state=None, strict_checking=False)
1254
1255    result = wait_for_network_rat_for_subscription(
1256        log, ad, sub_id, rat_family, max_wait_time, voice_or_data)
1257
1258    log.info(
1259        "End of ensure_network_rat_for_subscription for %s. "
1260        "Setting to %s, Expecting %s %s. Current: voice: %s(family: %s), "
1261        "data: %s(family: %s)", ad.serial, network_preference, rat_family,
1262        voice_or_data,
1263        ad.droid.telephonyGetCurrentVoiceNetworkTypeForSubscription(sub_id),
1264        rat_family_from_rat(
1265            ad.droid.telephonyGetCurrentVoiceNetworkTypeForSubscription(
1266                sub_id)),
1267        ad.droid.telephonyGetCurrentDataNetworkTypeForSubscription(sub_id),
1268        rat_family_from_rat(
1269            ad.droid.telephonyGetCurrentDataNetworkTypeForSubscription(
1270                sub_id)))
1271    return result
1272
1273
1274def ensure_network_preference(log,
1275                              ad,
1276                              network_preference,
1277                              voice_or_data=None,
1278                              max_wait_time=MAX_WAIT_TIME_NW_SELECTION,
1279                              toggle_apm_after_setting=False):
1280    """Ensure that current rat is within the device's preferred network rats.
1281    """
1282    return ensure_network_preference_for_subscription(
1283        log, ad, ad.droid.subscriptionGetDefaultSubId(), network_preference,
1284        voice_or_data, max_wait_time, toggle_apm_after_setting)
1285
1286
1287def ensure_network_preference_for_subscription(
1288        log,
1289        ad,
1290        sub_id,
1291        network_preference,
1292        voice_or_data=None,
1293        max_wait_time=MAX_WAIT_TIME_NW_SELECTION,
1294        toggle_apm_after_setting=False):
1295    """Ensure ad's network preference is <network_preference> for sub_id.
1296    """
1297    rat_family_list = rat_families_for_network_preference(network_preference)
1298    if not ad.droid.telephonySetPreferredNetworkTypesForSubscription(
1299            network_preference, sub_id):
1300        log.error("Set Preferred Networks failed.")
1301        return False
1302    if is_droid_in_rat_family_list_for_subscription(
1303            log, ad, sub_id, rat_family_list, voice_or_data):
1304        return True
1305
1306    if toggle_apm_after_setting:
1307        toggle_airplane_mode(log, ad, new_state=True, strict_checking=False)
1308        time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
1309        toggle_airplane_mode(log, ad, new_state=False, strict_checking=False)
1310
1311    result = wait_for_preferred_network_for_subscription(
1312        log, ad, sub_id, network_preference, max_wait_time, voice_or_data)
1313
1314    ad.log.info(
1315        "End of ensure_network_preference_for_subscription. "
1316        "Setting to %s, Expecting %s %s. Current: voice: %s(family: %s), "
1317        "data: %s(family: %s)", network_preference, rat_family_list,
1318        voice_or_data,
1319        ad.droid.telephonyGetCurrentVoiceNetworkTypeForSubscription(sub_id),
1320        rat_family_from_rat(
1321            ad.droid.telephonyGetCurrentVoiceNetworkTypeForSubscription(
1322                sub_id)),
1323        ad.droid.telephonyGetCurrentDataNetworkTypeForSubscription(sub_id),
1324        rat_family_from_rat(
1325            ad.droid.telephonyGetCurrentDataNetworkTypeForSubscription(
1326                sub_id)))
1327    return result
1328
1329
1330def ensure_network_generation(log,
1331                              ad,
1332                              generation,
1333                              max_wait_time=MAX_WAIT_TIME_NW_SELECTION,
1334                              voice_or_data=None,
1335                              toggle_apm_after_setting=False,
1336                              nr_type=None):
1337    """Ensure ad's network is <network generation> for default subscription ID.
1338
1339    Set preferred network generation to <generation>.
1340    Toggle ON/OFF airplane mode if necessary.
1341    Wait for ad in expected network type.
1342    """
1343    return ensure_network_generation_for_subscription(
1344        log, ad, ad.droid.subscriptionGetDefaultSubId(), generation,
1345        max_wait_time, voice_or_data, toggle_apm_after_setting, nr_type=nr_type)
1346
1347
1348def ensure_network_generation_for_subscription(
1349        log,
1350        ad,
1351        sub_id,
1352        generation,
1353        max_wait_time=MAX_WAIT_TIME_NW_SELECTION,
1354        voice_or_data=None,
1355        toggle_apm_after_setting=False,
1356        nr_type=None):
1357    """Ensure ad's network is <network generation> for specified subscription ID.
1358
1359        Set preferred network generation to <generation>.
1360        Toggle ON/OFF airplane mode if necessary.
1361        Wait for ad in expected network type.
1362
1363    Args:
1364        log: log object.
1365        ad: android device object.
1366        sub_id: subscription id.
1367        generation: network generation, e.g. GEN_2G, GEN_3G, GEN_4G, GEN_5G.
1368        max_wait_time: the time to wait for NW selection.
1369        voice_or_data: check voice network generation or data network generation
1370            This parameter is optional. If voice_or_data is None, then if
1371            either voice or data in expected generation, function will return True.
1372        toggle_apm_after_setting: Cycle airplane mode if True, otherwise do nothing.
1373
1374    Returns:
1375        True if success, False if fail.
1376    """
1377    ad.log.info(
1378        "RAT network type voice: %s, data: %s",
1379        ad.droid.telephonyGetCurrentVoiceNetworkTypeForSubscription(sub_id),
1380        ad.droid.telephonyGetCurrentDataNetworkTypeForSubscription(sub_id))
1381
1382    try:
1383        ad.log.info("Finding the network preference for generation %s for "
1384                    "operator %s phone type %s", generation,
1385                    ad.telephony["subscription"][sub_id]["operator"],
1386                    ad.telephony["subscription"][sub_id]["phone_type"])
1387        network_preference = network_preference_for_generation(
1388            generation, ad.telephony["subscription"][sub_id]["operator"],
1389            ad.telephony["subscription"][sub_id]["phone_type"])
1390        if ad.telephony["subscription"][sub_id]["operator"] == CARRIER_FRE \
1391            and generation == GEN_4G:
1392            network_preference = NETWORK_MODE_LTE_ONLY
1393        ad.log.info("Network preference for %s is %s", generation,
1394                    network_preference)
1395        rat_family = rat_family_for_generation(
1396            generation, ad.telephony["subscription"][sub_id]["operator"],
1397            ad.telephony["subscription"][sub_id]["phone_type"])
1398    except KeyError as e:
1399        ad.log.error("Failed to find a rat_family entry for generation %s"
1400                     " for subscriber id %s with error %s", generation,
1401                     sub_id, e)
1402        return False
1403
1404    if not set_preferred_network_mode_pref(log, ad, sub_id,
1405                                           network_preference):
1406        return False
1407
1408    if hasattr(ad, "dsds") and voice_or_data == "data" and sub_id != get_default_data_sub_id(ad):
1409        ad.log.info("MSIM - Non DDS, ignore data RAT")
1410        return True
1411
1412    if (generation == GEN_5G) or (generation == RAT_5G):
1413        if is_current_network_5g(ad, sub_id=sub_id, nr_type=nr_type):
1414            ad.log.info("Current network type is 5G.")
1415            return True
1416        else:
1417            ad.log.error("Not in 5G coverage for Sub %s.", sub_id)
1418            return False
1419
1420    if is_droid_in_network_generation_for_subscription(
1421            log, ad, sub_id, generation, voice_or_data):
1422        return True
1423
1424    if toggle_apm_after_setting:
1425        toggle_airplane_mode(log, ad, new_state=True, strict_checking=False)
1426        time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
1427        toggle_airplane_mode(log, ad, new_state=False, strict_checking=False)
1428
1429    result = wait_for_network_generation_for_subscription(
1430        log, ad, sub_id, generation, max_wait_time, voice_or_data)
1431
1432    ad.log.info(
1433        "Ensure network %s %s %s. With network preference %s, "
1434        "current: voice: %s(family: %s), data: %s(family: %s)", generation,
1435        voice_or_data, result, network_preference,
1436        ad.droid.telephonyGetCurrentVoiceNetworkTypeForSubscription(sub_id),
1437        rat_generation_from_rat(
1438            ad.droid.telephonyGetCurrentVoiceNetworkTypeForSubscription(
1439                sub_id)),
1440        ad.droid.telephonyGetCurrentDataNetworkTypeForSubscription(sub_id),
1441        rat_generation_from_rat(
1442            ad.droid.telephonyGetCurrentDataNetworkTypeForSubscription(
1443                sub_id)))
1444    if not result:
1445        get_telephony_signal_strength(ad)
1446    return result
1447
1448
1449def wait_for_network_rat(log,
1450                         ad,
1451                         rat_family,
1452                         max_wait_time=MAX_WAIT_TIME_NW_SELECTION,
1453                         voice_or_data=None):
1454    return wait_for_network_rat_for_subscription(
1455        log, ad, ad.droid.subscriptionGetDefaultSubId(), rat_family,
1456        max_wait_time, voice_or_data)
1457
1458
1459def wait_for_network_rat_for_subscription(
1460        log,
1461        ad,
1462        sub_id,
1463        rat_family,
1464        max_wait_time=MAX_WAIT_TIME_NW_SELECTION,
1465        voice_or_data=None):
1466    return _wait_for_droid_in_state_for_subscription(
1467        log, ad, sub_id, max_wait_time,
1468        is_droid_in_rat_family_for_subscription, rat_family, voice_or_data)
1469
1470
1471def wait_for_not_network_rat(log,
1472                             ad,
1473                             rat_family,
1474                             max_wait_time=MAX_WAIT_TIME_NW_SELECTION,
1475                             voice_or_data=None):
1476    return wait_for_not_network_rat_for_subscription(
1477        log, ad, ad.droid.subscriptionGetDefaultSubId(), rat_family,
1478        max_wait_time, voice_or_data)
1479
1480
1481def wait_for_not_network_rat_for_subscription(
1482        log,
1483        ad,
1484        sub_id,
1485        rat_family,
1486        max_wait_time=MAX_WAIT_TIME_NW_SELECTION,
1487        voice_or_data=None):
1488    return _wait_for_droid_in_state_for_subscription(
1489        log, ad, sub_id, max_wait_time,
1490        lambda log, ad, sub_id, *args, **kwargs: not is_droid_in_rat_family_for_subscription(log, ad, sub_id, rat_family, voice_or_data)
1491    )
1492
1493
1494def wait_for_preferred_network(log,
1495                               ad,
1496                               network_preference,
1497                               max_wait_time=MAX_WAIT_TIME_NW_SELECTION,
1498                               voice_or_data=None):
1499    return wait_for_preferred_network_for_subscription(
1500        log, ad, ad.droid.subscriptionGetDefaultSubId(), network_preference,
1501        max_wait_time, voice_or_data)
1502
1503
1504def wait_for_preferred_network_for_subscription(
1505        log,
1506        ad,
1507        sub_id,
1508        network_preference,
1509        max_wait_time=MAX_WAIT_TIME_NW_SELECTION,
1510        voice_or_data=None):
1511    rat_family_list = rat_families_for_network_preference(network_preference)
1512    return _wait_for_droid_in_state_for_subscription(
1513        log, ad, sub_id, max_wait_time,
1514        is_droid_in_rat_family_list_for_subscription, rat_family_list,
1515        voice_or_data)
1516
1517
1518def wait_for_network_generation(log,
1519                                ad,
1520                                generation,
1521                                max_wait_time=MAX_WAIT_TIME_NW_SELECTION,
1522                                voice_or_data=None):
1523    return wait_for_network_generation_for_subscription(
1524        log, ad, ad.droid.subscriptionGetDefaultSubId(), generation,
1525        max_wait_time, voice_or_data)
1526
1527
1528def wait_for_network_generation_for_subscription(
1529        log,
1530        ad,
1531        sub_id,
1532        generation,
1533        max_wait_time=MAX_WAIT_TIME_NW_SELECTION,
1534        voice_or_data=None,
1535        nr_type=None):
1536
1537    if generation == GEN_5G:
1538        if is_current_network_5g(ad, sub_id=sub_id, nr_type=nr_type):
1539            ad.log.info("Current network type is 5G.")
1540            return True
1541        else:
1542            ad.log.error("Not in 5G coverage for Sub %s.", sub_id)
1543            return False
1544
1545    return _wait_for_droid_in_state_for_subscription(
1546        log, ad, sub_id, max_wait_time,
1547        is_droid_in_network_generation_for_subscription, generation,
1548        voice_or_data)
1549
1550
1551def ensure_phones_idle(log, ads, max_time=MAX_WAIT_TIME_CALL_DROP):
1552    """Ensure ads idle (not in call).
1553    """
1554    result = True
1555    for ad in ads:
1556        if not ensure_phone_idle(log, ad, max_time=max_time):
1557            result = False
1558    return result
1559
1560
1561def ensure_phone_idle(log, ad, max_time=MAX_WAIT_TIME_CALL_DROP, retry=2):
1562    """Ensure ad idle (not in call).
1563    """
1564    while ad.droid.telecomIsInCall() and retry > 0:
1565        ad.droid.telecomEndCall()
1566        time.sleep(3)
1567        retry -= 1
1568    if not wait_for_droid_not_in_call(log, ad, max_time=max_time):
1569        ad.log.error("Failed to end call")
1570        return False
1571    return True
1572
1573
1574def ensure_phone_subscription(log, ad):
1575    """Ensure Phone Subscription.
1576    """
1577    #check for sim and service
1578    duration = 0
1579    while duration < MAX_WAIT_TIME_NW_SELECTION:
1580        subInfo = ad.droid.subscriptionGetAllSubInfoList()
1581        if subInfo and len(subInfo) >= 1:
1582            ad.log.debug("Find valid subcription %s", subInfo)
1583            break
1584        else:
1585            ad.log.info("Did not find any subscription")
1586            time.sleep(5)
1587            duration += 5
1588    else:
1589        ad.log.error("Unable to find a valid subscription!")
1590        return False
1591    while duration < MAX_WAIT_TIME_NW_SELECTION:
1592        data_sub_id = ad.droid.subscriptionGetDefaultDataSubId()
1593        voice_sub_id = ad.droid.subscriptionGetDefaultVoiceSubId()
1594        if data_sub_id > INVALID_SUB_ID or voice_sub_id > INVALID_SUB_ID:
1595            ad.log.debug("Find valid voice or data sub id")
1596            break
1597        else:
1598            ad.log.info("Did not find valid data or voice sub id")
1599            if getattr(ad, 'mep', False):
1600                default_slot = getattr(ad, "default_slot", 1)
1601                if get_subid_from_slot_index(ad.log, ad, default_slot) != INVALID_SUB_ID:
1602                    ad.log.info("Slot %s is the default slot.", default_slot)
1603                    set_default_sub_for_all_services(ad, default_slot)
1604                else:
1605                    ad.log.warning("Slot %s is NOT a valid slot. Slot %s will be used by default.",
1606                        default_slot, 1-default_slot)
1607                    set_default_sub_for_all_services(ad, 1-default_slot)
1608                    setattr(ad, "default_slot", 1-default_slot)
1609            elif getattr(ad, 'dsds', False):
1610                default_slot = getattr(ad, "default_slot", 0)
1611                if get_subid_from_slot_index(ad.log, ad, default_slot) != INVALID_SUB_ID:
1612                    ad.log.info("Slot %s is the default slot.", default_slot)
1613                    set_default_sub_for_all_services(ad, default_slot)
1614                else:
1615                    ad.log.warning("Slot %s is NOT a valid slot. Slot %s will be used by default.",
1616                        default_slot, 1-default_slot)
1617                    set_default_sub_for_all_services(ad, 1-default_slot)
1618                    setattr(ad, "default_slot", 1-default_slot)
1619            time.sleep(5)
1620            duration += 5
1621    else:
1622        ad.log.error("Unable to find valid data or voice sub id")
1623        return False
1624    while duration < MAX_WAIT_TIME_NW_SELECTION:
1625        data_sub_id = ad.droid.subscriptionGetDefaultDataSubId()
1626        if data_sub_id > INVALID_SUB_ID:
1627            data_rat = get_network_rat_for_subscription(
1628                log, ad, data_sub_id, NETWORK_SERVICE_DATA)
1629        else:
1630            data_rat = RAT_UNKNOWN
1631        if voice_sub_id > INVALID_SUB_ID:
1632            voice_rat = get_network_rat_for_subscription(
1633                log, ad, voice_sub_id, NETWORK_SERVICE_VOICE)
1634        else:
1635            voice_rat = RAT_UNKNOWN
1636        if data_rat != RAT_UNKNOWN or voice_rat != RAT_UNKNOWN:
1637            ad.log.info("Data sub_id %s in %s, voice sub_id %s in %s",
1638                        data_sub_id, data_rat, voice_sub_id, voice_rat)
1639            return True
1640        else:
1641            ad.log.info("Did not attach for data or voice service")
1642            time.sleep(5)
1643            duration += 5
1644    else:
1645        ad.log.error("Did not attach for voice or data service")
1646        return False
1647
1648
1649def ensure_phone_default_state(log, ad, check_subscription=True, retry=2):
1650    """Ensure ad in default state.
1651    Phone not in call.
1652    Phone have no stored WiFi network and WiFi disconnected.
1653    Phone not in airplane mode.
1654    Phone is data on.
1655    """
1656    result = True
1657    if not toggle_airplane_mode(log, ad, False, False):
1658        ad.log.error("Fail to turn off airplane mode")
1659        result = False
1660    try:
1661        ad.droid.telephonyToggleDataConnection(True)
1662        set_wifi_to_default(log, ad)
1663        while ad.droid.telecomIsInCall() and retry > 0:
1664            ad.droid.telecomEndCall()
1665            time.sleep(3)
1666            retry -= 1
1667        if not wait_for_droid_not_in_call(log, ad):
1668            ad.log.error("Failed to end call")
1669        #ad.droid.telephonyFactoryReset()
1670        data_roaming = getattr(ad, 'roaming', False)
1671        if get_cell_data_roaming_state_by_adb(ad) != data_roaming:
1672            set_cell_data_roaming_state_by_adb(ad, data_roaming)
1673        #remove_mobile_data_usage_limit(ad)
1674        if not wait_for_not_network_rat(
1675                log, ad, RAT_FAMILY_WLAN, voice_or_data=NETWORK_SERVICE_DATA):
1676            ad.log.error("%s still in %s", NETWORK_SERVICE_DATA,
1677                         RAT_FAMILY_WLAN)
1678            result = False
1679
1680        if check_subscription and not ensure_phone_subscription(log, ad):
1681            ad.log.error("Unable to find a valid subscription!")
1682            result = False
1683    except Exception as e:
1684        ad.log.error("%s failure, toggle APM instead", e)
1685        toggle_airplane_mode_by_adb(log, ad, True)
1686        toggle_airplane_mode_by_adb(log, ad, False)
1687        ad.send_keycode("ENDCALL")
1688        ad.adb.shell("settings put global wfc_ims_enabled 0")
1689        ad.adb.shell("settings put global mobile_data 1")
1690
1691    return result
1692
1693
1694def ensure_phones_default_state(log, ads, check_subscription=True):
1695    """Ensure ads in default state.
1696    Phone not in call.
1697    Phone have no stored WiFi network and WiFi disconnected.
1698    Phone not in airplane mode.
1699
1700    Returns:
1701        True if all steps of restoring default state succeed.
1702        False if any of the steps to restore default state fails.
1703    """
1704    tasks = []
1705    for ad in ads:
1706        tasks.append((ensure_phone_default_state, (log, ad,
1707                                                   check_subscription)))
1708    if not multithread_func(log, tasks):
1709        log.error("Ensure_phones_default_state Fail.")
1710        return False
1711    return True
1712
1713
1714def is_phone_not_in_call(log, ad):
1715    """Return True if phone not in call.
1716
1717    Args:
1718        log: log object.
1719        ad:  android device.
1720    """
1721    in_call = ad.droid.telecomIsInCall()
1722    call_state = ad.droid.telephonyGetCallState()
1723    if in_call:
1724        ad.log.info("Device is In Call")
1725    if call_state != TELEPHONY_STATE_IDLE:
1726        ad.log.info("Call_state is %s, not %s", call_state,
1727                    TELEPHONY_STATE_IDLE)
1728    return ((not in_call) and (call_state == TELEPHONY_STATE_IDLE))
1729
1730
1731def wait_for_droid_not_in_call(log, ad, max_time=MAX_WAIT_TIME_CALL_DROP):
1732    """Wait for android to be not in call state.
1733
1734    Args:
1735        log: log object.
1736        ad:  android device.
1737        max_time: maximal wait time.
1738
1739    Returns:
1740        If phone become not in call state within max_time, return True.
1741        Return False if timeout.
1742    """
1743    return _wait_for_droid_in_state(log, ad, max_time, is_phone_not_in_call)
1744
1745
1746def wait_for_voice_attach(log, ad, max_time=MAX_WAIT_TIME_NW_SELECTION):
1747    """Wait for android device to attach on voice.
1748
1749    Args:
1750        log: log object.
1751        ad:  android device.
1752        max_time: maximal wait time.
1753
1754    Returns:
1755        Return True if device attach voice within max_time.
1756        Return False if timeout.
1757    """
1758    return _wait_for_droid_in_state(log, ad, max_time, _is_attached,
1759                                    NETWORK_SERVICE_VOICE)
1760
1761
1762def wait_for_voice_attach_for_subscription(
1763        log, ad, sub_id, max_time=MAX_WAIT_TIME_NW_SELECTION):
1764    """Wait for android device to attach on voice in subscription id.
1765
1766    Args:
1767        log: log object.
1768        ad:  android device.
1769        sub_id: subscription id.
1770        max_time: maximal wait time.
1771
1772    Returns:
1773        Return True if device attach voice within max_time.
1774        Return False if timeout.
1775    """
1776    if not _wait_for_droid_in_state_for_subscription(
1777            log, ad, sub_id, max_time, _is_attached_for_subscription,
1778            NETWORK_SERVICE_VOICE):
1779        return False
1780
1781    # TODO: b/26295983 if pone attach to 1xrtt from unknown, phone may not
1782    # receive incoming call immediately.
1783    if ad.droid.telephonyGetCurrentVoiceNetworkType() == RAT_1XRTT:
1784        time.sleep(WAIT_TIME_1XRTT_VOICE_ATTACH)
1785    return True
1786