1#!/usr/bin/env python3
2#
3#   Copyright 2016 - 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.test_utils.tel.loggers.protos.telephony_metric_pb2 import TelephonyVoiceTestResult
20from acts.test_utils.tel.tel_defines import CALL_PROPERTY_HIGH_DEF_AUDIO
21from acts.test_utils.tel.tel_defines import CALL_STATE_ACTIVE
22from acts.test_utils.tel.tel_defines import CALL_STATE_HOLDING
23from acts.test_utils.tel.tel_defines import CAPABILITY_VOLTE
24from acts.test_utils.tel.tel_defines import CAPABILITY_WFC
25from acts.test_utils.tel.tel_defines import GEN_2G
26from acts.test_utils.tel.tel_defines import GEN_3G
27from acts.test_utils.tel.tel_defines import GEN_4G
28from acts.test_utils.tel.tel_defines import GEN_5G
29from acts.test_utils.tel.tel_defines import MAX_WAIT_TIME_NW_SELECTION
30from acts.test_utils.tel.tel_defines import MAX_WAIT_TIME_VOLTE_ENABLED
31from acts.test_utils.tel.tel_defines import MAX_WAIT_TIME_WFC_ENABLED
32from acts.test_utils.tel.tel_defines import NETWORK_SERVICE_DATA
33from acts.test_utils.tel.tel_defines import NETWORK_SERVICE_VOICE
34from acts.test_utils.tel.tel_defines import RAT_FAMILY_CDMA2000
35from acts.test_utils.tel.tel_defines import RAT_FAMILY_LTE
36from acts.test_utils.tel.tel_defines import RAT_FAMILY_GSM
37from acts.test_utils.tel.tel_defines import RAT_FAMILY_WCDMA
38from acts.test_utils.tel.tel_defines import RAT_FAMILY_WLAN
39from acts.test_utils.tel.tel_defines import RAT_1XRTT
40from acts.test_utils.tel.tel_defines import RAT_IWLAN
41from acts.test_utils.tel.tel_defines import RAT_LTE
42from acts.test_utils.tel.tel_defines import RAT_UMTS
43from acts.test_utils.tel.tel_defines import WAIT_TIME_BETWEEN_REG_AND_CALL
44from acts.test_utils.tel.tel_defines import WAIT_TIME_IN_CALL
45from acts.test_utils.tel.tel_defines import WAIT_TIME_LEAVE_VOICE_MAIL
46from acts.test_utils.tel.tel_defines import WFC_MODE_DISABLED
47from acts.test_utils.tel.tel_defines import WFC_MODE_CELLULAR_PREFERRED
48from acts.test_utils.tel.tel_defines import NETWORK_MODE_CDMA
49from acts.test_utils.tel.tel_defines import NETWORK_MODE_GSM_ONLY
50from acts.test_utils.tel.tel_defines import NETWORK_MODE_GSM_UMTS
51from acts.test_utils.tel.tel_defines import NETWORK_MODE_LTE_CDMA_EVDO
52from acts.test_utils.tel.tel_defines import NETWORK_MODE_LTE_GSM_WCDMA
53from acts.test_utils.tel.tel_defines import INVALID_SUB_ID
54from acts.test_utils.tel.tel_subscription_utils import get_outgoing_voice_sub_id
55from acts.test_utils.tel.tel_subscription_utils import set_subid_for_outgoing_call
56from acts.test_utils.tel.tel_subscription_utils import get_subid_from_slot_index
57from acts.test_utils.tel.tel_subscription_utils import get_default_data_sub_id
58from acts.test_utils.tel.tel_test_utils import call_reject_leave_message
59from acts.test_utils.tel.tel_test_utils import call_setup_teardown
60from acts.test_utils.tel.tel_test_utils import call_setup_teardown_for_call_forwarding
61from acts.test_utils.tel.tel_test_utils import call_setup_teardown_for_call_waiting
62from acts.test_utils.tel.tel_test_utils import ensure_network_generation
63from acts.test_utils.tel.tel_test_utils import \
64    ensure_network_generation_for_subscription
65from acts.test_utils.tel.tel_test_utils import \
66    ensure_network_rat_for_subscription
67from acts.test_utils.tel.tel_test_utils import ensure_phones_idle
68from acts.test_utils.tel.tel_test_utils import ensure_wifi_connected
69from acts.test_utils.tel.tel_test_utils import get_network_gen_for_subscription
70from acts.test_utils.tel.tel_test_utils import get_network_rat
71from acts.test_utils.tel.tel_test_utils import get_network_rat_for_subscription
72from acts.test_utils.tel.tel_test_utils import get_telephony_signal_strength
73from acts.test_utils.tel.tel_test_utils import is_wfc_enabled
74from acts.test_utils.tel.tel_test_utils import \
75    reset_preferred_network_type_to_allowable_range
76from acts.test_utils.tel.tel_test_utils import set_wfc_mode
77from acts.test_utils.tel.tel_test_utils import set_wifi_to_default
78from acts.test_utils.tel.tel_test_utils import TelResultWrapper
79from acts.test_utils.tel.tel_test_utils import toggle_airplane_mode
80from acts.test_utils.tel.tel_test_utils import toggle_volte
81from acts.test_utils.tel.tel_test_utils import toggle_volte_for_subscription
82from acts.test_utils.tel.tel_test_utils import verify_incall_state
83from acts.test_utils.tel.tel_test_utils import verify_internet_connection
84from acts.test_utils.tel.tel_test_utils import \
85    wait_for_data_attach_for_subscription
86from acts.test_utils.tel.tel_test_utils import wait_for_enhanced_4g_lte_setting
87from acts.test_utils.tel.tel_test_utils import wait_for_network_generation
88from acts.test_utils.tel.tel_test_utils import \
89    wait_for_network_generation_for_subscription
90from acts.test_utils.tel.tel_test_utils import wait_for_not_network_rat
91from acts.test_utils.tel.tel_test_utils import wait_for_network_rat
92from acts.test_utils.tel.tel_test_utils import \
93    wait_for_network_rat_for_subscription
94from acts.test_utils.tel.tel_test_utils import \
95     wait_for_not_network_rat_for_subscription
96from acts.test_utils.tel.tel_test_utils import wait_for_volte_enabled
97from acts.test_utils.tel.tel_test_utils import \
98    wait_for_voice_attach_for_subscription
99from acts.test_utils.tel.tel_test_utils import wait_for_wfc_enabled
100from acts.test_utils.tel.tel_test_utils import wait_for_wfc_disabled
101from acts.test_utils.tel.tel_test_utils import get_capability_for_subscription
102
103CallResult = TelephonyVoiceTestResult.CallResult.Value
104
105
106def two_phone_call_leave_voice_mail(
107        log,
108        caller,
109        caller_idle_func,
110        caller_in_call_check_func,
111        callee,
112        callee_idle_func,
113        wait_time_in_call=WAIT_TIME_LEAVE_VOICE_MAIL):
114    """Call from caller to callee, reject on callee, caller leave a voice mail.
115
116    1. Caller call Callee.
117    2. Callee reject incoming call.
118    3. Caller leave a voice mail.
119    4. Verify callee received the voice mail notification.
120
121    Args:
122        caller: caller android device object.
123        caller_idle_func: function to check caller's idle state.
124        caller_in_call_check_func: function to check caller's in-call state.
125        callee: callee android device object.
126        callee_idle_func: function to check callee's idle state.
127        wait_time_in_call: time to wait when leaving a voice mail.
128            This is optional, default is WAIT_TIME_LEAVE_VOICE_MAIL
129
130    Returns:
131        True: if voice message is received on callee successfully.
132        False: for errors
133    """
134
135    ads = [caller, callee]
136
137    # Make sure phones are idle.
138    ensure_phones_idle(log, ads)
139    if caller_idle_func and not caller_idle_func(log, caller):
140        caller.log.error("Caller Failed to Reselect")
141        return False
142    if callee_idle_func and not callee_idle_func(log, callee):
143        callee.log.error("Callee Failed to Reselect")
144        return False
145
146    # TODO: b/26337871 Need to use proper API to check phone registered.
147    time.sleep(WAIT_TIME_BETWEEN_REG_AND_CALL)
148
149    # Make call and leave a message.
150    if not call_reject_leave_message(
151            log, caller, callee, caller_in_call_check_func, wait_time_in_call):
152        log.error("make a call and leave a message failed.")
153        return False
154    return True
155
156
157def two_phone_call_short_seq(log,
158                             phone_a,
159                             phone_a_idle_func,
160                             phone_a_in_call_check_func,
161                             phone_b,
162                             phone_b_idle_func,
163                             phone_b_in_call_check_func,
164                             call_sequence_func=None,
165                             wait_time_in_call=WAIT_TIME_IN_CALL):
166    """Call process short sequence.
167    1. Ensure phone idle and in idle_func check return True.
168    2. Call from PhoneA to PhoneB, accept on PhoneB.
169    3. Check phone state, hangup on PhoneA.
170    4. Ensure phone idle and in idle_func check return True.
171    5. Call from PhoneA to PhoneB, accept on PhoneB.
172    6. Check phone state, hangup on PhoneB.
173
174    Args:
175        phone_a: PhoneA's android device object.
176        phone_a_idle_func: function to check PhoneA's idle state.
177        phone_a_in_call_check_func: function to check PhoneA's in-call state.
178        phone_b: PhoneB's android device object.
179        phone_b_idle_func: function to check PhoneB's idle state.
180        phone_b_in_call_check_func: function to check PhoneB's in-call state.
181        call_sequence_func: default parameter, not implemented.
182        wait_time_in_call: time to wait in call.
183            This is optional, default is WAIT_TIME_IN_CALL
184
185    Returns:
186        TelResultWrapper which will evaluate as False if error.
187    """
188    ads = [phone_a, phone_b]
189
190    call_params = [
191        (ads[0], ads[1], ads[0], phone_a_in_call_check_func,
192         phone_b_in_call_check_func),
193        (ads[0], ads[1], ads[1], phone_a_in_call_check_func,
194         phone_b_in_call_check_func),
195    ]
196
197    tel_result = TelResultWrapper(CallResult('SUCCESS'))
198    for param in call_params:
199        # Make sure phones are idle.
200        ensure_phones_idle(log, ads)
201        if phone_a_idle_func and not phone_a_idle_func(log, phone_a):
202            phone_a.log.error("Phone A Failed to Reselect")
203            return TelResultWrapper(CallResult('CALL_SETUP_FAILURE'))
204        if phone_b_idle_func and not phone_b_idle_func(log, phone_b):
205            phone_b.log.error("Phone B Failed to Reselect")
206            return TelResultWrapper(CallResult('CALL_SETUP_FAILURE'))
207
208        # TODO: b/26337871 Need to use proper API to check phone registered.
209        time.sleep(WAIT_TIME_BETWEEN_REG_AND_CALL)
210
211        # Make call.
212        log.info("---> Call test: %s to %s <---", param[0].serial,
213                 param[1].serial)
214        tel_result = call_setup_teardown(
215                log, *param, wait_time_in_call=wait_time_in_call)
216        if not tel_result:
217            log.error("Call Iteration Failed")
218            break
219
220    return tel_result
221
222def two_phone_call_msim_short_seq(log,
223                             phone_a,
224                             phone_a_idle_func,
225                             phone_a_in_call_check_func,
226                             phone_b,
227                             phone_b_idle_func,
228                             phone_b_in_call_check_func,
229                             call_sequence_func=None,
230                             wait_time_in_call=WAIT_TIME_IN_CALL):
231    """Call process short sequence.
232    1. Ensure phone idle and in idle_func check return True.
233    2. Call from PhoneA to PhoneB, accept on PhoneB.
234    3. Check phone state, hangup on PhoneA.
235    4. Ensure phone idle and in idle_func check return True.
236    5. Call from PhoneA to PhoneB, accept on PhoneB.
237    6. Check phone state, hangup on PhoneB.
238    Args:
239        phone_a: PhoneA's android device object.
240        phone_a_idle_func: function to check PhoneA's idle state.
241        phone_a_in_call_check_func: function to check PhoneA's in-call state.
242        phone_b: PhoneB's android device object.
243        phone_b_idle_func: function to check PhoneB's idle state.
244        phone_b_in_call_check_func: function to check PhoneB's in-call state.
245        call_sequence_func: default parameter, not implemented.
246        wait_time_in_call: time to wait in call.
247            This is optional, default is WAIT_TIME_IN_CALL
248    Returns:
249        True: if call sequence succeed.
250        False: for errors
251    """
252    ads = [phone_a, phone_b]
253    call_params = [
254        (ads[0], ads[1], ads[0], phone_a_in_call_check_func,
255         phone_b_in_call_check_func),
256        (ads[0], ads[1], ads[1], phone_a_in_call_check_func,
257         phone_b_in_call_check_func),
258    ]
259    for param in call_params:
260        # Make sure phones are idle.
261        ensure_phones_idle(log, ads)
262        if phone_a_idle_func and not phone_a_idle_func(log, phone_a):
263            phone_a.log.error("Phone A Failed to Reselect")
264            return False
265        if phone_b_idle_func and not phone_b_idle_func(log, phone_b):
266            phone_b.log.error("Phone B Failed to Reselect")
267            return False
268        # TODO: b/26337871 Need to use proper API to check phone registered.
269        time.sleep(WAIT_TIME_BETWEEN_REG_AND_CALL)
270        # Make call.
271        log.info("--> Call test: %s to %s <--", phone_a.serial, phone_b.serial)
272        slots = 2
273        for slot in range(slots):
274            set_subid_for_outgoing_call(
275                            ads[0], get_subid_from_slot_index(log,ads[0],slot))
276            set_subid_for_outgoing_call(
277                            ads[1], get_subid_from_slot_index(log,ads[1],slot))
278            time.sleep(WAIT_TIME_BETWEEN_REG_AND_CALL)
279            if not call_setup_teardown(log, *param,slot_id_callee = slot,
280                                       wait_time_in_call=wait_time_in_call):
281                log.error("Call Iteration Failed")
282                return False
283            if not call_setup_teardown(log, *param,slot_id_callee = 1-slot,
284                                       wait_time_in_call=wait_time_in_call):
285                log.error("Call Iteration Failed")
286                return False
287    return True
288
289def two_phone_call_long_seq(log,
290                            phone_a,
291                            phone_a_idle_func,
292                            phone_a_in_call_check_func,
293                            phone_b,
294                            phone_b_idle_func,
295                            phone_b_in_call_check_func,
296                            call_sequence_func=None,
297                            wait_time_in_call=WAIT_TIME_IN_CALL):
298    """Call process long sequence.
299    1. Ensure phone idle and in idle_func check return True.
300    2. Call from PhoneA to PhoneB, accept on PhoneB.
301    3. Check phone state, hangup on PhoneA.
302    4. Ensure phone idle and in idle_func check return True.
303    5. Call from PhoneA to PhoneB, accept on PhoneB.
304    6. Check phone state, hangup on PhoneB.
305    7. Ensure phone idle and in idle_func check return True.
306    8. Call from PhoneB to PhoneA, accept on PhoneA.
307    9. Check phone state, hangup on PhoneA.
308    10. Ensure phone idle and in idle_func check return True.
309    11. Call from PhoneB to PhoneA, accept on PhoneA.
310    12. Check phone state, hangup on PhoneB.
311
312    Args:
313        phone_a: PhoneA's android device object.
314        phone_a_idle_func: function to check PhoneA's idle state.
315        phone_a_in_call_check_func: function to check PhoneA's in-call state.
316        phone_b: PhoneB's android device object.
317        phone_b_idle_func: function to check PhoneB's idle state.
318        phone_b_in_call_check_func: function to check PhoneB's in-call state.
319        call_sequence_func: default parameter, not implemented.
320        wait_time_in_call: time to wait in call.
321            This is optional, default is WAIT_TIME_IN_CALL
322
323    Returns:
324        TelResultWrapper which will evaluate as False if error.
325
326    """
327    ads = [phone_a, phone_b]
328
329    call_params = [
330        (ads[0], ads[1], ads[0], phone_a_in_call_check_func,
331         phone_b_in_call_check_func),
332        (ads[0], ads[1], ads[1], phone_a_in_call_check_func,
333         phone_b_in_call_check_func),
334        (ads[1], ads[0], ads[0], phone_b_in_call_check_func,
335         phone_a_in_call_check_func),
336        (ads[1], ads[0], ads[1], phone_b_in_call_check_func,
337         phone_a_in_call_check_func),
338    ]
339
340    tel_result = TelResultWrapper(CallResult('SUCCESS'))
341    for param in call_params:
342        # Make sure phones are idle.
343        ensure_phones_idle(log, ads)
344        if phone_a_idle_func and not phone_a_idle_func(log, phone_a):
345            phone_a.log.error("Phone A Failed to Reselect")
346            return TelResultWrapper(CallResult('CALL_SETUP_FAILURE'))
347        if phone_b_idle_func and not phone_b_idle_func(log, phone_b):
348            phone_b.log.error("Phone B Failed to Reselect")
349            return TelResultWrapper(CallResult('CALL_SETUP_FAILURE'))
350
351        # TODO: b/26337871 Need to use proper API to check phone registered.
352        time.sleep(WAIT_TIME_BETWEEN_REG_AND_CALL)
353
354        # Make call.
355        log.info("---> Call test: %s to %s <---", param[0].serial,
356                 param[1].serial)
357        tel_result = call_setup_teardown(
358                log, *param, wait_time_in_call=wait_time_in_call)
359        if not tel_result:
360            log.error("Call Iteration Failed")
361            break
362
363    return tel_result
364
365def two_phone_call_msim_for_slot(log,
366                             phone_a,
367                             phone_a_slot,
368                             phone_a_idle_func,
369                             phone_a_in_call_check_func,
370                             phone_b,
371                             phone_b_slot,
372                             phone_b_idle_func,
373                             phone_b_in_call_check_func,
374                             call_sequence_func=None,
375                             wait_time_in_call=WAIT_TIME_IN_CALL,
376                             retry=2):
377    """Call process between 2 phones with specific slot.
378    1. Ensure phone idle and in idle_func    check return True.
379    2. Call from PhoneA to PhoneB, accept on PhoneB.
380    3. Check phone state, hangup on PhoneA.
381    4. Ensure phone idle and in idle_func check return True.
382    5. Call from PhoneA to PhoneB, accept on PhoneB.
383    6. Check phone state, hangup on PhoneB.
384
385    Args:
386        phone_a: PhoneA's android device object.
387        phone_a_slot: 0 or 1 (pSIM or eSIM)
388        phone_a_idle_func: function to check PhoneA's idle state.
389        phone_a_in_call_check_func: function to check PhoneA's in-call state.
390        phone_b: PhoneB's android device object.
391        phone_b_slot: 0 or 1 (pSIM or eSIM)
392        phone_b_idle_func: function to check PhoneB's idle state.
393        phone_b_in_call_check_func: function to check PhoneB's in-call state.
394        call_sequence_func: default parameter, not implemented.
395        wait_time_in_call: time to wait in call.
396            This is optional, default is WAIT_TIME_IN_CALL
397        retry: times of retry if call_setup_teardown failed.
398
399    Returns:
400        True: if call sequence succeed.
401        False: for errors
402    """
403    ads = [phone_a, phone_b]
404
405    call_params = [
406        (ads[0], ads[1], ads[0], phone_a_in_call_check_func,
407         phone_b_in_call_check_func),
408        (ads[0], ads[1], ads[1], phone_a_in_call_check_func,
409         phone_b_in_call_check_func),
410    ]
411
412    tel_result = TelResultWrapper(CallResult('SUCCESS'))
413    for param in call_params:
414        # Make sure phones are idle.
415        ensure_phones_idle(log, ads)
416        if phone_a_idle_func and not phone_a_idle_func(log, phone_a):
417            phone_a.log.error("Phone A Failed to Reselect")
418            return TelResultWrapper(CallResult('CALL_SETUP_FAILURE'))
419        if phone_b_idle_func and not phone_b_idle_func(log, phone_b):
420            phone_b.log.error("Phone B Failed to Reselect")
421            return TelResultWrapper(CallResult('CALL_SETUP_FAILURE'))
422
423        # TODO: b/26337871 Need to use proper API to check phone registered.
424        time.sleep(WAIT_TIME_BETWEEN_REG_AND_CALL)
425
426        # Make call.
427        log.info("--> Call test: %s slot %s to %s slot %s <--", phone_a.serial,
428            phone_a_slot, phone_b.serial, phone_b_slot)
429
430        mo_default_voice_subid = get_subid_from_slot_index(log,ads[0],
431            phone_a_slot)
432        if mo_default_voice_subid == INVALID_SUB_ID:
433            log.warning("Sub ID of MO (%s) slot %s is invalid.", phone_a.serial,
434                phone_a_slot)
435            return TelResultWrapper(CallResult('CALL_SETUP_FAILURE'))
436        set_subid_for_outgoing_call(
437                            ads[0], mo_default_voice_subid)
438
439        mt_default_voice_subid = get_subid_from_slot_index(log,ads[1],
440            phone_b_slot)
441        if mt_default_voice_subid == INVALID_SUB_ID:
442            log.warning("Sub ID of MT (%s) slot %s is invalid.", phone_b.serial,
443                phone_b_slot)
444            return TelResultWrapper(CallResult('CALL_SETUP_FAILURE'))
445
446        tel_result = call_setup_teardown(
447            log,
448            *param,
449            slot_id_callee=phone_b_slot,
450            wait_time_in_call=wait_time_in_call)
451
452        while not tel_result:
453            if retry <= 0:
454                log.error("Call Iteration failed.")
455                break
456            else:
457                log.info("RERUN call_setup_teardown.")
458                tel_result = call_setup_teardown(
459                    log,
460                    *param,
461                    slot_id_callee=phone_b_slot,
462                    wait_time_in_call=wait_time_in_call)
463
464            retry = retry - 1
465
466    return tel_result
467
468def three_phone_call_forwarding_short_seq(log,
469                             phone_a,
470                             phone_a_idle_func,
471                             phone_a_in_call_check_func,
472                             phone_b,
473                             phone_c,
474                             wait_time_in_call=WAIT_TIME_IN_CALL,
475                             call_forwarding_type="unconditional",
476                             retry=2):
477    """Short sequence of call process with call forwarding.
478    Test steps:
479        1. Ensure all phones are initially in idle state.
480        2. Enable call forwarding on Phone A.
481        3. Make a call from Phone B to Phone A, The call should be forwarded to
482           PhoneC. Accept the call on Phone C.
483        4. Ensure the call is connected and in correct phone state.
484        5. Hang up the call on Phone B.
485        6. Ensure all phones are in idle state.
486        7. Disable call forwarding on Phone A.
487        7. Make a call from Phone B to Phone A, The call should NOT be forwarded
488           to PhoneC. Accept the call on Phone A.
489        8. Ensure the call is connected and in correct phone state.
490        9. Hang up the call on Phone B.
491
492    Args:
493        phone_a: android object of Phone A
494        phone_a_idle_func: function to check idle state on Phone A
495        phone_a_in_call_check_func: function to check in-call state on Phone A
496        phone_b: android object of Phone B
497        phone_c: android object of Phone C
498        wait_time_in_call: time to wait in call.
499            This is optional, default is WAIT_TIME_IN_CALL
500        call_forwarding_type:
501            - "unconditional"
502            - "busy"
503            - "not_answered"
504            - "not_reachable"
505        retry: times of retry
506
507    Returns:
508        True: if call sequence succeed.
509        False: for errors
510    """
511    ads = [phone_a, phone_b, phone_c]
512
513    call_params = [
514        (ads[1], ads[0], ads[2], ads[1], phone_a_in_call_check_func, False)
515    ]
516
517    if call_forwarding_type != "unconditional":
518        call_params.append((
519            ads[1],
520            ads[0],
521            ads[2],
522            ads[1],
523            phone_a_in_call_check_func,
524            True))
525
526    for param in call_params:
527        ensure_phones_idle(log, ads)
528        if phone_a_idle_func and not phone_a_idle_func(log, phone_a):
529            phone_a.log.error("Phone A Failed to Reselect")
530            return False
531
532        time.sleep(WAIT_TIME_BETWEEN_REG_AND_CALL)
533
534        log.info(
535            "---> Call forwarding %s (caller: %s, callee: %s, callee forwarded:"
536            " %s) <---",
537            call_forwarding_type,
538            param[0].serial,
539            param[1].serial,
540            param[2].serial)
541        while not call_setup_teardown_for_call_forwarding(
542                log,
543                *param,
544                wait_time_in_call=wait_time_in_call,
545                call_forwarding_type=call_forwarding_type) and retry >= 0:
546
547            if retry <= 0:
548                log.error("Call forwarding %s failed." % call_forwarding_type)
549                return False
550            else:
551                log.info(
552                    "RERUN the test case: 'Call forwarding %s'" %
553                    call_forwarding_type)
554
555            retry = retry - 1
556
557    return True
558
559def three_phone_call_waiting_short_seq(log,
560                             phone_a,
561                             phone_a_idle_func,
562                             phone_a_in_call_check_func,
563                             phone_b,
564                             phone_c,
565                             wait_time_in_call=WAIT_TIME_IN_CALL,
566                             call_waiting=True,
567                             scenario=None,
568                             retry=2):
569    """Short sequence of call process with call waiting.
570    Test steps:
571        1. Ensure all phones are initially in idle state.
572        2. Enable call waiting on Phone A.
573        3. Make the 1st call from Phone B to Phone A. Accept the call on Phone B.
574        4. Ensure the call is connected and in correct phone state.
575        5. Make the 2nd call from Phone C to Phone A. The call should be able to
576           income correctly. Whether or not the 2nd call should be answered by
577           Phone A depends on the scenario listed in the next step.
578        6. Following 8 scenarios will be tested:
579           - 1st call ended first by Phone B during 2nd call incoming. 2nd call
580             ended by Phone C
581           - 1st call ended first by Phone B during 2nd call incoming. 2nd call
582             ended by Phone A
583           - 1st call ended first by Phone A during 2nd call incoming. 2nd call
584             ended by Phone C
585           - 1st call ended first by Phone A during 2nd call incoming. 2nd call
586             ended by Phone A
587           - 1st call ended by Phone B. 2nd call ended by Phone C
588           - 1st call ended by Phone B. 2nd call ended by Phone A
589           - 1st call ended by Phone A. 2nd call ended by Phone C
590           - 1st call ended by Phone A. 2nd call ended by Phone A
591        7. Ensure all phones are in idle state.
592
593    Args:
594        phone_a: android object of Phone A
595        phone_a_idle_func: function to check idle state on Phone A
596        phone_a_in_call_check_func: function to check in-call state on Phone A
597        phone_b: android object of Phone B
598        phone_c: android object of Phone C
599        wait_time_in_call: time to wait in call.
600            This is optional, default is WAIT_TIME_IN_CALL
601        call_waiting: True for call waiting enabled and False for disabled
602        scenario: 1-8 for scenarios listed above
603        retry: times of retry
604
605    Returns:
606        True: if call sequence succeed.
607        False: for errors
608    """
609    ads = [phone_a, phone_b, phone_c]
610
611    sub_test_cases = [
612        {
613            "description": "1st call ended first by caller1 during 2nd call"
614                " incoming. 2nd call ended by caller2",
615            "params": (
616                ads[1],
617                ads[0],
618                ads[2],
619                ads[1],
620                ads[2],
621                phone_a_in_call_check_func,
622                True)},
623        {
624            "description": "1st call ended first by caller1 during 2nd call"
625                " incoming. 2nd call ended by callee",
626            "params": (
627                ads[1],
628                ads[0],
629                ads[2],
630                ads[1],
631                ads[0],
632                phone_a_in_call_check_func,
633                True)},
634        {
635            "description": "1st call ended first by callee during 2nd call"
636                " incoming. 2nd call ended by caller2",
637            "params": (
638                ads[1],
639                ads[0],
640                ads[2],
641                ads[0],
642                ads[2],
643                phone_a_in_call_check_func,
644                True)},
645        {
646            "description": "1st call ended first by callee during 2nd call"
647                " incoming. 2nd call ended by callee",
648            "params": (
649                ads[1],
650                ads[0],
651                ads[2],
652                ads[0],
653                ads[0],
654                phone_a_in_call_check_func,
655                True)},
656        {
657            "description": "1st call ended by caller1. 2nd call ended by"
658                " caller2",
659            "params": (
660                ads[1],
661                ads[0],
662                ads[2],
663                ads[1],
664                ads[2],
665                phone_a_in_call_check_func,
666                False)},
667        {
668            "description": "1st call ended by caller1. 2nd call ended by callee",
669            "params": (
670                ads[1],
671                ads[0],
672                ads[2],
673                ads[1],
674                ads[0],
675                phone_a_in_call_check_func,
676                False)},
677        {
678            "description": "1st call ended by callee. 2nd call ended by caller2",
679            "params": (
680                ads[1],
681                ads[0],
682                ads[2],
683                ads[0],
684                ads[2],
685                phone_a_in_call_check_func,
686                False)},
687        {
688            "description": "1st call ended by callee. 2nd call ended by callee",
689            "params": (
690                ads[1],
691                ads[0],
692                ads[2],
693                ads[0],
694                ads[0],
695                phone_a_in_call_check_func,
696                False)}
697    ]
698
699    if call_waiting:
700        if not scenario:
701            test_cases = sub_test_cases
702        else:
703            test_cases = [sub_test_cases[scenario-1]]
704    else:
705        test_cases = [
706            {
707                "description": "Call waiting deactivated",
708                "params": (
709                    ads[1],
710                    ads[0],
711                    ads[2],
712                    ads[0],
713                    ads[0],
714                    phone_a_in_call_check_func,
715                    False)}
716        ]
717
718    results = []
719
720    for test_case in test_cases:
721        ensure_phones_idle(log, ads)
722        if phone_a_idle_func and not phone_a_idle_func(log, phone_a):
723            phone_a.log.error("Phone A Failed to Reselect")
724            return False
725
726        time.sleep(WAIT_TIME_BETWEEN_REG_AND_CALL)
727
728        log.info(
729            "---> %s (caller1: %s, caller2: %s, callee: %s) <---",
730            test_case["description"],
731            test_case["params"][1].serial,
732            test_case["params"][2].serial,
733            test_case["params"][0].serial)
734
735        while not call_setup_teardown_for_call_waiting(
736            log,
737            *test_case["params"],
738            wait_time_in_call=wait_time_in_call,
739            call_waiting=call_waiting) and retry >= 0:
740
741            if retry <= 0:
742                log.error("Call waiting sub-case: '%s' failed." % test_case[
743                    "description"])
744                results.append(False)
745            else:
746                log.info("RERUN the sub-case: '%s'" % test_case["description"])
747
748            retry = retry - 1
749
750    for result in results:
751        if not result:
752            return False
753
754    return True
755
756def phone_setup_iwlan(log,
757                      ad,
758                      is_airplane_mode,
759                      wfc_mode,
760                      wifi_ssid=None,
761                      wifi_pwd=None):
762    """Phone setup function for epdg call test.
763    Set WFC mode according to wfc_mode.
764    Set airplane mode according to is_airplane_mode.
765    Make sure phone connect to WiFi. (If wifi_ssid is not None.)
766    Wait for phone to be in iwlan data network type.
767    Wait for phone to report wfc enabled flag to be true.
768
769    Args:
770        log: Log object.
771        ad: Android device object.
772        is_airplane_mode: True to turn on airplane mode. False to turn off airplane mode.
773        wfc_mode: WFC mode to set to.
774        wifi_ssid: WiFi network SSID. This is optional.
775            If wifi_ssid is None, then phone_setup_iwlan will not attempt to connect to wifi.
776        wifi_pwd: WiFi network password. This is optional.
777
778    Returns:
779        True if success. False if fail.
780    """
781    if not get_capability_for_subscription(ad, CAPABILITY_WFC,
782        get_outgoing_voice_sub_id(ad)):
783        ad.log.error("WFC is not supported, abort test.")
784        raise signals.TestSkip("WFC is not supported, abort test.")
785    return phone_setup_iwlan_for_subscription(log, ad,
786                                              get_outgoing_voice_sub_id(ad),
787                                              is_airplane_mode, wfc_mode,
788                                              wifi_ssid, wifi_pwd)
789
790
791def phone_setup_iwlan_for_subscription(log,
792                                       ad,
793                                       sub_id,
794                                       is_airplane_mode,
795                                       wfc_mode,
796                                       wifi_ssid=None,
797                                       wifi_pwd=None):
798    """Phone setup function for epdg call test for subscription id.
799    Set WFC mode according to wfc_mode.
800    Set airplane mode according to is_airplane_mode.
801    Make sure phone connect to WiFi. (If wifi_ssid is not None.)
802    Wait for phone to be in iwlan data network type.
803    Wait for phone to report wfc enabled flag to be true.
804
805    Args:
806        log: Log object.
807        ad: Android device object.
808        sub_id: subscription id.
809        is_airplane_mode: True to turn on airplane mode. False to turn off airplane mode.
810        wfc_mode: WFC mode to set to.
811        wifi_ssid: WiFi network SSID. This is optional.
812            If wifi_ssid is None, then phone_setup_iwlan will not attempt to connect to wifi.
813        wifi_pwd: WiFi network password. This is optional.
814
815    Returns:
816        True if success. False if fail.
817    """
818    toggle_airplane_mode(log, ad, is_airplane_mode, strict_checking=False)
819
820    # check if WFC supported phones
821    if wfc_mode != WFC_MODE_DISABLED and not ad.droid.imsIsWfcEnabledByPlatform(
822    ):
823        ad.log.error("WFC is not enabled on this device by checking "
824                     "ImsManager.isWfcEnabledByPlatform")
825        return False
826
827    if wifi_ssid is not None:
828        if not ensure_wifi_connected(log, ad, wifi_ssid, wifi_pwd, apm=is_airplane_mode):
829            ad.log.error("Fail to bring up WiFi connection on %s.", wifi_ssid)
830            return False
831    else:
832        ad.log.info("WiFi network SSID not specified, available user "
833                    "parameters are: wifi_network_ssid, wifi_network_ssid_2g, "
834                    "wifi_network_ssid_5g")
835
836    if not set_wfc_mode(log, ad, wfc_mode):
837        ad.log.error("Unable to set WFC mode to %s.", wfc_mode)
838        return False
839
840    if not wait_for_wfc_enabled(log, ad, max_time=MAX_WAIT_TIME_WFC_ENABLED):
841        ad.log.error("WFC is not enabled")
842        return False
843    return True
844
845
846def phone_setup_iwlan_cellular_preferred(log,
847                                         ad,
848                                         wifi_ssid=None,
849                                         wifi_pwd=None):
850    """Phone setup function for iwlan Non-APM CELLULAR_PREFERRED test.
851    Set WFC mode according to CELLULAR_PREFERRED.
852    Set airplane mode according to False.
853    Make sure phone connect to WiFi. (If wifi_ssid is not None.)
854    Make sure phone don't report iwlan data network type.
855    Make sure phone don't report wfc enabled flag to be true.
856
857    Args:
858        log: Log object.
859        ad: Android device object.
860        wifi_ssid: WiFi network SSID. This is optional.
861            If wifi_ssid is None, then phone_setup_iwlan will not attempt to connect to wifi.
862        wifi_pwd: WiFi network password. This is optional.
863
864    Returns:
865        True if success. False if fail.
866    """
867    toggle_airplane_mode(log, ad, False, strict_checking=False)
868    try:
869        toggle_volte(log, ad, True)
870        if not wait_for_network_generation(
871                log, ad, GEN_4G, voice_or_data=NETWORK_SERVICE_DATA):
872            if not ensure_network_generation(
873                    log, ad, GEN_4G, voice_or_data=NETWORK_SERVICE_DATA):
874                ad.log.error("Fail to ensure data in 4G")
875                return False
876    except Exception as e:
877        ad.log.error(e)
878        ad.droid.telephonyToggleDataConnection(True)
879    if wifi_ssid is not None:
880        if not ensure_wifi_connected(log, ad, wifi_ssid, wifi_pwd):
881            ad.log.error("Connect to WiFi failed.")
882            return False
883    if not set_wfc_mode(log, ad, WFC_MODE_CELLULAR_PREFERRED):
884        ad.log.error("Set WFC mode failed.")
885        return False
886    if not wait_for_not_network_rat(
887            log, ad, RAT_FAMILY_WLAN, voice_or_data=NETWORK_SERVICE_DATA):
888        ad.log.error("Data rat in iwlan mode.")
889        return False
890    elif not wait_for_wfc_disabled(log, ad, MAX_WAIT_TIME_WFC_ENABLED):
891        ad.log.error("Should report wifi calling disabled within %s.",
892                     MAX_WAIT_TIME_WFC_ENABLED)
893        return False
894    return True
895
896
897def phone_setup_data_for_subscription(log, ad, sub_id, network_generation):
898    """Setup Phone <sub_id> Data to <network_generation>
899
900    Args:
901        log: log object
902        ad: android device object
903        sub_id: subscription id
904        network_generation: network generation, e.g. GEN_2G, GEN_3G, GEN_4G, GEN_5G
905
906    Returns:
907        True if success, False if fail.
908    """
909    toggle_airplane_mode(log, ad, False, strict_checking=False)
910    set_wifi_to_default(log, ad)
911    if not set_wfc_mode(log, ad, WFC_MODE_DISABLED):
912        ad.log.error("Disable WFC failed.")
913        return False
914    if not ensure_network_generation_for_subscription(
915            log,
916            ad,
917            sub_id,
918            network_generation,
919            voice_or_data=NETWORK_SERVICE_DATA):
920        get_telephony_signal_strength(ad)
921        return False
922    return True
923
924
925def phone_setup_5g(log, ad):
926    """Setup Phone default data sub_id data to 5G.
927
928    Args:
929        log: log object
930        ad: android device object
931
932    Returns:
933        True if success, False if fail.
934    """
935    return phone_setup_5g_for_subscription(log, ad,
936                                           get_default_data_sub_id(ad))
937
938
939def phone_setup_5g_for_subscription(log, ad, sub_id):
940    """Setup Phone <sub_id> Data to 5G.
941
942    Args:
943        log: log object
944        ad: android device object
945        sub_id: subscription id
946
947    Returns:
948        True if success, False if fail.
949    """
950    return phone_setup_data_for_subscription(log, ad, sub_id, GEN_5G)
951
952
953def phone_setup_4g(log, ad):
954    """Setup Phone default data sub_id data to 4G.
955
956    Args:
957        log: log object
958        ad: android device object
959
960    Returns:
961        True if success, False if fail.
962    """
963    return phone_setup_4g_for_subscription(log, ad,
964                                           get_default_data_sub_id(ad))
965
966
967def phone_setup_4g_for_subscription(log, ad, sub_id):
968    """Setup Phone <sub_id> Data to 4G.
969
970    Args:
971        log: log object
972        ad: android device object
973        sub_id: subscription id
974
975    Returns:
976        True if success, False if fail.
977    """
978    return phone_setup_data_for_subscription(log, ad, sub_id, GEN_4G)
979
980
981def phone_setup_3g(log, ad):
982    """Setup Phone default data sub_id data to 3G.
983
984    Args:
985        log: log object
986        ad: android device object
987
988    Returns:
989        True if success, False if fail.
990    """
991    return phone_setup_3g_for_subscription(log, ad,
992                                           get_default_data_sub_id(ad))
993
994
995def phone_setup_3g_for_subscription(log, ad, sub_id):
996    """Setup Phone <sub_id> Data to 3G.
997
998    Args:
999        log: log object
1000        ad: android device object
1001        sub_id: subscription id
1002
1003    Returns:
1004        True if success, False if fail.
1005    """
1006    return phone_setup_data_for_subscription(log, ad, sub_id, GEN_3G)
1007
1008
1009def phone_setup_2g(log, ad):
1010    """Setup Phone default data sub_id data to 2G.
1011
1012    Args:
1013        log: log object
1014        ad: android device object
1015
1016    Returns:
1017        True if success, False if fail.
1018    """
1019    return phone_setup_2g_for_subscription(log, ad,
1020                                           get_default_data_sub_id(ad))
1021
1022
1023def phone_setup_2g_for_subscription(log, ad, sub_id):
1024    """Setup Phone <sub_id> Data to 3G.
1025
1026    Args:
1027        log: log object
1028        ad: android device object
1029        sub_id: subscription id
1030
1031    Returns:
1032        True if success, False if fail.
1033    """
1034    return phone_setup_data_for_subscription(log, ad, sub_id, GEN_2G)
1035
1036
1037def phone_setup_csfb(log, ad):
1038    """Setup phone for CSFB call test.
1039
1040    Setup Phone to be in 4G mode.
1041    Disabled VoLTE.
1042
1043    Args:
1044        log: log object
1045        ad: Android device object.
1046
1047    Returns:
1048        True if setup successfully.
1049        False for errors.
1050    """
1051    return phone_setup_csfb_for_subscription(log, ad,
1052                                             get_outgoing_voice_sub_id(ad))
1053
1054
1055def phone_setup_csfb_for_subscription(log, ad, sub_id):
1056    """Setup phone for CSFB call test for subscription id.
1057
1058    Setup Phone to be in 4G mode.
1059    Disabled VoLTE.
1060
1061    Args:
1062        log: log object
1063        ad: Android device object.
1064        sub_id: subscription id.
1065
1066    Returns:
1067        True if setup successfully.
1068        False for errors.
1069    """
1070    capabilities = ad.telephony["subscription"][sub_id].get("capabilities", [])
1071    if capabilities:
1072        if "hide_enhanced_4g_lte" in capabilities:
1073            show_enhanced_4g_lte_mode = getattr(ad, "show_enhanced_4g_lte_mode", False)
1074            if show_enhanced_4g_lte_mode in ["false", "False", False]:
1075                ad.log.warning("'VoLTE' option is hidden. Test will be skipped.")
1076                raise signals.TestSkip("'VoLTE' option is hidden. Test will be skipped.")
1077    if not phone_setup_4g_for_subscription(log, ad, sub_id):
1078        ad.log.error("Failed to set to 4G data.")
1079        return False
1080    if ad.droid.imsIsEnhanced4gLteModeSettingEnabledByPlatform():
1081        toggle_volte(log, ad, False)
1082    if not ensure_network_generation_for_subscription(
1083            log, ad, sub_id, GEN_4G, voice_or_data=NETWORK_SERVICE_DATA):
1084        return False
1085
1086    if not wait_for_voice_attach_for_subscription(log, ad, sub_id,
1087                                                  MAX_WAIT_TIME_NW_SELECTION):
1088        return False
1089
1090    return phone_idle_csfb_for_subscription(log, ad, sub_id)
1091
1092
1093def phone_setup_volte(log, ad):
1094    """Setup VoLTE enable.
1095
1096    Args:
1097        log: log object
1098        ad: android device object.
1099
1100    Returns:
1101        True: if VoLTE is enabled successfully.
1102        False: for errors
1103    """
1104    if not get_capability_for_subscription(ad, CAPABILITY_VOLTE,
1105        get_outgoing_voice_sub_id(ad)):
1106        ad.log.error("VoLTE is not supported, abort test.")
1107        raise signals.TestSkip("VoLTE is not supported, abort test.")
1108    return phone_setup_volte_for_subscription(log, ad,
1109                                              get_outgoing_voice_sub_id(ad))
1110
1111
1112def phone_setup_volte_for_subscription(log, ad, sub_id):
1113    """Setup VoLTE enable for subscription id.
1114
1115    Args:
1116        log: log object
1117        ad: android device object.
1118        sub_id: subscription id.
1119
1120    Returns:
1121        True: if VoLTE is enabled successfully.
1122        False: for errors
1123    """
1124    if not phone_setup_4g_for_subscription(log, ad, sub_id):
1125        ad.log.error("Failed to set to 4G data.")
1126        return False
1127    if not wait_for_enhanced_4g_lte_setting(log, ad):
1128        ad.log.error("Enhanced 4G LTE setting is not available")
1129        return False
1130    toggle_volte_for_subscription(log, ad, sub_id, True)
1131    return phone_idle_volte_for_subscription(log, ad, sub_id)
1132
1133
1134def phone_setup_voice_3g(log, ad):
1135    """Setup phone voice to 3G.
1136
1137    Args:
1138        log: log object
1139        ad: Android device object.
1140
1141    Returns:
1142        True if setup successfully.
1143        False for errors.
1144    """
1145    return phone_setup_voice_3g_for_subscription(log, ad,
1146                                                 get_outgoing_voice_sub_id(ad))
1147
1148
1149def phone_setup_voice_3g_for_subscription(log, ad, sub_id):
1150    """Setup phone voice to 3G for subscription id.
1151
1152    Args:
1153        log: log object
1154        ad: Android device object.
1155        sub_id: subscription id.
1156
1157    Returns:
1158        True if setup successfully.
1159        False for errors.
1160    """
1161    if not phone_setup_3g_for_subscription(log, ad, sub_id):
1162        ad.log.error("Failed to set to 3G data.")
1163        return False
1164    if not wait_for_voice_attach_for_subscription(log, ad, sub_id,
1165                                                  MAX_WAIT_TIME_NW_SELECTION):
1166        return False
1167    return phone_idle_3g_for_subscription(log, ad, sub_id)
1168
1169
1170def phone_setup_voice_2g(log, ad):
1171    """Setup phone voice to 2G.
1172
1173    Args:
1174        log: log object
1175        ad: Android device object.
1176
1177    Returns:
1178        True if setup successfully.
1179        False for errors.
1180    """
1181    return phone_setup_voice_2g_for_subscription(log, ad,
1182                                                 get_outgoing_voice_sub_id(ad))
1183
1184
1185def phone_setup_voice_2g_for_subscription(log, ad, sub_id):
1186    """Setup phone voice to 2G for subscription id.
1187
1188    Args:
1189        log: log object
1190        ad: Android device object.
1191        sub_id: subscription id.
1192
1193    Returns:
1194        True if setup successfully.
1195        False for errors.
1196    """
1197    if not phone_setup_2g_for_subscription(log, ad, sub_id):
1198        ad.log.error("Failed to set to 2G data.")
1199        return False
1200    if not wait_for_voice_attach_for_subscription(log, ad, sub_id,
1201                                                  MAX_WAIT_TIME_NW_SELECTION):
1202        return False
1203    return phone_idle_2g_for_subscription(log, ad, sub_id)
1204
1205
1206def phone_setup_voice_general(log, ad):
1207    """Setup phone for voice general call test.
1208
1209    Make sure phone attached to voice.
1210    Make necessary delay.
1211
1212    Args:
1213        ad: Android device object.
1214
1215    Returns:
1216        True if setup successfully.
1217        False for errors.
1218    """
1219    return phone_setup_voice_general_for_subscription(
1220        log, ad, get_outgoing_voice_sub_id(ad))
1221
1222
1223def phone_setup_voice_general_for_slot(log,ad,slot_id):
1224    return phone_setup_voice_general_for_subscription(
1225        log, ad, get_subid_from_slot_index(log,ad,slot_id))
1226
1227
1228def phone_setup_voice_general_for_subscription(log, ad, sub_id):
1229    """Setup phone for voice general call test for subscription id.
1230
1231    Make sure phone attached to voice.
1232    Make necessary delay.
1233
1234    Args:
1235        ad: Android device object.
1236        sub_id: subscription id.
1237
1238    Returns:
1239        True if setup successfully.
1240        False for errors.
1241    """
1242    toggle_airplane_mode(log, ad, False, strict_checking=False)
1243    if not wait_for_voice_attach_for_subscription(log, ad, sub_id,
1244                                                  MAX_WAIT_TIME_NW_SELECTION):
1245        # if phone can not attach voice, try phone_setup_voice_3g
1246        return phone_setup_voice_3g_for_subscription(log, ad, sub_id)
1247    return True
1248
1249
1250def phone_setup_data_general(log, ad):
1251    """Setup phone for data general test.
1252
1253    Make sure phone attached to data.
1254    Make necessary delay.
1255
1256    Args:
1257        ad: Android device object.
1258
1259    Returns:
1260        True if setup successfully.
1261        False for errors.
1262    """
1263    return phone_setup_data_general_for_subscription(
1264        log, ad, ad.droid.subscriptionGetDefaultDataSubId())
1265
1266
1267def phone_setup_data_general_for_subscription(log, ad, sub_id):
1268    """Setup phone for data general test for subscription id.
1269
1270    Make sure phone attached to data.
1271    Make necessary delay.
1272
1273    Args:
1274        ad: Android device object.
1275        sub_id: subscription id.
1276
1277    Returns:
1278        True if setup successfully.
1279        False for errors.
1280    """
1281    toggle_airplane_mode(log, ad, False, strict_checking=False)
1282    if not wait_for_data_attach_for_subscription(log, ad, sub_id,
1283                                                 MAX_WAIT_TIME_NW_SELECTION):
1284        # if phone can not attach data, try reset network preference settings
1285        reset_preferred_network_type_to_allowable_range(log, ad)
1286
1287    return wait_for_data_attach_for_subscription(log, ad, sub_id,
1288                                                 MAX_WAIT_TIME_NW_SELECTION)
1289
1290
1291def phone_setup_rat_for_subscription(log, ad, sub_id, network_preference,
1292                                     rat_family):
1293    toggle_airplane_mode(log, ad, False, strict_checking=False)
1294    set_wifi_to_default(log, ad)
1295    if not set_wfc_mode(log, ad, WFC_MODE_DISABLED):
1296        ad.log.error("Disable WFC failed.")
1297        return False
1298    return ensure_network_rat_for_subscription(log, ad, sub_id,
1299                                               network_preference, rat_family)
1300
1301
1302def phone_setup_lte_gsm_wcdma(log, ad):
1303    return phone_setup_lte_gsm_wcdma_for_subscription(
1304        log, ad, ad.droid.subscriptionGetDefaultSubId())
1305
1306
1307def phone_setup_lte_gsm_wcdma_for_subscription(log, ad, sub_id):
1308    return phone_setup_rat_for_subscription(
1309        log, ad, sub_id, NETWORK_MODE_LTE_GSM_WCDMA, RAT_FAMILY_LTE)
1310
1311
1312def phone_setup_gsm_umts(log, ad):
1313    return phone_setup_gsm_umts_for_subscription(
1314        log, ad, ad.droid.subscriptionGetDefaultSubId())
1315
1316
1317def phone_setup_gsm_umts_for_subscription(log, ad, sub_id):
1318    return phone_setup_rat_for_subscription(
1319        log, ad, sub_id, NETWORK_MODE_GSM_UMTS, RAT_FAMILY_WCDMA)
1320
1321
1322def phone_setup_gsm_only(log, ad):
1323    return phone_setup_gsm_only_for_subscription(
1324        log, ad, ad.droid.subscriptionGetDefaultSubId())
1325
1326
1327def phone_setup_gsm_only_for_subscription(log, ad, sub_id):
1328    return phone_setup_rat_for_subscription(
1329        log, ad, sub_id, NETWORK_MODE_GSM_ONLY, RAT_FAMILY_GSM)
1330
1331
1332def phone_setup_lte_cdma_evdo(log, ad):
1333    return phone_setup_lte_cdma_evdo_for_subscription(
1334        log, ad, ad.droid.subscriptionGetDefaultSubId())
1335
1336
1337def phone_setup_lte_cdma_evdo_for_subscription(log, ad, sub_id):
1338    return phone_setup_rat_for_subscription(
1339        log, ad, sub_id, NETWORK_MODE_LTE_CDMA_EVDO, RAT_FAMILY_LTE)
1340
1341
1342def phone_setup_cdma(log, ad):
1343    return phone_setup_cdma_for_subscription(
1344        log, ad, ad.droid.subscriptionGetDefaultSubId())
1345
1346
1347def phone_setup_cdma_for_subscription(log, ad, sub_id):
1348    return phone_setup_rat_for_subscription(log, ad, sub_id, NETWORK_MODE_CDMA,
1349                                            RAT_FAMILY_CDMA2000)
1350
1351
1352def phone_idle_volte(log, ad):
1353    """Return if phone is idle for VoLTE call test.
1354
1355    Args:
1356        ad: Android device object.
1357    """
1358    return phone_idle_volte_for_subscription(log, ad,
1359                                             get_outgoing_voice_sub_id(ad))
1360
1361
1362def phone_idle_volte_for_subscription(log, ad, sub_id):
1363    """Return if phone is idle for VoLTE call test for subscription id.
1364
1365    Args:
1366        ad: Android device object.
1367        sub_id: subscription id.
1368    """
1369    if not wait_for_network_rat_for_subscription(
1370            log, ad, sub_id, RAT_FAMILY_LTE,
1371            voice_or_data=NETWORK_SERVICE_VOICE):
1372        ad.log.error("Voice rat not in LTE mode.")
1373        return False
1374    if not wait_for_volte_enabled(log, ad, MAX_WAIT_TIME_VOLTE_ENABLED):
1375        ad.log.error(
1376            "Failed to <report volte enabled true> within %s seconds.",
1377            MAX_WAIT_TIME_VOLTE_ENABLED)
1378        return False
1379    return True
1380
1381
1382def phone_idle_iwlan(log, ad):
1383    """Return if phone is idle for WiFi calling call test.
1384
1385    Args:
1386        ad: Android device object.
1387    """
1388    return phone_idle_iwlan_for_subscription(log, ad,
1389                                             get_outgoing_voice_sub_id(ad))
1390
1391
1392def phone_idle_iwlan_for_subscription(log, ad, sub_id):
1393    """Return if phone is idle for WiFi calling call test for subscription id.
1394
1395    Args:
1396        ad: Android device object.
1397        sub_id: subscription id.
1398    """
1399    if not wait_for_wfc_enabled(log, ad, MAX_WAIT_TIME_WFC_ENABLED):
1400        ad.log.error("Failed to <report wfc enabled true> within %s seconds.",
1401                     MAX_WAIT_TIME_WFC_ENABLED)
1402        return False
1403    return True
1404
1405
1406def phone_idle_not_iwlan(log, ad):
1407    """Return if phone is idle for non WiFi calling call test.
1408
1409    Args:
1410        ad: Android device object.
1411    """
1412    return phone_idle_not_iwlan_for_subscription(log, ad,
1413                                                 get_outgoing_voice_sub_id(ad))
1414
1415
1416def phone_idle_not_iwlan_for_subscription(log, ad, sub_id):
1417    """Return if phone is idle for non WiFi calling call test for sub id.
1418
1419    Args:
1420        ad: Android device object.
1421        sub_id: subscription id.
1422    """
1423    if not wait_for_not_network_rat_for_subscription(
1424            log, ad, sub_id, RAT_FAMILY_WLAN,
1425            voice_or_data=NETWORK_SERVICE_DATA):
1426        log.error("{} data rat in iwlan mode.".format(ad.serial))
1427        return False
1428    return True
1429
1430
1431def phone_idle_csfb(log, ad):
1432    """Return if phone is idle for CSFB call test.
1433
1434    Args:
1435        ad: Android device object.
1436    """
1437    return phone_idle_csfb_for_subscription(log, ad,
1438                                            get_outgoing_voice_sub_id(ad))
1439
1440
1441def phone_idle_csfb_for_subscription(log, ad, sub_id):
1442    """Return if phone is idle for CSFB call test for subscription id.
1443
1444    Args:
1445        ad: Android device object.
1446        sub_id: subscription id.
1447    """
1448    if not wait_for_network_rat_for_subscription(
1449            log, ad, sub_id, RAT_FAMILY_LTE,
1450            voice_or_data=NETWORK_SERVICE_DATA):
1451        ad.log.error("Data rat not in lte mode.")
1452        return False
1453    return True
1454
1455
1456def phone_idle_3g(log, ad):
1457    """Return if phone is idle for 3G call test.
1458
1459    Args:
1460        ad: Android device object.
1461    """
1462    return phone_idle_3g_for_subscription(log, ad,
1463                                          get_outgoing_voice_sub_id(ad))
1464
1465
1466def phone_idle_3g_for_subscription(log, ad, sub_id):
1467    """Return if phone is idle for 3G call test for subscription id.
1468
1469    Args:
1470        ad: Android device object.
1471        sub_id: subscription id.
1472    """
1473    return wait_for_network_generation_for_subscription(
1474        log, ad, sub_id, GEN_3G, voice_or_data=NETWORK_SERVICE_VOICE)
1475
1476
1477def phone_idle_2g(log, ad):
1478    """Return if phone is idle for 2G call test.
1479
1480    Args:
1481        ad: Android device object.
1482    """
1483    return phone_idle_2g_for_subscription(log, ad,
1484                                          get_outgoing_voice_sub_id(ad))
1485
1486
1487def phone_idle_2g_for_subscription(log, ad, sub_id):
1488    """Return if phone is idle for 2G call test for subscription id.
1489
1490    Args:
1491        ad: Android device object.
1492        sub_id: subscription id.
1493    """
1494    return wait_for_network_generation_for_subscription(
1495        log, ad, sub_id, GEN_2G, voice_or_data=NETWORK_SERVICE_VOICE)
1496
1497
1498def get_current_voice_rat(log, ad):
1499    """Return current Voice RAT
1500
1501    Args:
1502        ad: Android device object.
1503    """
1504    return get_current_voice_rat_for_subscription(
1505        log, ad, get_outgoing_voice_sub_id(ad))
1506
1507
1508def get_current_voice_rat_for_subscription(log, ad, sub_id):
1509    """Return current Voice RAT for subscription id.
1510
1511    Args:
1512        ad: Android device object.
1513        sub_id: subscription id.
1514    """
1515    return get_network_rat_for_subscription(log, ad, sub_id,
1516                                            NETWORK_SERVICE_VOICE)
1517
1518
1519def is_phone_in_call_volte(log, ad):
1520    """Return if phone is in VoLTE call.
1521
1522    Args:
1523        ad: Android device object.
1524    """
1525    return is_phone_in_call_volte_for_subscription(
1526        log, ad, get_outgoing_voice_sub_id(ad))
1527
1528
1529def is_phone_in_call_volte_for_subscription(log, ad, sub_id):
1530    """Return if phone is in VoLTE call for subscription id.
1531
1532    Args:
1533        ad: Android device object.
1534        sub_id: subscription id.
1535    """
1536    if not ad.droid.telecomIsInCall():
1537        ad.log.error("Not in call.")
1538        return False
1539    nw_type = get_network_rat_for_subscription(log, ad, sub_id,
1540                                               NETWORK_SERVICE_VOICE)
1541    if nw_type != RAT_LTE:
1542        ad.log.error("Voice rat on: %s. Expected: LTE", nw_type)
1543        return False
1544    return True
1545
1546
1547def is_phone_in_call_csfb(log, ad):
1548    """Return if phone is in CSFB call.
1549
1550    Args:
1551        ad: Android device object.
1552    """
1553    return is_phone_in_call_csfb_for_subscription(
1554        log, ad, get_outgoing_voice_sub_id(ad))
1555
1556
1557def is_phone_in_call_csfb_for_subscription(log, ad, sub_id):
1558    """Return if phone is in CSFB call for subscription id.
1559
1560    Args:
1561        ad: Android device object.
1562        sub_id: subscription id.
1563    """
1564    if not ad.droid.telecomIsInCall():
1565        ad.log.error("Not in call.")
1566        return False
1567    nw_type = get_network_rat_for_subscription(log, ad, sub_id,
1568                                               NETWORK_SERVICE_VOICE)
1569    if nw_type == RAT_LTE:
1570        ad.log.error("Voice rat on: %s. Expected: not LTE", nw_type)
1571        return False
1572    return True
1573
1574
1575def is_phone_in_call_3g(log, ad):
1576    """Return if phone is in 3G call.
1577
1578    Args:
1579        ad: Android device object.
1580    """
1581    return is_phone_in_call_3g_for_subscription(log, ad,
1582                                                get_outgoing_voice_sub_id(ad))
1583
1584
1585def is_phone_in_call_3g_for_subscription(log, ad, sub_id):
1586    """Return if phone is in 3G call for subscription id.
1587
1588    Args:
1589        ad: Android device object.
1590        sub_id: subscription id.
1591    """
1592    if not ad.droid.telecomIsInCall():
1593        ad.log.error("Not in call.")
1594        return False
1595    nw_gen = get_network_gen_for_subscription(log, ad, sub_id,
1596                                              NETWORK_SERVICE_VOICE)
1597    if nw_gen != GEN_3G:
1598        ad.log.error("Voice rat on: %s. Expected: 3g", nw_gen)
1599        return False
1600    return True
1601
1602
1603def is_phone_in_call_2g(log, ad):
1604    """Return if phone is in 2G call.
1605
1606    Args:
1607        ad: Android device object.
1608    """
1609    return is_phone_in_call_2g_for_subscription(log, ad,
1610                                                get_outgoing_voice_sub_id(ad))
1611
1612
1613def is_phone_in_call_2g_for_subscription(log, ad, sub_id):
1614    """Return if phone is in 2G call for subscription id.
1615
1616    Args:
1617        ad: Android device object.
1618        sub_id: subscription id.
1619    """
1620    if not ad.droid.telecomIsInCall():
1621        ad.log.error("Not in call.")
1622        return False
1623    nw_gen = get_network_gen_for_subscription(log, ad, sub_id,
1624                                              NETWORK_SERVICE_VOICE)
1625    if nw_gen != GEN_2G:
1626        ad.log.error("Voice rat on: %s. Expected: 2g", nw_gen)
1627        return False
1628    return True
1629
1630
1631def is_phone_in_call_1x(log, ad):
1632    """Return if phone is in 1x call.
1633
1634    Args:
1635        ad: Android device object.
1636    """
1637    return is_phone_in_call_1x_for_subscription(log, ad,
1638                                                get_outgoing_voice_sub_id(ad))
1639
1640
1641def is_phone_in_call_1x_for_subscription(log, ad, sub_id):
1642    """Return if phone is in 1x call for subscription id.
1643
1644    Args:
1645        ad: Android device object.
1646        sub_id: subscription id.
1647    """
1648    if not ad.droid.telecomIsInCall():
1649        ad.log.error("Not in call.")
1650        return False
1651    nw_type = get_network_rat_for_subscription(log, ad, sub_id,
1652                                               NETWORK_SERVICE_VOICE)
1653    if nw_type != RAT_1XRTT:
1654        ad.log.error("Voice rat on: %s. Expected: 1xrtt", nw_type)
1655        return False
1656    return True
1657
1658
1659def is_phone_in_call_wcdma(log, ad):
1660    """Return if phone is in WCDMA call.
1661
1662    Args:
1663        ad: Android device object.
1664    """
1665    return is_phone_in_call_wcdma_for_subscription(
1666        log, ad, get_outgoing_voice_sub_id(ad))
1667
1668
1669def is_phone_in_call_wcdma_for_subscription(log, ad, sub_id):
1670    """Return if phone is in WCDMA call for subscription id.
1671
1672    Args:
1673        ad: Android device object.
1674        sub_id: subscription id.
1675    """
1676    # Currently checking 'umts'.
1677    # Changes may needed in the future.
1678    if not ad.droid.telecomIsInCall():
1679        ad.log.error("Not in call.")
1680        return False
1681    nw_type = get_network_rat_for_subscription(log, ad, sub_id,
1682                                               NETWORK_SERVICE_VOICE)
1683    if nw_type != RAT_UMTS:
1684        ad.log.error("%s voice rat on: %s. Expected: umts", nw_type)
1685        return False
1686    return True
1687
1688
1689def is_phone_in_call_iwlan(log, ad, call_id=None):
1690    """Return if phone is in WiFi call.
1691
1692    Args:
1693        ad: Android device object.
1694    """
1695    if not ad.droid.telecomIsInCall():
1696        ad.log.error("Not in call.")
1697        return False
1698    if not ad.droid.telephonyIsImsRegistered():
1699        ad.log.info("IMS is not registered.")
1700        return False
1701    if not ad.droid.telephonyIsWifiCallingAvailable():
1702        ad.log.info("IsWifiCallingAvailble is False")
1703        return False
1704    if not call_id:
1705        call_ids = ad.droid.telecomCallGetCallIds()
1706        if call_ids:
1707            call_id = call_ids[-1]
1708    if not call_id:
1709        ad.log.error("Failed to get call id")
1710        return False
1711    else:
1712        call_prop = ad.droid.telecomCallGetProperties(call_id)
1713        if "WIFI" not in call_prop:
1714            ad.log.info("callProperties = %s, expecting WIFI", call_prop)
1715            return False
1716    nw_type = get_network_rat(log, ad, NETWORK_SERVICE_DATA)
1717    if nw_type != RAT_IWLAN:
1718        ad.log.warning("Data rat on: %s. Expected: iwlan", nw_type)
1719    return True
1720
1721
1722def is_phone_in_call_not_iwlan(log, ad):
1723    """Return if phone is in WiFi call for subscription id.
1724
1725    Args:
1726        ad: Android device object.
1727        sub_id: subscription id.
1728    """
1729    if not ad.droid.telecomIsInCall():
1730        ad.log.error("Not in call.")
1731        return False
1732    nw_type = get_network_rat(log, ad, NETWORK_SERVICE_DATA)
1733    if nw_type == RAT_IWLAN:
1734        ad.log.error("Data rat on: %s. Expected: not iwlan", nw_type)
1735        return False
1736    if is_wfc_enabled(log, ad):
1737        ad.log.error("WiFi Calling feature bit is True.")
1738        return False
1739    return True
1740
1741
1742def swap_calls(log,
1743               ads,
1744               call_hold_id,
1745               call_active_id,
1746               num_swaps=1,
1747               check_call_status=True):
1748    """PhoneA in call with B and C. Swap active/holding call on PhoneA.
1749
1750    Swap call and check status on PhoneA.
1751        (This step may have multiple times according to 'num_swaps'.)
1752    Check if all 3 phones are 'in-call'.
1753
1754    Args:
1755        ads: list of ad object, at least three need to pass in.
1756            Swap operation will happen on ads[0].
1757            ads[1] and ads[2] are call participants.
1758        call_hold_id: id for the holding call in ads[0].
1759            call_hold_id should be 'STATE_HOLDING' when calling this function.
1760        call_active_id: id for the active call in ads[0].
1761            call_active_id should be 'STATE_ACTIVE' when calling this function.
1762        num_swaps: how many swap/check operations will be done before return.
1763        check_call_status: This is optional. Default value is True.
1764            If this value is True, then call status (active/hold) will be
1765            be checked after each swap operation.
1766
1767    Returns:
1768        If no error happened, return True, otherwise, return False.
1769    """
1770    if check_call_status:
1771        # Check status before swap.
1772        if ads[0].droid.telecomCallGetCallState(
1773                call_active_id) != CALL_STATE_ACTIVE:
1774            ads[0].log.error(
1775                "Call_id:%s, state:%s, expected: STATE_ACTIVE", call_active_id,
1776                ads[0].droid.telecomCallGetCallState(call_active_id))
1777            return False
1778        if ads[0].droid.telecomCallGetCallState(
1779                call_hold_id) != CALL_STATE_HOLDING:
1780            ads[0].log.error(
1781                "Call_id:%s, state:%s, expected: STATE_HOLDING", call_hold_id,
1782                ads[0].droid.telecomCallGetCallState(call_hold_id))
1783            return False
1784
1785    i = 1
1786    while (i <= num_swaps):
1787        ads[0].log.info("swap_test %s: swap and check call status.", i)
1788        ads[0].droid.telecomCallHold(call_active_id)
1789        time.sleep(WAIT_TIME_IN_CALL)
1790        # Swap object reference
1791        call_active_id, call_hold_id = call_hold_id, call_active_id
1792        if check_call_status:
1793            # Check status
1794            if ads[0].droid.telecomCallGetCallState(
1795                    call_active_id) != CALL_STATE_ACTIVE:
1796                ads[0].log.error(
1797                    "Call_id:%s, state:%s, expected: STATE_ACTIVE",
1798                    call_active_id,
1799                    ads[0].droid.telecomCallGetCallState(call_active_id))
1800                return False
1801            if ads[0].droid.telecomCallGetCallState(
1802                    call_hold_id) != CALL_STATE_HOLDING:
1803                ads[0].log.error(
1804                    "Call_id:%s, state:%s, expected: STATE_HOLDING",
1805                    call_hold_id,
1806                    ads[0].droid.telecomCallGetCallState(call_hold_id))
1807                return False
1808        # TODO: b/26296375 add voice check.
1809
1810        i += 1
1811
1812    #In the end, check all three phones are 'in-call'.
1813    if not verify_incall_state(log, [ads[0], ads[1], ads[2]], True):
1814        return False
1815
1816    return True
1817
1818
1819def get_audio_route(log, ad):
1820    """Gets the audio route for the active call
1821
1822    Args:
1823        log: logger object
1824        ad: android_device object
1825
1826    Returns:
1827        Audio route string ["BLUETOOTH", "EARPIECE", "SPEAKER", "WIRED_HEADSET"
1828            "WIRED_OR_EARPIECE"]
1829    """
1830
1831    audio_state = ad.droid.telecomCallGetAudioState()
1832    return audio_state["AudioRoute"]
1833
1834
1835def set_audio_route(log, ad, route):
1836    """Sets the audio route for the active call
1837
1838    Args:
1839        log: logger object
1840        ad: android_device object
1841        route: string ["BLUETOOTH", "EARPIECE", "SPEAKER", "WIRED_HEADSET"
1842            "WIRED_OR_EARPIECE"]
1843
1844    Returns:
1845        If no error happened, return True, otherwise, return False.
1846    """
1847    ad.droid.telecomCallSetAudioRoute(route)
1848    return True
1849
1850
1851def is_property_in_call_properties(log, ad, call_id, expected_property):
1852    """Return if the call_id has the expected property
1853
1854    Args:
1855        log: logger object
1856        ad: android_device object
1857        call_id: call id.
1858        expected_property: expected property.
1859
1860    Returns:
1861        True if call_id has expected_property. False if not.
1862    """
1863    properties = ad.droid.telecomCallGetProperties(call_id)
1864    return (expected_property in properties)
1865
1866
1867def is_call_hd(log, ad, call_id):
1868    """Return if the call_id is HD call.
1869
1870    Args:
1871        log: logger object
1872        ad: android_device object
1873        call_id: call id.
1874
1875    Returns:
1876        True if call_id is HD call. False if not.
1877    """
1878    return is_property_in_call_properties(log, ad, call_id,
1879                                          CALL_PROPERTY_HIGH_DEF_AUDIO)
1880
1881
1882def get_cep_conference_call_id(ad):
1883    """Get CEP conference call id if there is an ongoing CEP conference call.
1884
1885    Args:
1886        ad: android device object.
1887
1888    Returns:
1889        call id for CEP conference call if there is an ongoing CEP conference call.
1890        None otherwise.
1891    """
1892    for call in ad.droid.telecomCallGetCallIds():
1893        if len(ad.droid.telecomCallGetCallChildren(call)) != 0:
1894            return call
1895    return None
1896