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