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