1#/usr/bin/env python3.4
2#
3#   Copyright 2016 - The Android Open Source Project
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 queue import Empty
19from datetime import datetime
20
21from acts.controllers.anritsu_lib._anritsu_utils import AnritsuUtils
22from acts.controllers.anritsu_lib.md8475a import BtsNumber
23from acts.controllers.anritsu_lib.md8475a import BtsNwNameEnable
24from acts.controllers.anritsu_lib.md8475a import BtsServiceState
25from acts.controllers.anritsu_lib.md8475a import BtsTechnology
26from acts.controllers.anritsu_lib.md8475a import CsfbType
27from acts.controllers.anritsu_lib.md8475a import ImsCscfCall
28from acts.controllers.anritsu_lib.md8475a import ImsCscfStatus
29from acts.controllers.anritsu_lib.md8475a import MD8475A
30from acts.controllers.anritsu_lib.md8475a import ReturnToEUTRAN
31from acts.controllers.anritsu_lib.md8475a import VirtualPhoneStatus
32from acts.controllers.anritsu_lib.md8475a import TestProcedure
33from acts.controllers.anritsu_lib.md8475a import TestPowerControl
34from acts.controllers.anritsu_lib.md8475a import TestMeasurement
35from acts.controllers.anritsu_lib.md8475a import Switch
36from acts.controllers.anritsu_lib.md8475a import BtsPacketRate
37from acts.test_utils.tel.tel_defines import CALL_TEARDOWN_PHONE
38from acts.test_utils.tel.tel_defines import CALL_TEARDOWN_REMOTE
39from acts.test_utils.tel.tel_defines import MAX_WAIT_TIME_CALL_DROP
40from acts.test_utils.tel.tel_defines import RAT_1XRTT
41from acts.test_utils.tel.tel_defines import WAIT_TIME_IN_CALL
42from acts.test_utils.tel.tel_defines import WAIT_TIME_IN_CALL_FOR_IMS
43from acts.test_utils.tel.tel_defines import EventCmasReceived
44from acts.test_utils.tel.tel_defines import EventEtwsReceived
45from acts.test_utils.tel.tel_defines import EventSmsDeliverSuccess
46from acts.test_utils.tel.tel_defines import EventSmsSentSuccess
47from acts.test_utils.tel.tel_defines import EventSmsReceived
48from acts.test_utils.tel.tel_test_utils import ensure_phone_idle
49from acts.test_utils.tel.tel_test_utils import hangup_call
50from acts.test_utils.tel.tel_test_utils import initiate_call
51from acts.test_utils.tel.tel_test_utils import wait_and_answer_call
52from acts.test_utils.tel.tel_test_utils import wait_for_droid_not_in_call
53
54# Timers
55# Time to wait after registration before sending a command to Anritsu
56# to ensure the phone has sufficient time to reconfigure based on new
57# network in Anritsu
58WAIT_TIME_ANRITSU_REG_AND_OPER = 10
59# Time to wait after registration to ensure the phone
60# has sufficient time to reconfigure based on new network in Anritsu
61WAIT_TIME_ANRITSU_REG_AND_CALL = 10
62# Max time to wait for Anritsu's virtual phone state change
63MAX_WAIT_TIME_VIRTUAL_PHONE_STATE = 45
64# Time to wait for Anritsu's IMS CSCF state change
65MAX_WAIT_TIME_IMS_CSCF_STATE = 30
66# Time to wait for before aSRVCC
67WAIT_TIME_IN_ALERT = 5
68
69# SIM card names
70P0250Ax = "P0250Ax"
71VzW12349 = "VzW12349"
72P0135Ax = "P0135Ax"
73
74# Test PLMN information
75TEST_PLMN_LTE_NAME = "MD8475A_LTE"
76TEST_PLMN_WCDMA_NAME = "MD8475A_WCDMA"
77TEST_PLMN_GSM_NAME = "MD8475A_GSM"
78TEST_PLMN_1X_NAME = "MD8475A_1X"
79TEST_PLMN_1_MCC = "001"
80TEST_PLMN_1_MNC = "01"
81DEFAULT_MCC = "310"
82DEFAULT_MNC = "260"
83DEFAULT_RAC = 1
84DEFAULT_LAC = 1
85VzW_MCC = "311"
86VzW_MNC = "480"
87TMO_MCC = "310"
88TMO_MNC = "260"
89
90# IP address information for internet sharing
91#GATEWAY_IPV4_ADDR = "192.168.137.1"
92#UE_IPV4_ADDR_1 = "192.168.137.2"
93#UE_IPV4_ADDR_2 = "192.168.137.3"
94#UE_IPV4_ADDR_3 = "192.168.137.4"
95#DNS_IPV4_ADDR = "192.168.137.1"
96#CSCF_IPV4_ADDR = "192.168.137.1"
97
98# Default IP address in Smart Studio, work for Internet Sharing with and
99# without WLAN ePDG server. Remember to add 192.168.1.2 to Ethernet 0
100# on MD8475A after turn on Windows' Internet Coonection Sharing
101GATEWAY_IPV4_ADDR = "192.168.1.2"
102UE_IPV4_ADDR_1 = "192.168.1.1"
103UE_IPV4_ADDR_2 = "192.168.1.11"
104UE_IPV4_ADDR_3 = "192.168.1.21"
105UE_IPV6_ADDR_1 = "2001:0:0:1::1"
106UE_IPV6_ADDR_2 = "2001:0:0:2::1"
107UE_IPV6_ADDR_3 = "2001:0:0:3::1"
108DNS_IPV4_ADDR = "192.168.1.12"
109CSCF_IPV4_ADDR = "192.168.1.2"
110CSCF_IPV6_ADDR = "2001:0:0:1::2"
111CSCF_IPV6_ADDR_2 = "2001:0:0:2::2"
112CSCF_IPV6_ADDR_3 = "2001:0:0:3::2"
113
114# GSM BAND constants
115GSM_BAND_GSM450 = "GSM450"
116GSM_BAND_GSM480 = "GSM480"
117GSM_BAND_GSM850 = "GSM850"
118GSM_BAND_PGSM900 = "P-GSM900"
119GSM_BAND_EGSM900 = "E-GSM900"
120GSM_BAND_RGSM900 = "R-GSM900"
121GSM_BAND_DCS1800 = "DCS1800"
122GSM_BAND_PCS1900 = "PCS1900"
123
124LTE_BAND_2 = 2
125LTE_BAND_4 = 4
126LTE_BAND_12 = 12
127WCDMA_BAND_1 = 1
128WCDMA_BAND_2 = 2
129
130# Default Cell Parameters
131DEFAULT_OUTPUT_LEVEL = -20
132DEFAULT_1X_OUTPUT_LEVEL = -35
133DEFAULT_INPUT_LEVEL = 0
134DEFAULT_LTE_BAND = [2, 4]
135DEFAULT_WCDMA_BAND = 1
136DEFAULT_WCDMA_PACKET_RATE = BtsPacketRate.WCDMA_DLHSAUTO_REL7_ULHSAUTO
137DEFAULT_GSM_BAND = GSM_BAND_GSM850
138DEFAULT_CDMA1X_BAND = 0
139DEFAULT_CDMA1X_CH = 356
140DEFAULT_CDMA1X_SID = 0
141DEFAULT_CDMA1X_NID = 65535
142DEFAULT_EVDO_BAND = 0
143DEFAULT_EVDO_CH = 356
144DEFAULT_EVDO_SECTOR_ID = "00000000,00000000,00000000,00000000"
145VzW_CDMA1x_BAND = 1
146VzW_CDMA1x_CH = 150
147VzW_CDMA1X_SID = 26
148VzW_CDMA1X_NID = 65535
149VzW_EVDO_BAND = 0
150VzW_EVDO_CH = 384
151VzW_EVDO_SECTOR_ID = "12345678,00000000,00000000,00000000"
152DEFAULT_T_MODE = "TM1"
153DEFAULT_DL_ANTENNA = 1
154
155# CMAS Message IDs
156CMAS_MESSAGE_PRESIDENTIAL_ALERT = hex(0x1112)
157CMAS_MESSAGE_EXTREME_IMMEDIATE_OBSERVED = hex(0x1113)
158CMAS_MESSAGE_EXTREME_IMMEDIATE_LIKELY = hex(0x1114)
159CMAS_MESSAGE_EXTREME_EXPECTED_OBSERVED = hex(0x1115)
160CMAS_MESSAGE_EXTREME_EXPECTED_LIKELY = hex(0x1116)
161CMAS_MESSAGE_SEVERE_IMMEDIATE_OBSERVED = hex(0x1117)
162CMAS_MESSAGE_SEVERE_IMMEDIATE_LIKELY = hex(0x1118)
163CMAS_MESSAGE_SEVERE_EXPECTED_OBSERVED = hex(0x1119)
164CMAS_MESSAGE_SEVERE_EXPECTED_LIKELY = hex(0x111A)
165CMAS_MESSAGE_CHILD_ABDUCTION_EMERGENCY = hex(0x111B)
166CMAS_MESSAGE_MONTHLY_TEST = hex(0x111C)
167CMAS_MESSAGE_CMAS_EXECERCISE = hex(0x111D)
168
169# ETWS Message IDs
170ETWS_WARNING_EARTHQUAKE = hex(0x1100)
171ETWS_WARNING_TSUNAMI = hex(0x1101)
172ETWS_WARNING_EARTHQUAKETSUNAMI = hex(0x1102)
173ETWS_WARNING_TEST_MESSAGE = hex(0x1103)
174ETWS_WARNING_OTHER_EMERGENCY = hex(0x1104)
175
176# C2K CMAS Message Constants
177CMAS_C2K_CATEGORY_PRESIDENTIAL = "Presidential"
178CMAS_C2K_CATEGORY_EXTREME = "Extreme"
179CMAS_C2K_CATEGORY_SEVERE = "Severe"
180CMAS_C2K_CATEGORY_AMBER = "AMBER"
181CMAS_C2K_CATEGORY_CMASTEST = "CMASTest"
182
183CMAS_C2K_PRIORITY_NORMAL = "Normal"
184CMAS_C2K_PRIORITY_INTERACTIVE = "Interactive"
185CMAS_C2K_PRIORITY_URGENT = "Urgent"
186CMAS_C2K_PRIORITY_EMERGENCY = "Emergency"
187
188CMAS_C2K_RESPONSETYPE_SHELTER = "Shelter"
189CMAS_C2K_RESPONSETYPE_EVACUATE = "Evacuate"
190CMAS_C2K_RESPONSETYPE_PREPARE = "Prepare"
191CMAS_C2K_RESPONSETYPE_EXECUTE = "Execute"
192CMAS_C2K_RESPONSETYPE_MONITOR = "Monitor"
193CMAS_C2K_RESPONSETYPE_AVOID = "Avoid"
194CMAS_C2K_RESPONSETYPE_ASSESS = "Assess"
195CMAS_C2K_RESPONSETYPE_NONE = "None"
196
197CMAS_C2K_SEVERITY_EXTREME = "Extreme"
198CMAS_C2K_SEVERITY_SEVERE = "Severe"
199
200CMAS_C2K_URGENCY_IMMEDIATE = "Immediate"
201CMAS_C2K_URGENCY_EXPECTED = "Expected"
202
203CMAS_C2K_CERTIANTY_OBSERVED = "Observed"
204CMAS_C2K_CERTIANTY_LIKELY = "Likely"
205
206#PDN Numbers
207PDN_NO_1 = 1
208PDN_NO_2 = 2
209PDN_NO_3 = 3
210
211# IMS Services parameters
212DEFAULT_VNID = 1
213NDP_NIC_NAME = '"Intel(R) 82577LM Gigabit Network Connection"'
214CSCF_Monitoring_UA_URI = '"sip:+11234567890@test.3gpp.com"'
215TMO_CSCF_Monitoring_UA_URI = '"sip:001010123456789@msg.lab.t-mobile.com"'
216CSCF_Virtual_UA_URI = '"sip:+11234567891@test.3gpp.com"'
217TMO_CSCF_Virtual_UA_URI = '"sip:0123456789@ims.mnc01.mcc001.3gppnetwork.org"'
218CSCF_HOSTNAME = '"ims.mnc01.mcc001.3gppnetwork.org"'
219TMO_USERLIST_NAME = "310260123456789@msg.lab.t-mobile.com"
220VZW_USERLIST_NAME = "001010123456789@test.3gpp.com"
221
222#Cell Numbers
223CELL_1 = 1
224CELL_2 = 2
225
226# default ims virtual network id for Anritsu ims call test.
227DEFAULT_IMS_VIRTUAL_NETWORK_ID = 1
228
229
230def cb_serial_number():
231    """ CMAS/ETWS serial number generator """
232    i = 0x3000
233    while True:
234        yield i
235        i += 1
236
237
238def set_usim_parameters(anritsu_handle, sim_card):
239    """ set USIM parameters in MD8475A simulationn parameter
240
241    Args:
242        anritsu_handle: anritusu device object.
243        sim_card : "P0250Ax" or "12349"
244
245    Returns:
246        None
247    """
248    if sim_card == P0250Ax:
249        anritsu_handle.usim_key = "000102030405060708090A0B0C0D0E0F"
250    elif sim_card == P0135Ax:
251        anritsu_handle.usim_key = "00112233445566778899AABBCCDDEEFF"
252    elif sim_card == VzW12349:
253        anritsu_handle.usim_key = "465B5CE8B199B49FAA5F0A2EE238A6BC"
254        anritsu_handle.send_command("IMSI 311480012345678")
255        anritsu_handle.send_command("SECURITY3G MILENAGE")
256        anritsu_handle.send_command(
257            "MILENAGEOP 5F1D289C5D354D0A140C2548F5F3E3BA")
258
259
260def save_anritsu_log_files(anritsu_handle, test_name, user_params):
261    """ saves the anritsu smart studio log files
262        The logs should be saved in Anritsu system. Need to provide
263        log folder path in Anritsu system
264
265    Args:
266        anritsu_handle: anritusu device object.
267        test_name: test case name
268        user_params : user supplied parameters list
269
270    Returns:
271        None
272    """
273    md8475a_log_folder = user_params["anritsu_log_file_path"]
274    file_name = getfilenamewithtimestamp(test_name)
275    seq_logfile = "{}\\{}_seq.csv".format(md8475a_log_folder, file_name)
276    msg_logfile = "{}\\{}_msg.csv".format(md8475a_log_folder, file_name)
277    trace_logfile = "{}\\{}_trace.lgex".format(md8475a_log_folder, file_name)
278    anritsu_handle.save_sequence_log(seq_logfile)
279    anritsu_handle.save_message_log(msg_logfile)
280    anritsu_handle.save_trace_log(trace_logfile, "BINARY", 1, 0, 0)
281    anritsu_handle.clear_sequence_log()
282    anritsu_handle.clear_message_log()
283
284
285def getfilenamewithtimestamp(test_name):
286    """ Gets the test name appended with current time
287
288    Args:
289        test_name : test case name
290
291    Returns:
292        string of test name appended with current time
293    """
294    time_stamp = datetime.now().strftime("%m-%d-%Y_%H-%M-%S")
295    return "{}_{}".format(test_name, time_stamp)
296
297
298def _init_lte_bts(bts, user_params, cell_no, sim_card):
299    """ initializes the LTE BTS
300        All BTS parameters should be set here
301
302    Args:
303        bts: BTS object.
304        user_params: pointer to user supplied parameters
305        cell_no: specify the cell number this BTS is configured
306        Anritsu supports two cells. so cell_1 or cell_2
307
308    Returns:
309        None
310    """
311    bts.nw_fullname_enable = BtsNwNameEnable.NAME_ENABLE
312    bts.nw_fullname = TEST_PLMN_LTE_NAME
313    bts.mcc = get_lte_mcc(user_params, cell_no, sim_card)
314    bts.mnc = get_lte_mnc(user_params, cell_no, sim_card)
315    bts.band = get_lte_band(user_params, cell_no)
316    bts.transmode = get_transmission_mode(user_params, cell_no)
317    bts.dl_antenna = get_dl_antenna(user_params, cell_no)
318    bts.output_level = DEFAULT_OUTPUT_LEVEL
319    bts.input_level = DEFAULT_INPUT_LEVEL
320
321
322def _init_wcdma_bts(bts, user_params, cell_no, sim_card):
323    """ initializes the WCDMA BTS
324        All BTS parameters should be set here
325
326    Args:
327        bts: BTS object.
328        user_params: pointer to user supplied parameters
329        cell_no: specify the cell number this BTS is configured
330        Anritsu supports two cells. so cell_1 or cell_2
331
332    Returns:
333        None
334    """
335    bts.nw_fullname_enable = BtsNwNameEnable.NAME_ENABLE
336    bts.nw_fullname = TEST_PLMN_WCDMA_NAME
337    bts.mcc = get_wcdma_mcc(user_params, cell_no, sim_card)
338    bts.mnc = get_wcdma_mnc(user_params, cell_no, sim_card)
339    bts.band = get_wcdma_band(user_params, cell_no)
340    bts.rac = get_wcdma_rac(user_params, cell_no)
341    bts.lac = get_wcdma_lac(user_params, cell_no)
342    bts.output_level = DEFAULT_OUTPUT_LEVEL
343    bts.input_level = DEFAULT_INPUT_LEVEL
344    bts.packet_rate = DEFAULT_WCDMA_PACKET_RATE
345
346
347def _init_gsm_bts(bts, user_params, cell_no, sim_card):
348    """ initializes the GSM BTS
349        All BTS parameters should be set here
350
351    Args:
352        bts: BTS object.
353        user_params: pointer to user supplied parameters
354        cell_no: specify the cell number this BTS is configured
355        Anritsu supports two cells. so cell_1 or cell_2
356
357    Returns:
358        None
359    """
360    bts.nw_fullname_enable = BtsNwNameEnable.NAME_ENABLE
361    bts.nw_fullname = TEST_PLMN_GSM_NAME
362    bts.mcc = get_gsm_mcc(user_params, cell_no, sim_card)
363    bts.mnc = get_gsm_mnc(user_params, cell_no, sim_card)
364    bts.band = get_gsm_band(user_params, cell_no)
365    bts.rac = get_gsm_rac(user_params, cell_no)
366    bts.lac = get_gsm_lac(user_params, cell_no)
367    bts.output_level = DEFAULT_OUTPUT_LEVEL
368    bts.input_level = DEFAULT_INPUT_LEVEL
369
370
371def _init_1x_bts(bts, user_params, cell_no, sim_card):
372    """ initializes the 1X BTS
373        All BTS parameters should be set here
374
375    Args:
376        bts: BTS object.
377        user_params: pointer to user supplied parameters
378        cell_no: specify the cell number this BTS is configured
379        Anritsu supports two cells. so cell_1 or cell_2
380
381    Returns:
382        None
383    """
384    bts.sector1_mcc = get_1x_mcc(user_params, cell_no, sim_card)
385    bts.band = get_1x_band(user_params, cell_no, sim_card)
386    bts.dl_channel = get_1x_channel(user_params, cell_no, sim_card)
387    bts.sector1_sid = get_1x_sid(user_params, cell_no, sim_card)
388    bts.sector1_nid = get_1x_nid(user_params, cell_no, sim_card)
389    bts.output_level = DEFAULT_1X_OUTPUT_LEVEL
390
391
392def _init_evdo_bts(bts, user_params, cell_no, sim_card):
393    """ initializes the EVDO BTS
394        All BTS parameters should be set here
395
396    Args:
397        bts: BTS object.
398        user_params: pointer to user supplied parameters
399        cell_no: specify the cell number this BTS is configured
400        Anritsu supports two cells. so cell_1 or cell_2
401
402    Returns:
403        None
404    """
405    bts.band = get_evdo_band(user_params, cell_no, sim_card)
406    bts.dl_channel = get_evdo_channel(user_params, cell_no, sim_card)
407    bts.evdo_sid = get_evdo_sid(user_params, cell_no, sim_card)
408    bts.output_level = DEFAULT_1X_OUTPUT_LEVEL
409
410
411def _init_PDN(anritsu_handle,
412              pdn,
413              ipv4,
414              ipv6,
415              ims_binding,
416              vnid_number=DEFAULT_VNID):
417    """ initializes the PDN parameters
418        All PDN parameters should be set here
419
420    Args:
421        anritsu_handle: anritusu device object.
422        pdn: pdn object
423        ip_address : UE IP address
424        ims_binding: to bind with IMS VNID(1) or not
425
426    Returns:
427        None
428    """
429    # Setting IP address for internet connection sharing
430    anritsu_handle.gateway_ipv4addr = GATEWAY_IPV4_ADDR
431    pdn.ue_address_ipv4 = ipv4
432    pdn.ue_address_ipv6 = ipv6
433    if ims_binding:
434        pdn.pdn_ims = Switch.ENABLE
435        pdn.pdn_vnid = vnid_number
436    else:
437        pdn.primary_dns_address_ipv4 = DNS_IPV4_ADDR
438        pdn.secondary_dns_address_ipv4 = DNS_IPV4_ADDR
439        pdn.cscf_address_ipv4 = CSCF_IPV4_ADDR
440
441
442def _init_IMS(anritsu_handle,
443              vnid,
444              sim_card=None,
445              ipv6_address=CSCF_IPV6_ADDR,
446              ip_type="IPV4V6",
447              auth=False):
448    """ initializes the IMS VNID parameters
449        All IMS parameters should be set here
450
451    Args:
452        anritsu_handle: anritusu device object.
453        vnid: IMS Services object
454
455    Returns:
456        None
457    """
458    # vnid.sync = Switch.ENABLE # supported in 6.40a release
459    vnid.cscf_address_ipv4 = CSCF_IPV4_ADDR
460    vnid.cscf_address_ipv6 = ipv6_address
461    vnid.imscscf_iptype = ip_type
462    vnid.dns = Switch.DISABLE
463    vnid.ndp_nic = NDP_NIC_NAME
464    vnid.ndp_prefix = ipv6_address
465    if sim_card == P0135Ax:
466        vnid.cscf_monitoring_ua = TMO_CSCF_Monitoring_UA_URI
467        vnid.cscf_virtual_ua = TMO_CSCF_Virtual_UA_URI
468        vnid.cscf_host_name = CSCF_HOSTNAME
469        vnid.cscf_ims_authentication = "DISABLE"
470        if auth:
471            vnid.cscf_ims_authentication = "ENABLE"
472            vnid.tmo_cscf_userslist_add = TMO_USERLIST_NAME
473    elif sim_card == VzW12349:
474        vnid.cscf_monitoring_ua = CSCF_Monitoring_UA_URI
475        vnid.cscf_virtual_ua = CSCF_Virtual_UA_URI
476        vnid.cscf_ims_authentication = "DISABLE"
477        if auth:
478            vnid.cscf_ims_authentication = "ENABLE"
479            vnid.vzw_cscf_userslist_add = VZW_USERLIST_NAME
480    else:
481        vnid.cscf_monitoring_ua = CSCF_Monitoring_UA_URI
482    vnid.psap = Switch.ENABLE
483    vnid.psap_auto_answer = Switch.ENABLE
484
485
486def set_system_model_lte_lte(anritsu_handle, user_params, sim_card):
487    """ Configures Anritsu system for LTE and LTE simulation
488
489    Args:
490        anritsu_handle: anritusu device object.
491        user_params: pointer to user supplied parameters
492
493    Returns:
494        Lte and Wcdma BTS objects
495    """
496    anritsu_handle.set_simulation_model(BtsTechnology.LTE, BtsTechnology.LTE)
497    # setting BTS parameters
498    lte1_bts = anritsu_handle.get_BTS(BtsNumber.BTS1)
499    lte2_bts = anritsu_handle.get_BTS(BtsNumber.BTS2)
500    _init_lte_bts(lte1_bts, user_params, CELL_1, sim_card)
501    _init_lte_bts(lte2_bts, user_params, CELL_2, sim_card)
502    pdn1 = anritsu_handle.get_PDN(PDN_NO_1)
503    pdn2 = anritsu_handle.get_PDN(PDN_NO_2)
504    pdn3 = anritsu_handle.get_PDN(PDN_NO_3)
505    # Initialize PDN IP address for internet connection sharing
506    _init_PDN(anritsu_handle, pdn1, UE_IPV4_ADDR_1, UE_IPV6_ADDR_1, True)
507    _init_PDN(anritsu_handle, pdn2, UE_IPV4_ADDR_2, UE_IPV6_ADDR_2, False)
508    _init_PDN(anritsu_handle, pdn3, UE_IPV4_ADDR_3, UE_IPV6_ADDR_3, True)
509    vnid1 = anritsu_handle.get_IMS(DEFAULT_VNID)
510    if sim_card == P0135Ax:
511        vnid2 = anritsu_handle.get_IMS(2)
512        vnid3 = anritsu_handle.get_IMS(3)
513        _init_IMS(
514            anritsu_handle,
515            vnid1,
516            sim_card,
517            ipv6_address=CSCF_IPV6_ADDR,
518            auth=True)
519        _init_IMS(
520            anritsu_handle,
521            vnid2,
522            sim_card,
523            ipv6_address=CSCF_IPV6_ADDR_2,
524            ip_type="IPV6")
525        _init_IMS(
526            anritsu_handle,
527            vnid3,
528            sim_card,
529            ipv6_address=CSCF_IPV6_ADDR_3,
530            ip_type="IPV6")
531    elif sim_card == VzW12349:
532        _init_IMS(anritsu_handle, vnid1, sim_card, auth=True)
533    else:
534        _init_IMS(anritsu_handle, vnid1, sim_card)
535    return [lte1_bts, lte2_bts]
536
537
538def set_system_model_wcdma_wcdma(anritsu_handle, user_params, sim_card):
539    """ Configures Anritsu system for WCDMA and WCDMA simulation
540
541    Args:
542        anritsu_handle: anritusu device object.
543        user_params: pointer to user supplied parameters
544
545    Returns:
546        Lte and Wcdma BTS objects
547    """
548    anritsu_handle.set_simulation_model(BtsTechnology.WCDMA,
549                                        BtsTechnology.WCDMA)
550    # setting BTS parameters
551    wcdma1_bts = anritsu_handle.get_BTS(BtsNumber.BTS1)
552    wcdma2_bts = anritsu_handle.get_BTS(BtsNumber.BTS2)
553    _init_wcdma_bts(wcdma1_bts, user_params, CELL_1, sim_card)
554    _init_wcdma_bts(wcdma2_bts, user_params, CELL_2, sim_card)
555    pdn1 = anritsu_handle.get_PDN(PDN_NO_1)
556    # Initialize PDN IP address for internet connection sharing
557    _init_PDN(anritsu_handle, pdn1, UE_IPV4_ADDR_1, UE_IPV6_ADDR_1, False)
558    return [wcdma1_bts, wcdma2_bts]
559
560
561def set_system_model_lte_wcdma(anritsu_handle, user_params, sim_card):
562    """ Configures Anritsu system for LTE and WCDMA simulation
563
564    Args:
565        anritsu_handle: anritusu device object.
566        user_params: pointer to user supplied parameters
567
568    Returns:
569        Lte and Wcdma BTS objects
570    """
571    anritsu_handle.set_simulation_model(BtsTechnology.LTE, BtsTechnology.WCDMA)
572    # setting BTS parameters
573    lte_bts = anritsu_handle.get_BTS(BtsNumber.BTS1)
574    wcdma_bts = anritsu_handle.get_BTS(BtsNumber.BTS2)
575    _init_lte_bts(lte_bts, user_params, CELL_1, sim_card)
576    _init_wcdma_bts(wcdma_bts, user_params, CELL_2, sim_card)
577    pdn1 = anritsu_handle.get_PDN(PDN_NO_1)
578    pdn2 = anritsu_handle.get_PDN(PDN_NO_2)
579    pdn3 = anritsu_handle.get_PDN(PDN_NO_3)
580    # Initialize PDN IP address for internet connection sharing
581    _init_PDN(anritsu_handle, pdn1, UE_IPV4_ADDR_1, UE_IPV6_ADDR_1, True)
582    _init_PDN(anritsu_handle, pdn2, UE_IPV4_ADDR_2, UE_IPV6_ADDR_2, False)
583    _init_PDN(anritsu_handle, pdn3, UE_IPV4_ADDR_3, UE_IPV6_ADDR_3, True)
584    vnid1 = anritsu_handle.get_IMS(DEFAULT_VNID)
585    if sim_card == P0135Ax:
586        vnid2 = anritsu_handle.get_IMS(2)
587        vnid3 = anritsu_handle.get_IMS(3)
588        _init_IMS(
589            anritsu_handle,
590            vnid1,
591            sim_card,
592            ipv6_address=CSCF_IPV6_ADDR,
593            auth=True)
594        _init_IMS(
595            anritsu_handle,
596            vnid2,
597            sim_card,
598            ipv6_address=CSCF_IPV6_ADDR_2,
599            ip_type="IPV6")
600        _init_IMS(
601            anritsu_handle,
602            vnid3,
603            sim_card,
604            ipv6_address=CSCF_IPV6_ADDR_3,
605            ip_type="IPV6")
606    elif sim_card == VzW12349:
607        _init_IMS(anritsu_handle, vnid1, sim_card, auth=True)
608    else:
609        _init_IMS(anritsu_handle, vnid1, sim_card)
610    return [lte_bts, wcdma_bts]
611
612
613def set_system_model_lte_gsm(anritsu_handle, user_params, sim_card):
614    """ Configures Anritsu system for LTE and GSM simulation
615
616    Args:
617        anritsu_handle: anritusu device object.
618        user_params: pointer to user supplied parameters
619
620    Returns:
621        Lte and Wcdma BTS objects
622    """
623    anritsu_handle.set_simulation_model(BtsTechnology.LTE, BtsTechnology.GSM)
624    # setting BTS parameters
625    lte_bts = anritsu_handle.get_BTS(BtsNumber.BTS1)
626    gsm_bts = anritsu_handle.get_BTS(BtsNumber.BTS2)
627    _init_lte_bts(lte_bts, user_params, CELL_1, sim_card)
628    _init_gsm_bts(gsm_bts, user_params, CELL_2, sim_card)
629    pdn1 = anritsu_handle.get_PDN(PDN_NO_1)
630    pdn2 = anritsu_handle.get_PDN(PDN_NO_2)
631    pdn3 = anritsu_handle.get_PDN(PDN_NO_3)
632    # Initialize PDN IP address for internet connection sharing
633    _init_PDN(anritsu_handle, pdn1, UE_IPV4_ADDR_1, UE_IPV6_ADDR_1, True)
634    _init_PDN(anritsu_handle, pdn2, UE_IPV4_ADDR_2, UE_IPV6_ADDR_2, False)
635    _init_PDN(anritsu_handle, pdn3, UE_IPV4_ADDR_3, UE_IPV6_ADDR_3, True)
636    vnid1 = anritsu_handle.get_IMS(DEFAULT_VNID)
637    if sim_card == P0135Ax:
638        vnid2 = anritsu_handle.get_IMS(2)
639        vnid3 = anritsu_handle.get_IMS(3)
640        _init_IMS(
641            anritsu_handle,
642            vnid1,
643            sim_card,
644            ipv6_address=CSCF_IPV6_ADDR,
645            auth=True)
646        _init_IMS(
647            anritsu_handle,
648            vnid2,
649            sim_card,
650            ipv6_address=CSCF_IPV6_ADDR_2,
651            ip_type="IPV6")
652        _init_IMS(
653            anritsu_handle,
654            vnid3,
655            sim_card,
656            ipv6_address=CSCF_IPV6_ADDR_3,
657            ip_type="IPV6")
658    elif sim_card == VzW12349:
659        _init_IMS(anritsu_handle, vnid1, sim_card, auth=True)
660    else:
661        _init_IMS(anritsu_handle, vnid1, sim_card)
662    return [lte_bts, gsm_bts]
663
664
665def set_system_model_lte_1x(anritsu_handle, user_params, sim_card):
666    """ Configures Anritsu system for LTE and 1x simulation
667
668    Args:
669        anritsu_handle: anritusu device object.
670        user_params: pointer to user supplied parameters
671
672    Returns:
673        Lte and 1x BTS objects
674    """
675    anritsu_handle.set_simulation_model(BtsTechnology.LTE,
676                                        BtsTechnology.CDMA1X)
677    # setting BTS parameters
678    lte_bts = anritsu_handle.get_BTS(BtsNumber.BTS1)
679    cdma1x_bts = anritsu_handle.get_BTS(BtsNumber.BTS2)
680    _init_lte_bts(lte_bts, user_params, CELL_1, sim_card)
681    _init_1x_bts(cdma1x_bts, user_params, CELL_2, sim_card)
682    pdn1 = anritsu_handle.get_PDN(PDN_NO_1)
683    pdn2 = anritsu_handle.get_PDN(PDN_NO_2)
684    pdn3 = anritsu_handle.get_PDN(PDN_NO_3)
685    # Initialize PDN IP address for internet connection sharing
686    _init_PDN(anritsu_handle, pdn1, UE_IPV4_ADDR_1, UE_IPV6_ADDR_1, True)
687    _init_PDN(anritsu_handle, pdn2, UE_IPV4_ADDR_2, UE_IPV6_ADDR_2, False)
688    _init_PDN(anritsu_handle, pdn3, UE_IPV4_ADDR_3, UE_IPV6_ADDR_3, True)
689    vnid1 = anritsu_handle.get_IMS(DEFAULT_VNID)
690    if sim_card == P0135Ax:
691        vnid2 = anritsu_handle.get_IMS(2)
692        vnid3 = anritsu_handle.get_IMS(3)
693        _init_IMS(
694            anritsu_handle,
695            vnid1,
696            sim_card,
697            ipv6_address=CSCF_IPV6_ADDR,
698            auth=True)
699        _init_IMS(
700            anritsu_handle,
701            vnid2,
702            sim_card,
703            ipv6_address=CSCF_IPV6_ADDR_2,
704            ip_type="IPV6")
705        _init_IMS(
706            anritsu_handle,
707            vnid3,
708            sim_card,
709            ipv6_address=CSCF_IPV6_ADDR_3,
710            ip_type="IPV6")
711    elif sim_card == VzW12349:
712        _init_IMS(anritsu_handle, vnid1, sim_card, auth=True)
713    else:
714        _init_IMS(anritsu_handle, vnid1, sim_card)
715    return [lte_bts, cdma1x_bts]
716
717
718def set_system_model_lte_evdo(anritsu_handle, user_params, sim_card):
719    """ Configures Anritsu system for LTE and EVDO simulation
720
721    Args:
722        anritsu_handle: anritusu device object.
723        user_params: pointer to user supplied parameters
724
725    Returns:
726        Lte and 1x BTS objects
727    """
728    anritsu_handle.set_simulation_model(BtsTechnology.LTE, BtsTechnology.EVDO)
729    # setting BTS parameters
730    lte_bts = anritsu_handle.get_BTS(BtsNumber.BTS1)
731    evdo_bts = anritsu_handle.get_BTS(BtsNumber.BTS2)
732    _init_lte_bts(lte_bts, user_params, CELL_1, sim_card)
733    _init_evdo_bts(evdo_bts, user_params, CELL_2, sim_card)
734    pdn1 = anritsu_handle.get_PDN(PDN_NO_1)
735    pdn2 = anritsu_handle.get_PDN(PDN_NO_2)
736    pdn3 = anritsu_handle.get_PDN(PDN_NO_3)
737    # Initialize PDN IP address for internet connection sharing
738    _init_PDN(anritsu_handle, pdn1, UE_IPV4_ADDR_1, UE_IPV6_ADDR_1, True)
739    _init_PDN(anritsu_handle, pdn2, UE_IPV4_ADDR_2, UE_IPV6_ADDR_2, False)
740    _init_PDN(anritsu_handle, pdn3, UE_IPV4_ADDR_3, UE_IPV6_ADDR_3, True)
741    vnid1 = anritsu_handle.get_IMS(DEFAULT_VNID)
742    if sim_card == P0135Ax:
743        vnid2 = anritsu_handle.get_IMS(2)
744        vnid3 = anritsu_handle.get_IMS(3)
745        _init_IMS(
746            anritsu_handle,
747            vnid1,
748            sim_card,
749            ipv6_address=CSCF_IPV6_ADDR,
750            auth=True)
751        _init_IMS(
752            anritsu_handle,
753            vnid2,
754            sim_card,
755            ipv6_address=CSCF_IPV6_ADDR_2,
756            ip_type="IPV6")
757        _init_IMS(
758            anritsu_handle,
759            vnid3,
760            sim_card,
761            ipv6_address=CSCF_IPV6_ADDR_3,
762            ip_type="IPV6")
763    elif sim_card == VzW12349:
764        _init_IMS(anritsu_handle, vnid1, sim_card, auth=True)
765    else:
766        _init_IMS(anritsu_handle, vnid1, sim_card)
767    return [lte_bts, evdo_bts]
768
769
770def set_system_model_wcdma_gsm(anritsu_handle, user_params, sim_card):
771    """ Configures Anritsu system for WCDMA and GSM simulation
772
773    Args:
774        anritsu_handle: anritusu device object.
775        user_params: pointer to user supplied parameters
776
777    Returns:
778        Wcdma and Gsm BTS objects
779    """
780    anritsu_handle.set_simulation_model(BtsTechnology.WCDMA, BtsTechnology.GSM)
781    # setting BTS parameters
782    wcdma_bts = anritsu_handle.get_BTS(BtsNumber.BTS1)
783    gsm_bts = anritsu_handle.get_BTS(BtsNumber.BTS2)
784    _init_wcdma_bts(wcdma_bts, user_params, CELL_1, sim_card)
785    _init_gsm_bts(gsm_bts, user_params, CELL_2, sim_card)
786    pdn1 = anritsu_handle.get_PDN(PDN_NO_1)
787    # Initialize PDN IP address for internet connection sharing
788    _init_PDN(anritsu_handle, pdn1, UE_IPV4_ADDR_1, UE_IPV6_ADDR_1, False)
789    return [wcdma_bts, gsm_bts]
790
791
792def set_system_model_gsm_gsm(anritsu_handle, user_params, sim_card):
793    """ Configures Anritsu system for GSM and GSM simulation
794
795    Args:
796        anritsu_handle: anritusu device object.
797        user_params: pointer to user supplied parameters
798
799    Returns:
800        Wcdma and Gsm BTS objects
801    """
802    anritsu_handle.set_simulation_model(BtsTechnology.GSM, BtsTechnology.GSM)
803    # setting BTS parameters
804    gsm1_bts = anritsu_handle.get_BTS(BtsNumber.BTS1)
805    gsm2_bts = anritsu_handle.get_BTS(BtsNumber.BTS2)
806    _init_gsm_bts(gsm1_bts, user_params, CELL_1, sim_card)
807    _init_gsm_bts(gsm2_bts, user_params, CELL_2, sim_card)
808    pdn1 = anritsu_handle.get_PDN(PDN_NO_1)
809    # Initialize PDN IP address for internet connection sharing
810    _init_PDN(anritsu_handle, pdn1, UE_IPV4_ADDR_1, UE_IPV6_ADDR_1, False)
811    return [gsm1_bts, gsm2_bts]
812
813
814def set_system_model_lte(anritsu_handle, user_params, sim_card):
815    """ Configures Anritsu system for LTE simulation
816
817    Args:
818        anritsu_handle: anritusu device object.
819        user_params: pointer to user supplied parameters
820
821    Returns:
822        Lte BTS object
823    """
824    anritsu_handle.set_simulation_model(BtsTechnology.LTE)
825    # setting BTS parameters
826    lte_bts = anritsu_handle.get_BTS(BtsNumber.BTS1)
827    _init_lte_bts(lte_bts, user_params, CELL_1, sim_card)
828    pdn1 = anritsu_handle.get_PDN(PDN_NO_1)
829    pdn2 = anritsu_handle.get_PDN(PDN_NO_2)
830    pdn3 = anritsu_handle.get_PDN(PDN_NO_3)
831    # Initialize PDN IP address for internet connection sharing
832    _init_PDN(anritsu_handle, pdn1, UE_IPV4_ADDR_1, UE_IPV6_ADDR_1, True)
833    _init_PDN(anritsu_handle, pdn2, UE_IPV4_ADDR_2, UE_IPV6_ADDR_2, False)
834    _init_PDN(anritsu_handle, pdn3, UE_IPV4_ADDR_3, UE_IPV6_ADDR_3, True)
835    vnid1 = anritsu_handle.get_IMS(DEFAULT_VNID)
836    if sim_card == P0135Ax:
837        vnid2 = anritsu_handle.get_IMS(2)
838        vnid3 = anritsu_handle.get_IMS(3)
839        _init_IMS(
840            anritsu_handle,
841            vnid1,
842            sim_card,
843            ipv6_address=CSCF_IPV6_ADDR,
844            auth=True)
845        _init_IMS(
846            anritsu_handle,
847            vnid2,
848            sim_card,
849            ipv6_address=CSCF_IPV6_ADDR_2,
850            ip_type="IPV6")
851        _init_IMS(
852            anritsu_handle,
853            vnid3,
854            sim_card,
855            ipv6_address=CSCF_IPV6_ADDR_3,
856            ip_type="IPV6")
857    elif sim_card == VzW12349:
858        _init_IMS(anritsu_handle, vnid1, sim_card, auth=True)
859    else:
860        _init_IMS(anritsu_handle, vnid1, sim_card)
861    return [lte_bts]
862
863
864def set_system_model_wcdma(anritsu_handle, user_params, sim_card):
865    """ Configures Anritsu system for WCDMA simulation
866
867    Args:
868        anritsu_handle: anritusu device object.
869        user_params: pointer to user supplied parameters
870
871    Returns:
872        Wcdma BTS object
873    """
874    anritsu_handle.set_simulation_model(BtsTechnology.WCDMA)
875    # setting BTS parameters
876    wcdma_bts = anritsu_handle.get_BTS(BtsNumber.BTS1)
877    _init_wcdma_bts(wcdma_bts, user_params, CELL_1, sim_card)
878    pdn1 = anritsu_handle.get_PDN(PDN_NO_1)
879    # Initialize PDN IP address for internet connection sharing
880    _init_PDN(anritsu_handle, pdn1, UE_IPV4_ADDR_1, UE_IPV6_ADDR_1, False)
881    return [wcdma_bts]
882
883
884def set_system_model_gsm(anritsu_handle, user_params, sim_card):
885    """ Configures Anritsu system for GSM simulation
886
887    Args:
888        anritsu_handle: anritusu device object.
889        user_params: pointer to user supplied parameters
890
891    Returns:
892        Gsm BTS object
893    """
894    anritsu_handle.set_simulation_model(BtsTechnology.GSM)
895    # setting BTS parameters
896    gsm_bts = anritsu_handle.get_BTS(BtsNumber.BTS1)
897    _init_gsm_bts(gsm_bts, user_params, CELL_1, sim_card)
898    pdn1 = anritsu_handle.get_PDN(PDN_NO_1)
899    # Initialize PDN IP address for internet connection sharing
900    _init_PDN(anritsu_handle, pdn1, UE_IPV4_ADDR_1, UE_IPV6_ADDR_1, False)
901    return [gsm_bts]
902
903
904def set_system_model_1x(anritsu_handle, user_params, sim_card):
905    """ Configures Anritsu system for CDMA 1X simulation
906
907    Args:
908        anritsu_handle: anritusu device object.
909        user_params: pointer to user supplied parameters
910
911    Returns:
912        Cdma 1x BTS object
913    """
914    PDN_ONE = 1
915    anritsu_handle.set_simulation_model(BtsTechnology.CDMA1X)
916    # setting BTS parameters
917    cdma1x_bts = anritsu_handle.get_BTS(BtsNumber.BTS1)
918    _init_1x_bts(cdma1x_bts, user_params, CELL_1, sim_card)
919    pdn1 = anritsu_handle.get_PDN(PDN_ONE)
920    # Initialize PDN IP address for internet connection sharing
921    _init_PDN(anritsu_handle, pdn1, UE_IPV4_ADDR_1, UE_IPV6_ADDR_1, False)
922    return [cdma1x_bts]
923
924
925def set_system_model_1x_evdo(anritsu_handle, user_params, sim_card):
926    """ Configures Anritsu system for CDMA 1X simulation
927
928    Args:
929        anritsu_handle: anritusu device object.
930        user_params: pointer to user supplied parameters
931
932    Returns:
933        Cdma 1x BTS object
934    """
935    PDN_ONE = 1
936    anritsu_handle.set_simulation_model(BtsTechnology.CDMA1X,
937                                        BtsTechnology.EVDO)
938    # setting BTS parameters
939    cdma1x_bts = anritsu_handle.get_BTS(BtsNumber.BTS1)
940    evdo_bts = anritsu_handle.get_BTS(BtsNumber.BTS2)
941    _init_1x_bts(cdma1x_bts, user_params, CELL_1, sim_card)
942    _init_evdo_bts(evdo_bts, user_params, CELL_2, sim_card)
943    pdn1 = anritsu_handle.get_PDN(PDN_ONE)
944    # Initialize PDN IP address for internet connection sharing
945    _init_PDN(anritsu_handle, pdn1, UE_IPV4_ADDR_1, UE_IPV6_ADDR_1, False)
946    return [cdma1x_bts]
947
948
949def wait_for_bts_state(log, btsnumber, state, timeout=30):
950    """ Waits for BTS to be in the specified state ("IN" or "OUT")
951
952    Args:
953        btsnumber: BTS number.
954        state: expected state
955
956    Returns:
957        True for success False for failure
958    """
959    #  state value are "IN" and "OUT"
960    status = False
961    sleep_interval = 1
962    wait_time = timeout
963
964    if state is "IN":
965        service_state = BtsServiceState.SERVICE_STATE_IN
966    elif state is "OUT":
967        service_state = BtsServiceState.SERVICE_STATE_OUT
968    else:
969        log.info("wrong state value")
970        return status
971
972    if btsnumber.service_state is service_state:
973        log.info("BTS state is already in {}".format(state))
974        return True
975
976    # set to desired service state
977    btsnumber.service_state = service_state
978
979    while wait_time > 0:
980        if service_state == btsnumber.service_state:
981            status = True
982            break
983        time.sleep(sleep_interval)
984        wait_time = wait_time - sleep_interval
985
986    if not status:
987        log.info("Timeout: Expected BTS state is not received.")
988    return status
989
990
991class _CallSequenceException(Exception):
992    pass
993
994
995def call_mo_setup_teardown(
996        log,
997        ad,
998        anritsu_handle,
999        callee_number,
1000        teardown_side=CALL_TEARDOWN_PHONE,
1001        is_emergency=False,
1002        wait_time_in_call=WAIT_TIME_IN_CALL,
1003        is_ims_call=False,
1004        ims_virtual_network_id=DEFAULT_IMS_VIRTUAL_NETWORK_ID):
1005    """ Makes a MO call and tear down the call
1006
1007    Args:
1008        ad: Android device object.
1009        anritsu_handle: Anritsu object.
1010        callee_number: Number to be called.
1011        teardown_side: the side to end the call (Phone or remote).
1012        is_emergency: is the call an emergency call.
1013        wait_time_in_call: Time to wait when phone in call.
1014        is_ims_call: is the call expected to be ims call.
1015        ims_virtual_network_id: ims virtual network id.
1016
1017    Returns:
1018        True for success False for failure
1019    """
1020
1021    log.info("Making Call to " + callee_number)
1022    virtual_phone_handle = anritsu_handle.get_VirtualPhone()
1023
1024    try:
1025        # for an IMS call we either check CSCF or *nothing* (no virtual phone).
1026        if is_ims_call:
1027            # we only need pre-call registration in a non-emergency case
1028            if not is_emergency:
1029                if not wait_for_ims_cscf_status(log, anritsu_handle,
1030                                                ims_virtual_network_id,
1031                                                ImsCscfStatus.SIPIDLE.value):
1032                    raise _CallSequenceException(
1033                        "Phone IMS status is not idle.")
1034        else:
1035            if not wait_for_virtualphone_state(log, virtual_phone_handle,
1036                                               VirtualPhoneStatus.STATUS_IDLE):
1037                raise _CallSequenceException("Virtual Phone not idle.")
1038
1039        if not initiate_call(log, ad, callee_number, is_emergency):
1040            raise _CallSequenceException("Initiate call failed.")
1041
1042        if is_ims_call:
1043            if not wait_for_ims_cscf_status(log, anritsu_handle,
1044                                            ims_virtual_network_id,
1045                                            ImsCscfStatus.CALLING.value):
1046                raise _CallSequenceException(
1047                    "Phone IMS status is not calling.")
1048            if not wait_for_ims_cscf_status(log, anritsu_handle,
1049                                            ims_virtual_network_id,
1050                                            ImsCscfStatus.CONNECTED.value):
1051                raise _CallSequenceException(
1052                    "Phone IMS status is not connected.")
1053        else:
1054            # check Virtual phone answered the call
1055            if not wait_for_virtualphone_state(
1056                    log, virtual_phone_handle,
1057                    VirtualPhoneStatus.STATUS_VOICECALL_INPROGRESS):
1058                raise _CallSequenceException("Virtual Phone not in call.")
1059
1060        time.sleep(wait_time_in_call)
1061
1062        if not ad.droid.telecomIsInCall():
1063            raise _CallSequenceException("Call ended before delay_in_call.")
1064
1065        if teardown_side is CALL_TEARDOWN_REMOTE:
1066            log.info("Disconnecting the call from Remote")
1067            if is_ims_call:
1068                anritsu_handle.ims_cscf_call_action(ims_virtual_network_id,
1069                                                    ImsCscfCall.END.value)
1070            else:
1071                virtual_phone_handle.set_voice_on_hook()
1072            if not wait_for_droid_not_in_call(log, ad,
1073                                              MAX_WAIT_TIME_CALL_DROP):
1074                raise _CallSequenceException("DUT call not drop.")
1075        else:
1076            log.info("Disconnecting the call from DUT")
1077            if not hangup_call(log, ad):
1078                raise _CallSequenceException(
1079                    "Error in Hanging-Up Call on DUT.")
1080
1081        if is_ims_call:
1082            if not wait_for_ims_cscf_status(log, anritsu_handle,
1083                                            ims_virtual_network_id,
1084                                            ImsCscfStatus.SIPIDLE.value):
1085                raise _CallSequenceException("Phone IMS status is not idle.")
1086        else:
1087            if not wait_for_virtualphone_state(log, virtual_phone_handle,
1088                                               VirtualPhoneStatus.STATUS_IDLE):
1089                raise _CallSequenceException(
1090                    "Virtual Phone not idle after hangup.")
1091        return True
1092
1093    except _CallSequenceException as e:
1094        log.error(e)
1095        return False
1096    finally:
1097        try:
1098            if ad.droid.telecomIsInCall():
1099                ad.droid.telecomEndCall()
1100        except Exception as e:
1101            log.error(str(e))
1102
1103
1104def handover_tc(log,
1105                anritsu_handle,
1106                wait_time=0,
1107                s_bts=BtsNumber.BTS1,
1108                t_bts=BtsNumber.BTS2,
1109                timeout=60):
1110    """ Setup and perform a handover test case in MD8475A
1111
1112    Args:
1113        anritsu_handle: Anritsu object.
1114        s_bts: Serving (originating) BTS
1115        t_bts: Target (destination) BTS
1116        wait_time: time to wait before handover
1117
1118    Returns:
1119        True for success False for failure
1120    """
1121    log.info("Starting HO test case procedure")
1122    log.info("Serving BTS = {}, Target BTS = {}".format(s_bts, t_bts))
1123    time.sleep(wait_time)
1124    ho_tc = anritsu_handle.get_AnritsuTestCases()
1125    ho_tc.procedure = TestProcedure.PROCEDURE_HO
1126    ho_tc.bts_direction = (s_bts, t_bts)
1127    ho_tc.power_control = TestPowerControl.POWER_CONTROL_DISABLE
1128    ho_tc.measurement_LTE = TestMeasurement.MEASUREMENT_DISABLE
1129    anritsu_handle.start_testcase()
1130    status = anritsu_handle.get_testcase_status()
1131    timer = 0
1132    while status == "0":
1133        time.sleep(1)
1134        status = anritsu_handle.get_testcase_status()
1135        timer += 1
1136        if timer > timeout:
1137            return "Handover Test Case time out in {} sec!".format(timeout)
1138    return status
1139
1140
1141def make_ims_call(log,
1142                  ad,
1143                  anritsu_handle,
1144                  callee_number,
1145                  is_emergency=False,
1146                  check_ims_reg=True,
1147                  check_ims_calling=True,
1148                  mo=True,
1149                  ims_virtual_network_id=DEFAULT_IMS_VIRTUAL_NETWORK_ID):
1150    """ Makes a MO call after IMS registred
1151
1152    Args:
1153        ad: Android device object.
1154        anritsu_handle: Anritsu object.
1155        callee_number: Number to be called.
1156        check_ims_reg: check if Anritsu cscf server state is "SIPIDLE".
1157        check_ims_calling: check if Anritsu cscf server state is "CALLING".
1158        mo: Mobile originated call
1159        ims_virtual_network_id: ims virtual network id.
1160
1161    Returns:
1162        True for success False for failure
1163    """
1164
1165    try:
1166        # confirm ims registration
1167        if check_ims_reg:
1168            if not wait_for_ims_cscf_status(log, anritsu_handle,
1169                                            ims_virtual_network_id,
1170                                            ImsCscfStatus.SIPIDLE.value):
1171                raise _CallSequenceException("IMS/CSCF status is not idle.")
1172        if mo:  # make MO call
1173            log.info("Making Call to " + callee_number)
1174            if not initiate_call(log, ad, callee_number, is_emergency):
1175                raise _CallSequenceException("Initiate call failed.")
1176            if not wait_for_ims_cscf_status(log, anritsu_handle,
1177                                            ims_virtual_network_id,
1178                                            ImsCscfStatus.CALLING.value):
1179                raise _CallSequenceException(
1180                    "Phone IMS status is not calling.")
1181        else:  # make MT call
1182            log.info("Making IMS Call to UE from MD8475A...")
1183            anritsu_handle.ims_cscf_call_action(ims_virtual_network_id,
1184                                                ImsCscfCall.MAKE.value)
1185            if not wait_for_ims_cscf_status(log, anritsu_handle,
1186                                            ims_virtual_network_id,
1187                                            ImsCscfStatus.RINGING.value):
1188                raise _CallSequenceException(
1189                    "Phone IMS status is not ringing.")
1190            # answer the call on the UE
1191            if not wait_and_answer_call(log, ad):
1192                raise _CallSequenceException("UE Answer call Fail")
1193
1194        if not wait_for_ims_cscf_status(log, anritsu_handle,
1195                                        ims_virtual_network_id,
1196                                        ImsCscfStatus.CONNECTED.value):
1197            raise _CallSequenceException(
1198                "MD8475A IMS status is not connected.")
1199        return True
1200
1201    except _CallSequenceException as e:
1202        log.error(e)
1203        return False
1204
1205
1206def tear_down_call(log,
1207                   ad,
1208                   anritsu_handle,
1209                   ims_virtual_network_id=DEFAULT_IMS_VIRTUAL_NETWORK_ID):
1210    """ Check and End a VoLTE call
1211
1212    Args:
1213        ad: Android device object.
1214        anritsu_handle: Anritsu object.
1215        ims_virtual_network_id: ims virtual network id.
1216
1217    Returns:
1218        True for success False for failure
1219    """
1220    try:
1221        # end the call from phone
1222        log.info("Disconnecting the call from DUT")
1223        if not hangup_call(log, ad):
1224            raise _CallSequenceException("Error in Hanging-Up Call on DUT.")
1225        # confirm if CSCF status is back to idle
1226        if not wait_for_ims_cscf_status(log, anritsu_handle,
1227                                        ims_virtual_network_id,
1228                                        ImsCscfStatus.SIPIDLE.value):
1229            raise _CallSequenceException("IMS/CSCF status is not idle.")
1230        return True
1231
1232    except _CallSequenceException as e:
1233        log.error(e)
1234        return False
1235    finally:
1236        try:
1237            if ad.droid.telecomIsInCall():
1238                ad.droid.telecomEndCall()
1239        except Exception as e:
1240            log.error(str(e))
1241
1242
1243# This procedure is for VoLTE mobility test cases
1244def ims_call_ho(log,
1245                ad,
1246                anritsu_handle,
1247                callee_number,
1248                is_emergency=False,
1249                check_ims_reg=True,
1250                check_ims_calling=True,
1251                mo=True,
1252                wait_time_in_volte=WAIT_TIME_IN_CALL_FOR_IMS,
1253                ims_virtual_network_id=DEFAULT_IMS_VIRTUAL_NETWORK_ID):
1254    """ Makes a MO call after IMS registred, then handover
1255
1256    Args:
1257        ad: Android device object.
1258        anritsu_handle: Anritsu object.
1259        callee_number: Number to be called.
1260        check_ims_reg: check if Anritsu cscf server state is "SIPIDLE".
1261        check_ims_calling: check if Anritsu cscf server state is "CALLING".
1262        mo: Mobile originated call
1263        wait_time_in_volte: Time for phone in VoLTE call, not used for SRLTE
1264        ims_virtual_network_id: ims virtual network id.
1265
1266    Returns:
1267        True for success False for failure
1268    """
1269
1270    try:
1271        # confirm ims registration
1272        if check_ims_reg:
1273            if not wait_for_ims_cscf_status(log, anritsu_handle,
1274                                            ims_virtual_network_id,
1275                                            ImsCscfStatus.SIPIDLE.value):
1276                raise _CallSequenceException("IMS/CSCF status is not idle.")
1277        if mo:  # make MO call
1278            log.info("Making Call to " + callee_number)
1279            if not initiate_call(log, ad, callee_number, is_emergency):
1280                raise _CallSequenceException("Initiate call failed.")
1281            if not wait_for_ims_cscf_status(log, anritsu_handle,
1282                                            ims_virtual_network_id,
1283                                            ImsCscfStatus.CALLING.value):
1284                raise _CallSequenceException(
1285                    "Phone IMS status is not calling.")
1286        else:  # make MT call
1287            log.info("Making IMS Call to UE from MD8475A...")
1288            anritsu_handle.ims_cscf_call_action(ims_virtual_network_id,
1289                                                ImsCscfCall.MAKE.value)
1290            if not wait_for_ims_cscf_status(log, anritsu_handle,
1291                                            ims_virtual_network_id,
1292                                            ImsCscfStatus.RINGING.value):
1293                raise _CallSequenceException(
1294                    "Phone IMS status is not ringing.")
1295            # answer the call on the UE
1296            if not wait_and_answer_call(log, ad):
1297                raise _CallSequenceException("UE Answer call Fail")
1298
1299        if not wait_for_ims_cscf_status(log, anritsu_handle,
1300                                        ims_virtual_network_id,
1301                                        ImsCscfStatus.CONNECTED.value):
1302            raise _CallSequenceException("Phone IMS status is not connected.")
1303        log.info(
1304            "Wait for {} seconds before handover".format(wait_time_in_volte))
1305        time.sleep(wait_time_in_volte)
1306
1307        # Once VoLTE call is connected, then Handover
1308        log.info("Starting handover procedure...")
1309        result = handover_tc(anritsu_handle, BtsNumber.BTS1, BtsNumber.BTS2)
1310        log.info("Handover procedure ends with result code {}".format(result))
1311        log.info(
1312            "Wait for {} seconds after handover".format(wait_time_in_volte))
1313        time.sleep(wait_time_in_volte)
1314
1315        # check if the phone stay in call
1316        if not ad.droid.telecomIsInCall():
1317            raise _CallSequenceException("Call ended before delay_in_call.")
1318        # end the call from phone
1319        log.info("Disconnecting the call from DUT")
1320        if not hangup_call(log, ad):
1321            raise _CallSequenceException("Error in Hanging-Up Call on DUT.")
1322        # confirm if CSCF status is back to idle
1323        if not wait_for_ims_cscf_status(log, anritsu_handle,
1324                                        ims_virtual_network_id,
1325                                        ImsCscfStatus.SIPIDLE.value):
1326            raise _CallSequenceException("IMS/CSCF status is not idle.")
1327
1328        return True
1329
1330    except _CallSequenceException as e:
1331        log.error(e)
1332        return False
1333    finally:
1334        try:
1335            if ad.droid.telecomIsInCall():
1336                ad.droid.telecomEndCall()
1337        except Exception as e:
1338            log.error(str(e))
1339
1340
1341# This procedure is for SRLTE CSFB and SRVCC test cases
1342def ims_call_cs_teardown(
1343        log,
1344        ad,
1345        anritsu_handle,
1346        callee_number,
1347        teardown_side=CALL_TEARDOWN_PHONE,
1348        is_emergency=False,
1349        check_ims_reg=True,
1350        check_ims_calling=True,
1351        srvcc=None,
1352        mo=True,
1353        wait_time_in_volte=WAIT_TIME_IN_CALL_FOR_IMS,
1354        wait_time_in_cs=WAIT_TIME_IN_CALL,
1355        wait_time_in_alert=WAIT_TIME_IN_ALERT,
1356        ims_virtual_network_id=DEFAULT_IMS_VIRTUAL_NETWORK_ID):
1357    """ Makes a MO call after IMS registred, transit to CS, tear down the call
1358
1359    Args:
1360        ad: Android device object.
1361        anritsu_handle: Anritsu object.
1362        callee_number: Number to be called.
1363        teardown_side: the side to end the call (Phone or remote).
1364        is_emergency: to make emergency call on the phone.
1365        check_ims_reg: check if Anritsu cscf server state is "SIPIDLE".
1366        check_ims_calling: check if Anritsu cscf server state is "CALLING".
1367        srvcc: is the test case a SRVCC call.
1368        mo: Mobile originated call
1369        wait_time_in_volte: Time for phone in VoLTE call, not used for SRLTE
1370        wait_time_in_cs: Time for phone in CS call.
1371        ims_virtual_network_id: ims virtual network id.
1372
1373    Returns:
1374        True for success False for failure
1375    """
1376
1377    virtual_phone_handle = anritsu_handle.get_VirtualPhone()
1378
1379    try:
1380        # confirm ims registration
1381        if check_ims_reg:
1382            if not wait_for_ims_cscf_status(log, anritsu_handle,
1383                                            ims_virtual_network_id,
1384                                            ImsCscfStatus.SIPIDLE.value):
1385                raise _CallSequenceException("IMS/CSCF status is not idle.")
1386        # confirm virtual phone in idle
1387        if not wait_for_virtualphone_state(log, virtual_phone_handle,
1388                                           VirtualPhoneStatus.STATUS_IDLE):
1389            raise _CallSequenceException("Virtual Phone not idle.")
1390        if mo:  # make MO call
1391            log.info("Making Call to " + callee_number)
1392            if not initiate_call(log, ad, callee_number, is_emergency):
1393                raise _CallSequenceException("Initiate call failed.")
1394        else:  # make MT call
1395            log.info("Making IMS Call to UE from MD8475A...")
1396            anritsu_handle.ims_cscf_call_action(ims_virtual_network_id,
1397                                                ImsCscfCall.MAKE.value)
1398        # if check ims calling is required
1399        if check_ims_calling:
1400            if mo:
1401                if not wait_for_ims_cscf_status(log, anritsu_handle,
1402                                                ims_virtual_network_id,
1403                                                ImsCscfStatus.CALLING.value):
1404                    raise _CallSequenceException(
1405                        "Phone IMS status is not calling.")
1406            else:
1407                if not wait_for_ims_cscf_status(log, anritsu_handle,
1408                                                ims_virtual_network_id,
1409                                                ImsCscfStatus.RINGING.value):
1410                    raise _CallSequenceException(
1411                        "Phone IMS status is not ringing.")
1412
1413            # if SRVCC, check if VoLTE call is connected, then Handover
1414            if srvcc != None:
1415                if srvcc == "InCall":
1416                    if not wait_for_ims_cscf_status(
1417                            log, anritsu_handle, ims_virtual_network_id,
1418                            ImsCscfStatus.CONNECTED.value):
1419                        raise _CallSequenceException(
1420                            "Phone IMS status is not connected.")
1421                    # stay in call for "wait_time_in_volte" seconds
1422                    time.sleep(wait_time_in_volte)
1423                elif srvcc == "Alert":
1424                    # ring for WAIT_TIME_IN_ALERT seconds
1425                    time.sleep(WAIT_TIME_IN_ALERT)
1426                # SRVCC by handover test case procedure
1427                srvcc_tc = anritsu_handle.get_AnritsuTestCases()
1428                srvcc_tc.procedure = TestProcedure.PROCEDURE_HO
1429                srvcc_tc.bts_direction = (BtsNumber.BTS1, BtsNumber.BTS2)
1430                srvcc_tc.power_control = TestPowerControl.POWER_CONTROL_DISABLE
1431                srvcc_tc.measurement_LTE = TestMeasurement.MEASUREMENT_DISABLE
1432                anritsu_handle.start_testcase()
1433                time.sleep(5)
1434        if not mo:
1435            # answer the call on the UE
1436            if not wait_and_answer_call(log, ad):
1437                raise _CallSequenceException("UE Answer call Fail")
1438        # check if Virtual phone in the call
1439        if not wait_for_virtualphone_state(
1440                log, virtual_phone_handle,
1441                VirtualPhoneStatus.STATUS_VOICECALL_INPROGRESS):
1442            raise _CallSequenceException("Virtual Phone not in call.")
1443        # stay in call for "wait_time_in_cs" seconds
1444        time.sleep(wait_time_in_cs)
1445        # check if the phone stay in call
1446        if not ad.droid.telecomIsInCall():
1447            raise _CallSequenceException("Call ended before delay_in_call.")
1448        # end the call
1449        if teardown_side is CALL_TEARDOWN_REMOTE:
1450            log.info("Disconnecting the call from Remote")
1451            virtual_phone_handle.set_voice_on_hook()
1452            if not wait_for_droid_not_in_call(log, ad,
1453                                              MAX_WAIT_TIME_CALL_DROP):
1454                raise _CallSequenceException("DUT call not drop.")
1455        else:
1456            log.info("Disconnecting the call from DUT")
1457            if not hangup_call(log, ad):
1458                raise _CallSequenceException(
1459                    "Error in Hanging-Up Call on DUT.")
1460        # confirm if virtual phone status is back to idle
1461        if not wait_for_virtualphone_state(log, virtual_phone_handle,
1462                                           VirtualPhoneStatus.STATUS_IDLE):
1463            raise _CallSequenceException(
1464                "Virtual Phone not idle after hangup.")
1465        return True
1466
1467    except _CallSequenceException as e:
1468        log.error(e)
1469        return False
1470    finally:
1471        try:
1472            if ad.droid.telecomIsInCall():
1473                ad.droid.telecomEndCall()
1474        except Exception as e:
1475            log.error(str(e))
1476
1477
1478def call_mt_setup_teardown(log,
1479                           ad,
1480                           virtual_phone_handle,
1481                           caller_number=None,
1482                           teardown_side=CALL_TEARDOWN_PHONE,
1483                           rat=""):
1484    """ Makes a call from Anritsu Virtual phone to device and tear down the call
1485
1486    Args:
1487        ad: Android device object.
1488        virtual_phone_handle: Anritus virtual phone handle
1489        caller_number =  Caller number
1490        teardown_side = specifiy the side to end the call (Phone or remote)
1491
1492    Returns:
1493        True for success False for failure
1494    """
1495    log.info("Receive MT Call - Making a call to the phone from remote")
1496    try:
1497        if not wait_for_virtualphone_state(log, virtual_phone_handle,
1498                                           VirtualPhoneStatus.STATUS_IDLE):
1499            raise Exception("Virtual Phone is not in a state to start call")
1500        if caller_number is not None:
1501            if rat == RAT_1XRTT:
1502                virtual_phone_handle.id_c2k = caller_number
1503            else:
1504                virtual_phone_handle.id = caller_number
1505        virtual_phone_handle.set_voice_off_hook()
1506
1507        if not wait_and_answer_call(log, ad, caller_number):
1508            raise Exception("Answer call Fail")
1509
1510        time.sleep(WAIT_TIME_IN_CALL)
1511
1512        if not ad.droid.telecomIsInCall():
1513            raise Exception("Call ended before delay_in_call.")
1514    except Exception:
1515        return False
1516
1517    if ad.droid.telecomIsInCall():
1518        if teardown_side is CALL_TEARDOWN_REMOTE:
1519            log.info("Disconnecting the call from Remote")
1520            virtual_phone_handle.set_voice_on_hook()
1521        else:
1522            log.info("Disconnecting the call from Phone")
1523            ad.droid.telecomEndCall()
1524
1525    wait_for_virtualphone_state(log, virtual_phone_handle,
1526                                VirtualPhoneStatus.STATUS_IDLE)
1527    ensure_phone_idle(log, ad)
1528
1529    return True
1530
1531
1532def wait_for_sms_deliver_success(log, ad, time_to_wait=60):
1533    sms_deliver_event = EventSmsDeliverSuccess
1534    sleep_interval = 2
1535    status = False
1536    event = None
1537
1538    try:
1539        event = ad.ed.pop_event(sms_deliver_event, time_to_wait)
1540        status = True
1541    except Empty:
1542        log.info("Timeout: Expected event is not received.")
1543    return status
1544
1545
1546def wait_for_sms_sent_success(log, ad, time_to_wait=60):
1547    sms_sent_event = EventSmsSentSuccess
1548    sleep_interval = 2
1549    status = False
1550    event = None
1551
1552    try:
1553        event = ad.ed.pop_event(sms_sent_event, time_to_wait)
1554        log.info(event)
1555        status = True
1556    except Empty:
1557        log.info("Timeout: Expected event is not received.")
1558    return status
1559
1560
1561def wait_for_incoming_sms(log, ad, time_to_wait=60):
1562    sms_received_event = EventSmsReceived
1563    sleep_interval = 2
1564    status = False
1565    event = None
1566
1567    try:
1568        event = ad.ed.pop_event(sms_received_event, time_to_wait)
1569        log.info(event)
1570        status = True
1571    except Empty:
1572        log.info("Timeout: Expected event is not received.")
1573    return status, event
1574
1575
1576def verify_anritsu_received_sms(log, vp_handle, receiver_number, message, rat):
1577    if rat == RAT_1XRTT:
1578        receive_sms = vp_handle.receiveSms_c2k()
1579    else:
1580        receive_sms = vp_handle.receiveSms()
1581
1582    if receive_sms == "NONE":
1583        return False
1584    split = receive_sms.split('&')
1585    text = ""
1586    if rat == RAT_1XRTT:
1587        # TODO: b/26296388 There is some problem when retrieving message with é
1588        # from Anritsu.
1589        return True
1590    for i in range(len(split)):
1591        if split[i].startswith('Text='):
1592            text = split[i][5:]
1593            text = AnritsuUtils.gsm_decode(text)
1594            break
1595    # TODO: b/26296388 Verify Phone number
1596    if text != message:
1597        log.error("Wrong message received")
1598        return False
1599    return True
1600
1601
1602def sms_mo_send(log, ad, vp_handle, receiver_number, message, rat=""):
1603    try:
1604        if not wait_for_virtualphone_state(log, vp_handle,
1605                                           VirtualPhoneStatus.STATUS_IDLE):
1606            raise Exception("Virtual Phone is not in a state to receive SMS")
1607        log.info("Sending SMS to " + receiver_number)
1608        ad.droid.smsSendTextMessage(receiver_number, message, False)
1609        log.info("Waiting for SMS sent event")
1610        test_status = wait_for_sms_sent_success(log, ad)
1611        if not test_status:
1612            raise Exception("Failed to send SMS")
1613        if not verify_anritsu_received_sms(log, vp_handle, receiver_number,
1614                                           message, rat):
1615            raise Exception("Anritsu didn't receive message")
1616    except Exception as e:
1617        log.error("Exception :" + str(e))
1618        return False
1619    return True
1620
1621
1622def sms_mt_receive_verify(log, ad, vp_handle, sender_number, message, rat=""):
1623    ad.droid.smsStartTrackingIncomingMessage()
1624    try:
1625        if not wait_for_virtualphone_state(log, vp_handle,
1626                                           VirtualPhoneStatus.STATUS_IDLE):
1627            raise Exception("Virtual Phone is not in a state to receive SMS")
1628        log.info("Waiting for Incoming SMS from " + sender_number)
1629        if rat == RAT_1XRTT:
1630            vp_handle.sendSms_c2k(sender_number, message)
1631        else:
1632            vp_handle.sendSms(sender_number, message)
1633        test_status, event = wait_for_incoming_sms(log, ad)
1634        if not test_status:
1635            raise Exception("Failed to receive SMS")
1636        log.info("Incoming SMS: Sender " + event['data']['Sender'])
1637        log.info("Incoming SMS: Message " + event['data']['Text'])
1638        if event['data']['Sender'] != sender_number:
1639            raise Exception("Wrong sender Number")
1640        if event['data']['Text'] != message:
1641            raise Exception("Wrong message")
1642    except Exception as e:
1643        log.error("exception: " + str(e))
1644        return False
1645    finally:
1646        ad.droid.smsStopTrackingIncomingMessage()
1647    return True
1648
1649
1650def wait_for_ims_cscf_status(log,
1651                             anritsu_handle,
1652                             virtual_network_id,
1653                             status,
1654                             timeout=MAX_WAIT_TIME_IMS_CSCF_STATE):
1655    """ Wait for IMS CSCF to be in expected state.
1656
1657    Args:
1658        log: log object
1659        anritsu_handle: anritsu object
1660        virtual_network_id: virtual network id to be monitored
1661        status: expected status
1662        timeout: wait time
1663    """
1664    sleep_interval = 1
1665    wait_time = timeout
1666    while wait_time > 0:
1667        if status == anritsu_handle.get_ims_cscf_status(virtual_network_id):
1668            return True
1669        time.sleep(sleep_interval)
1670        wait_time = wait_time - sleep_interval
1671    return False
1672
1673
1674def wait_for_virtualphone_state(log,
1675                                vp_handle,
1676                                state,
1677                                timeout=MAX_WAIT_TIME_VIRTUAL_PHONE_STATE):
1678    """ Waits for Anritsu Virtual phone to be in expected state
1679
1680    Args:
1681        ad: Android device object.
1682        vp_handle: Anritus virtual phone handle
1683        state =  expected state
1684
1685    Returns:
1686        True for success False for failure
1687    """
1688    status = False
1689    sleep_interval = 1
1690    wait_time = timeout
1691    while wait_time > 0:
1692        if vp_handle.status == state:
1693            log.info(vp_handle.status)
1694            status = True
1695            break
1696        time.sleep(sleep_interval)
1697        wait_time = wait_time - sleep_interval
1698
1699    if not status:
1700        log.info("Timeout: Expected state is not received.")
1701    return status
1702
1703
1704# There is a difference between CMAS/ETWS message formation in LTE/WCDMA and CDMA 1X
1705# LTE and CDMA : 3GPP
1706# CDMA 1X: 3GPP2
1707# hence different functions
1708def cmas_receive_verify_message_lte_wcdma(
1709        log, ad, anritsu_handle, serial_number, message_id, warning_message):
1710    """ Makes Anritsu to send a CMAS message and phone and verifies phone
1711        receives the message on LTE/WCDMA
1712
1713    Args:
1714        ad: Android device object.
1715        anritsu_handle: Anritus device object
1716        serial_number =  serial number of CMAS message
1717        message_id =  CMAS message ID
1718        warning_message =  CMAS warning message
1719
1720    Returns:
1721        True for success False for failure
1722    """
1723    status = False
1724    event = None
1725    ad.droid.smsStartTrackingGsmEmergencyCBMessage()
1726    anritsu_handle.send_cmas_lte_wcdma(
1727        hex(serial_number), message_id, warning_message)
1728    try:
1729        log.info("Waiting for CMAS Message")
1730        event = ad.ed.pop_event(EventCmasReceived, 60)
1731        status = True
1732        log.info(event)
1733        if warning_message != event['data']['message']:
1734            log.info("Wrong warning messgae received")
1735            status = False
1736        if message_id != hex(event['data']['serviceCategory']):
1737            log.info("Wrong warning messgae received")
1738            status = False
1739    except Empty:
1740        log.info("Timeout: Expected event is not received.")
1741
1742    ad.droid.smsStopTrackingGsmEmergencyCBMessage()
1743    return status
1744
1745
1746def cmas_receive_verify_message_cdma1x(
1747        log,
1748        ad,
1749        anritsu_handle,
1750        message_id,
1751        service_category,
1752        alert_text,
1753        response_type=CMAS_C2K_RESPONSETYPE_SHELTER,
1754        severity=CMAS_C2K_SEVERITY_EXTREME,
1755        urgency=CMAS_C2K_URGENCY_IMMEDIATE,
1756        certainty=CMAS_C2K_CERTIANTY_OBSERVED):
1757    """ Makes Anritsu to send a CMAS message and phone and verifies phone
1758        receives the message on CDMA 1X
1759
1760    Args:
1761        ad: Android device object.
1762        anritsu_handle: Anritus device object
1763        serial_number =  serial number of CMAS message
1764        message_id =  CMAS message ID
1765        warning_message =  CMAS warning message
1766
1767    Returns:
1768        True for success False for failure
1769    """
1770    status = False
1771    event = None
1772    ad.droid.smsStartTrackingCdmaEmergencyCBMessage()
1773    anritsu_handle.send_cmas_etws_cdma1x(message_id, service_category,
1774                                         alert_text, response_type, severity,
1775                                         urgency, certainty)
1776    try:
1777        log.info("Waiting for CMAS Message")
1778        event = ad.ed.pop_event(EventCmasReceived, 60)
1779        status = True
1780        log.info(event)
1781        if alert_text != event['data']['message']:
1782            log.info("Wrong alert messgae received")
1783            status = False
1784
1785        if event['data']['cmasResponseType'].lower() != response_type.lower():
1786            log.info("Wrong response type received")
1787            status = False
1788
1789        if event['data']['cmasUrgency'].lower() != urgency.lower():
1790            log.info("Wrong cmasUrgency received")
1791            status = False
1792
1793        if event['data']['cmasSeverity'].lower() != severity.lower():
1794            Log.info("Wrong cmasSeverity received")
1795            status = False
1796    except Empty:
1797        log.info("Timeout: Expected event is not received.")
1798
1799    ad.droid.smsStopTrackingCdmaEmergencyCBMessage()
1800    return status
1801
1802
1803def etws_receive_verify_message_lte_wcdma(
1804        log, ad, anritsu_handle, serial_number, message_id, warning_message):
1805    """ Makes Anritsu to send a ETWS message and phone and verifies phone
1806        receives the message on LTE/WCDMA
1807
1808    Args:
1809        ad: Android device object.
1810        anritsu_handle: Anritus device object
1811        serial_number =  serial number of ETWS message
1812        message_id =  ETWS message ID
1813        warning_message =  ETWS warning message
1814
1815    Returns:
1816        True for success False for failure
1817    """
1818    status = False
1819    event = None
1820    if message_id == ETWS_WARNING_EARTHQUAKE:
1821        warning_type = "Earthquake"
1822    elif message_id == ETWS_WARNING_EARTHQUAKETSUNAMI:
1823        warning_type = "EarthquakeandTsunami"
1824    elif message_id == ETWS_WARNING_TSUNAMI:
1825        warning_type = "Tsunami"
1826    elif message_id == ETWS_WARNING_TEST_MESSAGE:
1827        warning_type = "test"
1828    elif message_id == ETWS_WARNING_OTHER_EMERGENCY:
1829        warning_type = "other"
1830    ad.droid.smsStartTrackingGsmEmergencyCBMessage()
1831    anritsu_handle.send_etws_lte_wcdma(
1832        hex(serial_number), message_id, warning_type, warning_message, "ON",
1833        "ON")
1834    try:
1835        log.info("Waiting for ETWS Message")
1836        event = ad.ed.pop_event(EventEtwsReceived, 60)
1837        status = True
1838        log.info(event)
1839        # TODO: b/26296388 Event data verification
1840    except Empty:
1841        log.info("Timeout: Expected event is not received.")
1842
1843    ad.droid.smsStopTrackingGsmEmergencyCBMessage()
1844    return status
1845
1846
1847def etws_receive_verify_message_cdma1x(log, ad, anritsu_handle, serial_number,
1848                                       message_id, warning_message):
1849    """ Makes Anritsu to send a ETWS message and phone and verifies phone
1850        receives the message on CDMA1X
1851
1852    Args:
1853        ad: Android device object.
1854        anritsu_handle: Anritus device object
1855        serial_number =  serial number of ETWS message
1856        message_id =  ETWS message ID
1857        warning_message =  ETWS warning message
1858
1859    Returns:
1860        True for success False for failure
1861    """
1862    status = False
1863    event = None
1864    # TODO: b/26296388 need to add logic to check etws.
1865    return status
1866
1867
1868def read_ue_identity(log, ad, anritsu_handle, identity_type):
1869    """ Get the UE identity IMSI, IMEI, IMEISV
1870
1871    Args:
1872        ad: Android device object.
1873        anritsu_handle: Anritus device object
1874        identity_type: Identity type(IMSI/IMEI/IMEISV)
1875
1876    Returns:
1877        Requested Identity value
1878    """
1879    return anritsu_handle.get_ue_identity(identity_type)
1880
1881
1882def get_transmission_mode(user_params, cell_no):
1883    """ Returns the TRANSMODE to be used from the user specified parameters
1884        or default value
1885
1886    Args:
1887        user_params: pointer to user supplied parameters
1888        cell_no: specify the cell number this BTS is configured
1889        Anritsu supports two cells. so cell_1 or cell_2
1890
1891    Returns:
1892        TM to be used
1893    """
1894    key = "cell{}_transmission_mode".format(cell_no)
1895    transmission_mode = user_params.get(key, DEFAULT_T_MODE)
1896    return transmission_mode
1897
1898
1899def get_dl_antenna(user_params, cell_no):
1900    """ Returns the DL ANTENNA to be used from the user specified parameters
1901        or default value
1902
1903    Args:
1904        user_params: pointer to user supplied parameters
1905        cell_no: specify the cell number this BTS is configured
1906        Anritsu supports two cells. so cell_1 or cell_2
1907
1908    Returns:
1909        number of DL ANTENNAS to be used
1910    """
1911    key = "cell{}_dl_antenna".format(cell_no)
1912    dl_antenna = user_params.get(key, DEFAULT_DL_ANTENNA)
1913    return dl_antenna
1914
1915
1916def get_lte_band(user_params, cell_no):
1917    """ Returns the LTE BAND to be used from the user specified parameters
1918        or default value
1919
1920    Args:
1921        user_params: pointer to user supplied parameters
1922        cell_no: specify the cell number this BTS is configured
1923        Anritsu supports two cells. so cell_1 or cell_2
1924
1925    Returns:
1926        LTE BAND to be used
1927    """
1928    key = "cell{}_lte_band".format(cell_no)
1929    band = DEFAULT_LTE_BAND[cell_no - 1]
1930    return user_params.get(key, band)
1931
1932
1933def get_wcdma_band(user_params, cell_no):
1934    """ Returns the WCDMA BAND to be used from the user specified parameters
1935        or default value
1936
1937    Args:
1938        user_params: pointer to user supplied parameters
1939        cell_no: specify the cell number this BTS is configured
1940        Anritsu supports two cells. so cell_1 or cell_2
1941
1942    Returns:
1943        WCDMA BAND to be used
1944    """
1945    key = "cell{}_wcdma_band".format(cell_no)
1946    wcdma_band = user_params.get(key, DEFAULT_WCDMA_BAND)
1947    return wcdma_band
1948
1949
1950def get_gsm_band(user_params, cell_no):
1951    """ Returns the GSM BAND to be used from the user specified parameters
1952        or default value
1953
1954    Args:
1955        user_params: pointer to user supplied parameters
1956        cell_no: specify the cell number this BTS is configured
1957        Anritsu supports two cells. so cell_1 or cell_2
1958
1959    Returns:
1960        GSM BAND to be used
1961    """
1962    key = "cell{}_gsm_band".format(cell_no)
1963    gsm_band = user_params.get(key, DEFAULT_GSM_BAND)
1964    return gsm_band
1965
1966
1967def get_1x_band(user_params, cell_no, sim_card):
1968    """ Returns the 1X BAND to be used from the user specified parameters
1969        or default value
1970
1971    Args:
1972        user_params: pointer to user supplied parameters
1973        cell_no: specify the cell number this BTS is configured
1974        Anritsu supports two cells. so cell_1 or cell_2
1975
1976    Returns:
1977        1X BAND to be used
1978    """
1979    key = "cell{}_1x_band".format(cell_no)
1980    band = VzW_CDMA1x_BAND if sim_card == VzW12349 else DEFAULT_CDMA1X_BAND
1981    return user_params.get(key, band)
1982
1983
1984def get_evdo_band(user_params, cell_no, sim_card):
1985    """ Returns the EVDO BAND to be used from the user specified parameters
1986        or default value
1987
1988    Args:
1989        user_params: pointer to user supplied parameters
1990        cell_no: specify the cell number this BTS is configured
1991        Anritsu supports two cells. so cell_1 or cell_2
1992
1993    Returns:
1994        EVDO BAND to be used
1995    """
1996    key = "cell{}_evdo_band".format(cell_no)
1997    band = VzW_EVDO_BAND if sim_card == VzW12349 else DEFAULT_EVDO_BAND
1998    return user_params.get(key, band)
1999
2000
2001def get_wcdma_rac(user_params, cell_no):
2002    """ Returns the WCDMA RAC to be used from the user specified parameters
2003        or default value
2004
2005    Args:
2006        user_params: pointer to user supplied parameters
2007        cell_no: specify the cell number this BTS is configured
2008        Anritsu supports two cells. so cell_1 or cell_2
2009
2010    Returns:
2011        WCDMA RAC to be used
2012    """
2013    key = "cell{}_wcdma_rac".format(cell_no)
2014    try:
2015        wcdma_rac = user_params[key]
2016    except KeyError:
2017        wcdma_rac = DEFAULT_RAC
2018    return wcdma_rac
2019
2020
2021def get_gsm_rac(user_params, cell_no):
2022    """ Returns the GSM RAC to be used from the user specified parameters
2023        or default value
2024
2025    Args:
2026        user_params: pointer to user supplied parameters
2027        cell_no: specify the cell number this BTS is configured
2028        Anritsu supports two cells. so cell_1 or cell_2
2029
2030    Returns:
2031        GSM RAC to be used
2032    """
2033    key = "cell{}_gsm_rac".format(cell_no)
2034    try:
2035        gsm_rac = user_params[key]
2036    except KeyError:
2037        gsm_rac = DEFAULT_RAC
2038    return gsm_rac
2039
2040
2041def get_wcdma_lac(user_params, cell_no):
2042    """ Returns the WCDMA LAC to be used from the user specified parameters
2043        or default value
2044
2045    Args:
2046        user_params: pointer to user supplied parameters
2047        cell_no: specify the cell number this BTS is configured
2048        Anritsu supports two cells. so cell_1 or cell_2
2049
2050    Returns:
2051        WCDMA LAC to be used
2052    """
2053    key = "cell{}_wcdma_lac".format(cell_no)
2054    try:
2055        wcdma_lac = user_params[key]
2056    except KeyError:
2057        wcdma_lac = DEFAULT_LAC
2058    return wcdma_lac
2059
2060
2061def get_gsm_lac(user_params, cell_no):
2062    """ Returns the GSM LAC to be used from the user specified parameters
2063        or default value
2064
2065    Args:
2066        user_params: pointer to user supplied parameters
2067        cell_no: specify the cell number this BTS is configured
2068        Anritsu supports two cells. so cell_1 or cell_2
2069
2070    Returns:
2071        GSM LAC to be used
2072    """
2073    key = "cell{}_gsm_lac".format(cell_no)
2074    try:
2075        gsm_lac = user_params[key]
2076    except KeyError:
2077        gsm_lac = DEFAULT_LAC
2078    return gsm_lac
2079
2080
2081def get_lte_mcc(user_params, cell_no, sim_card):
2082    """ Returns the LTE MCC to be used from the user specified parameters
2083        or default value
2084
2085    Args:
2086        user_params: pointer to user supplied parameters
2087        cell_no: specify the cell number this BTS is configured
2088        Anritsu supports two cells. so cell_1 or cell_2
2089
2090    Returns:
2091        LTE MCC to be used
2092    """
2093
2094    key = "cell{}_lte_mcc".format(cell_no)
2095    mcc = VzW_MCC if sim_card == VzW12349 else DEFAULT_MCC
2096    return user_params.get(key, mcc)
2097
2098
2099def get_lte_mnc(user_params, cell_no, sim_card):
2100    """ Returns the LTE MNC to be used from the user specified parameters
2101        or default value
2102
2103    Args:
2104        user_params: pointer to user supplied parameters
2105        cell_no: specify the cell number this BTS is configured
2106        Anritsu supports two cells. so cell_1 or cell_2
2107
2108    Returns:
2109        LTE MNC to be used
2110    """
2111    key = "cell{}_lte_mnc".format(cell_no)
2112    mnc = VzW_MNC if sim_card == VzW12349 else DEFAULT_MNC
2113    return user_params.get(key, mnc)
2114
2115
2116def get_wcdma_mcc(user_params, cell_no, sim_card):
2117    """ Returns the WCDMA MCC to be used from the user specified parameters
2118        or default value
2119
2120    Args:
2121        user_params: pointer to user supplied parameters
2122        cell_no: specify the cell number this BTS is configured
2123        Anritsu supports two cells. so cell_1 or cell_2
2124
2125    Returns:
2126        WCDMA MCC to be used
2127    """
2128    key = "cell{}_wcdma_mcc".format(cell_no)
2129    mcc = VzW_MCC if sim_card == VzW12349 else DEFAULT_MCC
2130    return user_params.get(key, mcc)
2131
2132
2133def get_wcdma_mnc(user_params, cell_no, sim_card):
2134    """ Returns the WCDMA MNC to be used from the user specified parameters
2135        or default value
2136
2137    Args:
2138        user_params: pointer to user supplied parameters
2139        cell_no: specify the cell number this BTS is configured
2140        Anritsu supports two cells. so cell_1 or cell_2
2141
2142    Returns:
2143        WCDMA MNC to be used
2144    """
2145    key = "cell{}_wcdma_mnc".format(cell_no)
2146    mnc = VzW_MNC if sim_card == VzW12349 else DEFAULT_MNC
2147    return user_params.get(key, mnc)
2148
2149
2150def get_gsm_mcc(user_params, cell_no, sim_card):
2151    """ Returns the GSM MCC to be used from the user specified parameters
2152        or default value
2153
2154    Args:
2155        user_params: pointer to user supplied parameters
2156        cell_no: specify the cell number this BTS is configured
2157        Anritsu supports two cells. so cell_1 or cell_2
2158
2159    Returns:
2160        GSM MCC to be used
2161    """
2162    key = "cell{}_gsm_mcc".format(cell_no)
2163    mcc = VzW_MCC if sim_card == VzW12349 else DEFAULT_MCC
2164    return user_params.get(key, mcc)
2165
2166
2167def get_gsm_mnc(user_params, cell_no, sim_card):
2168    """ Returns the GSM MNC to be used from the user specified parameters
2169        or default value
2170
2171    Args:
2172        user_params: pointer to user supplied parameters
2173        cell_no: specify the cell number this BTS is configured
2174        Anritsu supports two cells. so cell_1 or cell_2
2175
2176    Returns:
2177        GSM MNC to be used
2178    """
2179    key = "cell{}_gsm_mnc".format(cell_no)
2180    mnc = VzW_MNC if sim_card == VzW12349 else DEFAULT_MNC
2181    return user_params.get(key, mnc)
2182
2183
2184def get_1x_mcc(user_params, cell_no, sim_card):
2185    """ Returns the 1X MCC to be used from the user specified parameters
2186        or default value
2187
2188    Args:
2189        user_params: pointer to user supplied parameters
2190        cell_no: specify the cell number this BTS is configured
2191        Anritsu supports two cells. so cell_1 or cell_2
2192
2193    Returns:
2194        1X MCC to be used
2195    """
2196    key = "cell{}_1x_mcc".format(cell_no)
2197    mcc = VzW_MCC if sim_card == VzW12349 else DEFAULT_MCC
2198    return user_params.get(key, mcc)
2199
2200
2201def get_1x_channel(user_params, cell_no, sim_card):
2202    """ Returns the 1X Channel to be used from the user specified parameters
2203        or default value
2204
2205    Args:
2206        user_params: pointer to user supplied parameters
2207        cell_no: specify the cell number this BTS is configured
2208        Anritsu supports two cells. so cell_1 or cell_2
2209
2210    Returns:
2211        1X Channel to be used
2212    """
2213    key = "cell{}_1x_channel".format(cell_no)
2214    ch = VzW_CDMA1x_CH if sim_card == VzW12349 else DEFAULT_CDMA1X_CH
2215    return user_params.get(key, ch)
2216
2217
2218def get_1x_sid(user_params, cell_no, sim_card):
2219    """ Returns the 1X SID to be used from the user specified parameters
2220        or default value
2221
2222    Args:
2223        user_params: pointer to user supplied parameters
2224        cell_no: specify the cell number this BTS is configured
2225        Anritsu supports two cells. so cell_1 or cell_2
2226
2227    Returns:
2228        1X SID to be used
2229    """
2230    key = "cell{}_1x_sid".format(cell_no)
2231    sid = VzW_CDMA1X_SID if sim_card == VzW12349 else DEFAULT_CDMA1X_SID
2232    return user_params.get(key, sid)
2233
2234
2235def get_1x_nid(user_params, cell_no, sim_card):
2236    """ Returns the 1X NID to be used from the user specified parameters
2237        or default value
2238
2239    Args:
2240        user_params: pointer to user supplied parameters
2241        cell_no: specify the cell number this BTS is configured
2242        Anritsu supports two cells. so cell_1 or cell_2
2243
2244    Returns:
2245        1X NID to be used
2246    """
2247    key = "cell{}_1x_nid".format(cell_no)
2248    nid = VzW_CDMA1X_NID if sim_card == VzW12349 else DEFAULT_CDMA1X_NID
2249    return user_params.get(key, nid)
2250
2251
2252def get_evdo_channel(user_params, cell_no, sim_card):
2253    """ Returns the EVDO Channel to be used from the user specified parameters
2254        or default value
2255
2256    Args:
2257        user_params: pointer to user supplied parameters
2258        cell_no: specify the cell number this BTS is configured
2259        Anritsu supports two cells. so cell_1 or cell_2
2260
2261    Returns:
2262        EVDO Channel to be used
2263    """
2264    key = "cell{}_evdo_channel".format(cell_no)
2265    ch = VzW_EVDO_CH if sim_card == VzW12349 else DEFAULT_EVDO_CH
2266    return user_params.get(key, ch)
2267
2268
2269def get_evdo_sid(user_params, cell_no, sim_card):
2270    """ Returns the EVDO SID to be used from the user specified parameters
2271        or default value
2272
2273    Args:
2274        user_params: pointer to user supplied parameters
2275        cell_no: specify the cell number this BTS is configured
2276        Anritsu supports two cells. so cell_1 or cell_2
2277
2278    Returns:
2279        EVDO SID to be used
2280    """
2281    key = "cell{}_evdo_sid".format(cell_no)
2282    return user_params.get(key, DEFAULT_EVDO_SECTOR_ID)
2283    sid = VzW_EVDO_SECTOR_ID if sim_card == VzW12349 else DEFAULT_EVDO_SECTOR_ID
2284    return user_params.get(key, sid)
2285
2286
2287def get_csfb_type(user_params):
2288    """ Returns the CSFB Type to be used from the user specified parameters
2289        or default value
2290
2291    Args:
2292        user_params: pointer to user supplied parameters
2293        cell_no: specify the cell number this BTS is configured
2294        Anritsu supports two cells. so cell_1 or cell_2
2295
2296    Returns:
2297        CSFB Type to be used
2298    """
2299    try:
2300        csfb_type = user_params["csfb_type"]
2301    except KeyError:
2302        csfb_type = CsfbType.CSFB_TYPE_REDIRECTION
2303    return csfb_type
2304
2305
2306def set_post_sim_params(anritsu_handle, user_params, sim_card):
2307    if sim_card == P0135Ax:
2308        anritsu_handle.send_command("PDNCHECKAPN 1,ims")
2309        anritsu_handle.send_command("PDNCHECKAPN 2,fast.t-mobile.com")
2310        anritsu_handle.send_command("PDNIMS 1,ENABLE")
2311        anritsu_handle.send_command("PDNVNID 1,1")
2312        anritsu_handle.send_command("PDNIMS 2,ENABLE")
2313        anritsu_handle.send_command("PDNVNID 2,2")
2314        anritsu_handle.send_command("PDNIMS 3,ENABLE")
2315        anritsu_handle.send_command("PDNVNID 3,1")
2316    if sim_card == VzW12349:
2317        anritsu_handle.send_command("PDNCHECKAPN 1,IMS")
2318        anritsu_handle.send_command("PDNCHECKAPN 2,VZWINTERNET")
2319        anritsu_handle.send_command("PDNIMS 1,ENABLE")
2320        anritsu_handle.send_command("PDNVNID 1,1")
2321        anritsu_handle.send_command("PDNIMS 3,ENABLE")
2322        anritsu_handle.send_command("PDNVNID 3,1")
2323