1#!/usr/bin/env python3
2#
3#   Copyright 2021 - Google
4#
5#   Licensed under the Apache License, Version 2.0 (the "License");
6#   you may not use this file except in compliance with the License.
7#   You may obtain a copy of the License at
8#
9#       http://www.apache.org/licenses/LICENSE-2.0
10#
11#   Unless required by applicable law or agreed to in writing, software
12#   distributed under the License is distributed on an "AS IS" BASIS,
13#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14#   See the License for the specific language governing permissions and
15#   limitations under the License.
16
17import re
18import time
19from queue import Empty
20from acts import signals
21from acts.utils import rand_ascii_str
22from acts.libs.utils.multithread import multithread_func
23from acts.libs.utils.multithread import run_multithread_func
24from acts_contrib.test_utils.tel.tel_defines import EventCallStateChanged
25from acts_contrib.test_utils.tel.tel_defines import EventMmsSentFailure
26from acts_contrib.test_utils.tel.tel_defines import EventMmsSentSuccess
27from acts_contrib.test_utils.tel.tel_defines import EventMmsDownloaded
28from acts_contrib.test_utils.tel.tel_defines import EventSmsDeliverFailure
29from acts_contrib.test_utils.tel.tel_defines import EventSmsDeliverSuccess
30from acts_contrib.test_utils.tel.tel_defines import EventSmsReceived
31from acts_contrib.test_utils.tel.tel_defines import EventSmsSentFailure
32from acts_contrib.test_utils.tel.tel_defines import EventSmsSentSuccess
33from acts_contrib.test_utils.tel.tel_defines import INCALL_UI_DISPLAY_BACKGROUND
34from acts_contrib.test_utils.tel.tel_defines import INCALL_UI_DISPLAY_FOREGROUND
35from acts_contrib.test_utils.tel.tel_defines import MAX_WAIT_TIME_MMS_RECEIVE
36from acts_contrib.test_utils.tel.tel_defines import MAX_WAIT_TIME_SMS_RECEIVE
37from acts_contrib.test_utils.tel.tel_defines import MAX_WAIT_TIME_SMS_RECEIVE_IN_COLLISION
38from acts_contrib.test_utils.tel.tel_defines import MAX_WAIT_TIME_SMS_SENT_SUCCESS_IN_COLLISION
39from acts_contrib.test_utils.tel.tel_defines import SMS_OVER_WIFI_PROVIDERS
40from acts_contrib.test_utils.tel.tel_defines import WAIT_TIME_ANDROID_STATE_SETTLING
41from acts_contrib.test_utils.tel.tel_defines import WAIT_TIME_IN_CALL
42from acts_contrib.test_utils.tel.tel_defines import VT_STATE_BIDIRECTIONAL
43from acts_contrib.test_utils.tel.tel_defines import WFC_MODE_DISABLED
44from acts_contrib.test_utils.tel.tel_phone_setup_utils import phone_setup_on_rat
45from acts_contrib.test_utils.tel.tel_subscription_utils import get_incoming_message_sub_id
46from acts_contrib.test_utils.tel.tel_subscription_utils import get_outgoing_message_sub_id
47from acts_contrib.test_utils.tel.tel_subscription_utils import get_subid_from_slot_index
48from acts_contrib.test_utils.tel.tel_subscription_utils import get_subid_on_same_network_of_host_ad
49from acts_contrib.test_utils.tel.tel_subscription_utils import set_subid_for_message
50from acts_contrib.test_utils.tel.tel_test_utils import CallResult
51from acts_contrib.test_utils.tel.tel_test_utils import TelResultWrapper
52from acts_contrib.test_utils.tel.tel_test_utils import check_phone_number_match
53from acts_contrib.test_utils.tel.tel_test_utils import get_device_epoch_time
54from acts_contrib.test_utils.tel.tel_test_utils import toggle_airplane_mode
55from acts_contrib.test_utils.tel.tel_voice_utils import call_setup_teardown
56from acts_contrib.test_utils.tel.tel_voice_utils import hangup_call
57from acts_contrib.test_utils.tel.tel_voice_utils import is_phone_in_call
58from acts_contrib.test_utils.tel.tel_voice_utils import last_call_drop_reason
59from acts_contrib.test_utils.tel.tel_voice_utils import is_phone_in_call_on_rat
60from acts_contrib.test_utils.tel.tel_voice_utils import wait_and_answer_call_for_subscription
61from acts_contrib.test_utils.tel.tel_voice_utils import wait_for_in_call_active
62from acts_contrib.test_utils.tel.tel_voice_utils import wait_for_call_end
63from acts_contrib.test_utils.tel.tel_voice_utils import wait_for_call_offhook_for_subscription
64from acts_contrib.test_utils.tel.tel_video_utils import is_phone_in_call_video_bidirectional
65from acts_contrib.test_utils.tel.tel_video_utils import video_call_setup_teardown
66from acts_contrib.test_utils.tel.tel_video_utils import phone_idle_video
67from acts_contrib.test_utils.tel.tel_wifi_utils import ensure_wifi_connected
68
69
70def send_message_with_random_message_body(
71    log, ad_mo, ad_mt, msg_type='sms', long_msg=False, mms_expected_result=True):
72    """Test SMS/MMS between two phones.
73    Returns:
74        True if success.
75        False if failed.
76    """
77    message_lengths = (50, 160, 180)
78
79    if long_msg:
80        message_lengths = (800, 1600)
81        message_lengths_of_jp_carriers = (800, 1530)
82        sender_message_sub_id = get_outgoing_message_sub_id(ad_mo)
83        sender_mcc = ad_mo.telephony["subscription"][sender_message_sub_id]["mcc"]
84        if str(sender_mcc) in ["440", "441"]:
85            message_lengths = message_lengths_of_jp_carriers
86
87    if msg_type == 'sms':
88        for length in message_lengths:
89            message_array = [rand_ascii_str(length)]
90            if not sms_send_receive_verify(log, ad_mo, ad_mt, message_array):
91                ad_mo.log.error("SMS of length %s test failed", length)
92                return False
93            else:
94                ad_mo.log.info("SMS of length %s test succeeded", length)
95        log.info("SMS test of length %s characters succeeded.",
96                    message_lengths)
97    elif msg_type == 'mms':
98        is_roaming = False
99        for ad in [ad_mo, ad_mt]:
100            ad.sms_over_wifi = False
101            # verizon supports sms over wifi. will add more carriers later
102            for sub in ad.telephony["subscription"].values():
103                if sub["operator"] in SMS_OVER_WIFI_PROVIDERS:
104                    ad.sms_over_wifi = True
105
106            if getattr(ad, 'roaming', False):
107                is_roaming = True
108
109        if is_roaming:
110            # roaming device does not allow message of length 180
111            message_lengths = (50, 160)
112
113        for length in message_lengths:
114            message_array = [("Test Message", rand_ascii_str(length), None)]
115            result = True
116            if not mms_send_receive_verify(
117                    log,
118                    ad_mo,
119                    ad_mt,
120                    message_array,
121                    expected_result=mms_expected_result):
122
123                if mms_expected_result is True:
124                    if ad_mo.droid.telecomIsInCall() or ad_mt.droid.telecomIsInCall():
125                        if not mms_receive_verify_after_call_hangup(
126                            log, ad_mo, ad_mt, message_array):
127                            result = False
128                    else:
129                        result = False
130
131                if not result:
132                    log.error("MMS of body length %s test failed", length)
133                    return False
134            else:
135                log.info("MMS of body length %s test succeeded", length)
136        log.info("MMS test of body lengths %s succeeded", message_lengths)
137    return True
138
139def message_test(
140    log,
141    ad_mo,
142    ad_mt,
143    mo_rat='general',
144    mt_rat='general',
145    msg_type='sms',
146    long_msg=False,
147    mms_expected_result=True,
148    msg_in_call=False,
149    video_or_voice='voice',
150    is_airplane_mode=False,
151    wfc_mode=None,
152    wifi_ssid=None,
153    wifi_pwd=None):
154
155    mo_phone_setup_argv = (
156        log, ad_mo, 'general', None, False, None, None, None, None, 'sms')
157    mt_phone_setup_argv = (
158        log, ad_mt, 'general', None, False, None, None, None, None, 'sms')
159    verify_caller_func = None
160    verify_callee_func = None
161
162    if long_msg:
163      for ad in [ad_mo, ad_mt]:
164        ad.root_adb()
165        # set max sms length to 10000 for long sms test
166        ad.adb.shell("settings put global sms_outgoing_check_max_count 10000")
167
168    if mo_rat:
169        mo_phone_setup_argv = (
170            log,
171            ad_mo,
172            mo_rat,
173            None,
174            is_airplane_mode,
175            wfc_mode,
176            wifi_ssid,
177            wifi_pwd,
178            None,
179            'sms')
180        verify_caller_func = is_phone_in_call_on_rat(
181            log, ad_mo, rat=mo_rat, only_return_fn=True)
182
183    if mt_rat:
184        mt_phone_setup_argv = (
185            log,
186            ad_mt,
187            mt_rat,
188            None,
189            is_airplane_mode,
190            wfc_mode,
191            wifi_ssid,
192            wifi_pwd,
193            None,
194            'sms')
195        verify_callee_func = is_phone_in_call_on_rat(
196            log, ad_mo, rat=mt_rat, only_return_fn=True)
197
198    tasks = [(phone_setup_on_rat, mo_phone_setup_argv),
199                (phone_setup_on_rat, mt_phone_setup_argv)]
200    if not multithread_func(log, tasks):
201        log.error("Phone Failed to Set Up Properly.")
202        return False
203    time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
204
205    if wifi_ssid:
206        if not wfc_mode or wfc_mode == WFC_MODE_DISABLED:
207            tasks = [(ensure_wifi_connected, (log, ad_mo, wifi_ssid, wifi_pwd)),
208                    (ensure_wifi_connected, (log, ad_mt, wifi_ssid, wifi_pwd))]
209            if not multithread_func(log, tasks):
210                log.error("Failed to connected to Wi-Fi.")
211                return False
212
213    if msg_in_call:
214        if video_or_voice == 'voice':
215            if not call_setup_teardown(
216                    log,
217                    ad_mo,
218                    ad_mt,
219                    ad_hangup=None,
220                    verify_caller_func=verify_caller_func,
221                    verify_callee_func=verify_callee_func):
222                log.error("Failed to setup a voice call")
223                return False
224        elif video_or_voice == 'video':
225            tasks = [
226                (phone_idle_video, (log, ad_mo)),
227                (phone_idle_video, (log, ad_mt))]
228            if not multithread_func(log, tasks):
229                log.error("Phone Failed to Set Up Properly.")
230                return False
231            time.sleep(WAIT_TIME_ANDROID_STATE_SETTLING)
232            if not video_call_setup_teardown(
233                    log,
234                    ad_mo,
235                    ad_mt,
236                    None,
237                    video_state=VT_STATE_BIDIRECTIONAL,
238                    verify_caller_func=is_phone_in_call_video_bidirectional,
239                    verify_callee_func=is_phone_in_call_video_bidirectional):
240                log.error("Failed to setup a video call")
241                return False
242
243    result = True
244    if not send_message_with_random_message_body(
245        log, ad_mo, ad_mt, msg_type, long_msg, mms_expected_result):
246        log.error("Test failed.")
247        result = False
248
249    if msg_in_call:
250        if not hangup_call(log, ad_mo):
251            ad_mo.log.info("Failed to hang up call!")
252            result = False
253
254    return result
255
256def sms_send_receive_verify(log,
257                            ad_tx,
258                            ad_rx,
259                            array_message,
260                            max_wait_time=MAX_WAIT_TIME_SMS_RECEIVE,
261                            expected_result=True,
262                            slot_id_rx=None):
263    """Send SMS, receive SMS, and verify content and sender's number.
264
265        Send (several) SMS from droid_tx to droid_rx.
266        Verify SMS is sent, delivered and received.
267        Verify received content and sender's number are correct.
268
269    Args:
270        log: Log object.
271        ad_tx: Sender's Android Device Object
272        ad_rx: Receiver's Android Device Object
273        array_message: the array of message to send/receive
274        slot_id_rx: the slot on the Receiver's android device (0/1)
275    """
276    subid_tx = get_outgoing_message_sub_id(ad_tx)
277    if slot_id_rx is None:
278        subid_rx = get_incoming_message_sub_id(ad_rx)
279    else:
280        subid_rx = get_subid_from_slot_index(log, ad_rx, slot_id_rx)
281
282    result = sms_send_receive_verify_for_subscription(
283        log, ad_tx, ad_rx, subid_tx, subid_rx, array_message, max_wait_time)
284    if result != expected_result:
285        log_messaging_screen_shot(ad_tx, test_name="sms_tx")
286        log_messaging_screen_shot(ad_rx, test_name="sms_rx")
287    return result == expected_result
288
289def sms_send_receive_verify_for_subscription(
290        log,
291        ad_tx,
292        ad_rx,
293        subid_tx,
294        subid_rx,
295        array_message,
296        max_wait_time=MAX_WAIT_TIME_SMS_RECEIVE):
297    """Send SMS, receive SMS, and verify content and sender's number.
298
299        Send (several) SMS from droid_tx to droid_rx.
300        Verify SMS is sent, delivered and received.
301        Verify received content and sender's number are correct.
302
303    Args:
304        log: Log object.
305        ad_tx: Sender's Android Device Object..
306        ad_rx: Receiver's Android Device Object.
307        subid_tx: Sender's subscription ID to be used for SMS
308        subid_rx: Receiver's subscription ID to be used for SMS
309        array_message: the array of message to send/receive
310    """
311    phonenumber_tx = ad_tx.telephony['subscription'][subid_tx]['phone_num']
312    phonenumber_rx = ad_rx.telephony['subscription'][subid_rx]['phone_num']
313
314    for ad in (ad_tx, ad_rx):
315        if not getattr(ad, "messaging_droid", None):
316            ad.messaging_droid, ad.messaging_ed = ad.get_droid()
317            ad.messaging_ed.start()
318        else:
319            try:
320                if not ad.messaging_droid.is_live:
321                    ad.messaging_droid, ad.messaging_ed = ad.get_droid()
322                    ad.messaging_ed.start()
323                else:
324                    ad.messaging_ed.clear_all_events()
325                ad.messaging_droid.logI(
326                    "Start sms_send_receive_verify_for_subscription test")
327            except Exception:
328                ad.log.info("Create new sl4a session for messaging")
329                ad.messaging_droid, ad.messaging_ed = ad.get_droid()
330                ad.messaging_ed.start()
331
332    for text in array_message:
333        length = len(text)
334        ad_tx.log.info("Sending SMS from %s to %s, len: %s, content: %s.",
335                       phonenumber_tx, phonenumber_rx, length, text)
336        try:
337            ad_rx.messaging_ed.clear_events(EventSmsReceived)
338            ad_tx.messaging_ed.clear_events(EventSmsSentSuccess)
339            ad_tx.messaging_ed.clear_events(EventSmsSentFailure)
340            ad_rx.messaging_droid.smsStartTrackingIncomingSmsMessage()
341            time.sleep(1)  #sleep 100ms after starting event tracking
342            ad_tx.messaging_droid.logI("Sending SMS of length %s" % length)
343            ad_rx.messaging_droid.logI("Expecting SMS of length %s" % length)
344            ad_tx.messaging_droid.smsSendTextMessage(phonenumber_rx, text,
345                                                     True)
346            try:
347                events = ad_tx.messaging_ed.pop_events(
348                    "(%s|%s|%s|%s)" %
349                    (EventSmsSentSuccess, EventSmsSentFailure,
350                     EventSmsDeliverSuccess,
351                     EventSmsDeliverFailure), max_wait_time)
352                for event in events:
353                    ad_tx.log.info("Got event %s", event["name"])
354                    if event["name"] == EventSmsSentFailure or event["name"] == EventSmsDeliverFailure:
355                        if event.get("data") and event["data"].get("Reason"):
356                            ad_tx.log.error("%s with reason: %s",
357                                            event["name"],
358                                            event["data"]["Reason"])
359                        return False
360                    elif event["name"] == EventSmsSentSuccess or event["name"] == EventSmsDeliverSuccess:
361                        break
362            except Empty:
363                ad_tx.log.error("No %s or %s event for SMS of length %s.",
364                                EventSmsSentSuccess, EventSmsSentFailure,
365                                length)
366                return False
367
368            if not wait_for_matching_sms(
369                    log,
370                    ad_rx,
371                    phonenumber_tx,
372                    text,
373                    max_wait_time,
374                    allow_multi_part_long_sms=True):
375                ad_rx.log.error("No matching received SMS of length %s.",
376                                length)
377                return False
378        except Exception as e:
379            log.error("Exception error %s", e)
380            raise
381        finally:
382            ad_rx.messaging_droid.smsStopTrackingIncomingSmsMessage()
383    return True
384
385def sms_in_collision_send_receive_verify(
386        log,
387        ad_rx,
388        ad_rx2,
389        ad_tx,
390        ad_tx2,
391        array_message,
392        array_message2,
393        max_wait_time=MAX_WAIT_TIME_SMS_RECEIVE_IN_COLLISION):
394    """Send 2 SMS', receive both SMS', and verify content and sender's number of
395       each SMS.
396
397        Send 2 SMS'. One from ad_tx to ad_rx and the other from ad_tx2 to ad_rx2.
398        When ad_rx is identical to ad_rx2, the scenario of SMS' in collision can
399        be tested.
400        Verify both SMS' are sent, delivered and received.
401        Verify received content and sender's number of each SMS is correct.
402
403    Args:
404        log: Log object.
405        ad_tx: Sender's Android Device Object..
406        ad_rx: Receiver's Android Device Object.
407        ad_tx2: 2nd sender's Android Device Object..
408        ad_rx2: 2nd receiver's Android Device Object.
409        array_message: the array of message to send/receive from ad_tx to ad_rx
410        array_message2: the array of message to send/receive from ad_tx2 to
411        ad_rx2
412        max_wait_time: Max time to wait for reception of SMS
413    """
414    rx_sub_id = get_outgoing_message_sub_id(ad_rx)
415    rx2_sub_id = get_outgoing_message_sub_id(ad_rx2)
416
417    _, tx_sub_id, _ = get_subid_on_same_network_of_host_ad(
418        [ad_rx, ad_tx, ad_tx2],
419        host_sub_id=rx_sub_id)
420    set_subid_for_message(ad_tx, tx_sub_id)
421
422    _, _, tx2_sub_id = get_subid_on_same_network_of_host_ad(
423        [ad_rx2, ad_tx, ad_tx2],
424        host_sub_id=rx2_sub_id)
425    set_subid_for_message(ad_tx2, tx2_sub_id)
426
427    if not sms_in_collision_send_receive_verify_for_subscription(
428        log,
429        ad_tx,
430        ad_tx2,
431        ad_rx,
432        ad_rx2,
433        tx_sub_id,
434        tx2_sub_id,
435        rx_sub_id,
436        rx_sub_id,
437        array_message,
438        array_message2,
439        max_wait_time):
440        log_messaging_screen_shot(
441            ad_rx, test_name="sms rx subid: %s" % rx_sub_id)
442        log_messaging_screen_shot(
443            ad_rx2, test_name="sms rx2 subid: %s" % rx2_sub_id)
444        log_messaging_screen_shot(
445            ad_tx, test_name="sms tx subid: %s" % tx_sub_id)
446        log_messaging_screen_shot(
447            ad_tx2, test_name="sms tx subid: %s" % tx2_sub_id)
448        return False
449    return True
450
451def sms_in_collision_send_receive_verify_for_subscription(
452        log,
453        ad_tx,
454        ad_tx2,
455        ad_rx,
456        ad_rx2,
457        subid_tx,
458        subid_tx2,
459        subid_rx,
460        subid_rx2,
461        array_message,
462        array_message2,
463        max_wait_time=MAX_WAIT_TIME_SMS_RECEIVE_IN_COLLISION):
464    """Send 2 SMS', receive both SMS', and verify content and sender's number of
465       each SMS.
466
467        Send 2 SMS'. One from ad_tx to ad_rx and the other from ad_tx2 to ad_rx2.
468        When ad_rx is identical to ad_rx2, the scenario of SMS' in collision can
469        be tested.
470        Verify both SMS' are sent, delivered and received.
471        Verify received content and sender's number of each SMS is correct.
472
473    Args:
474        log: Log object.
475        ad_tx: Sender's Android Device Object..
476        ad_rx: Receiver's Android Device Object.
477        ad_tx2: 2nd sender's Android Device Object..
478        ad_rx2: 2nd receiver's Android Device Object.
479        subid_tx: Sub ID of ad_tx as default Sub ID for outgoing SMS
480        subid_tx2: Sub ID of ad_tx2 as default Sub ID for outgoing SMS
481        subid_rx: Sub ID of ad_rx as default Sub ID for incoming SMS
482        subid_rx2: Sub ID of ad_rx2 as default Sub ID for incoming SMS
483        array_message: the array of message to send/receive from ad_tx to ad_rx
484        array_message2: the array of message to send/receive from ad_tx2 to
485        ad_rx2
486        max_wait_time: Max time to wait for reception of SMS
487    """
488
489    phonenumber_tx = ad_tx.telephony['subscription'][subid_tx]['phone_num']
490    phonenumber_tx2 = ad_tx2.telephony['subscription'][subid_tx2]['phone_num']
491    phonenumber_rx = ad_rx.telephony['subscription'][subid_rx]['phone_num']
492    phonenumber_rx2 = ad_rx2.telephony['subscription'][subid_rx2]['phone_num']
493
494    for ad in (ad_tx, ad_tx2, ad_rx, ad_rx2):
495        ad.send_keycode("BACK")
496        if not getattr(ad, "messaging_droid", None):
497            ad.messaging_droid, ad.messaging_ed = ad.get_droid()
498            ad.messaging_ed.start()
499        else:
500            try:
501                if not ad.messaging_droid.is_live:
502                    ad.messaging_droid, ad.messaging_ed = ad.get_droid()
503                    ad.messaging_ed.start()
504                else:
505                    ad.messaging_ed.clear_all_events()
506                ad.messaging_droid.logI(
507                    "Start sms_send_receive_verify_for_subscription test")
508            except Exception:
509                ad.log.info("Create new sl4a session for messaging")
510                ad.messaging_droid, ad.messaging_ed = ad.get_droid()
511                ad.messaging_ed.start()
512
513    for text, text2 in zip(array_message, array_message2):
514        length = len(text)
515        length2 = len(text2)
516        ad_tx.log.info("Sending SMS from %s to %s, len: %s, content: %s.",
517                       phonenumber_tx, phonenumber_rx, length, text)
518        ad_tx2.log.info("Sending SMS from %s to %s, len: %s, content: %s.",
519                       phonenumber_tx2, phonenumber_rx2, length2, text2)
520
521        try:
522            ad_rx.messaging_ed.clear_events(EventSmsReceived)
523            ad_rx2.messaging_ed.clear_events(EventSmsReceived)
524            ad_tx.messaging_ed.clear_events(EventSmsSentSuccess)
525            ad_tx.messaging_ed.clear_events(EventSmsSentFailure)
526            ad_tx2.messaging_ed.clear_events(EventSmsSentSuccess)
527            ad_tx2.messaging_ed.clear_events(EventSmsSentFailure)
528            ad_rx.messaging_droid.smsStartTrackingIncomingSmsMessage()
529            if ad_rx2 != ad_rx:
530                ad_rx2.messaging_droid.smsStartTrackingIncomingSmsMessage()
531            time.sleep(1)
532            ad_tx.messaging_droid.logI("Sending SMS of length %s" % length)
533            ad_tx2.messaging_droid.logI("Sending SMS of length %s" % length2)
534            ad_rx.messaging_droid.logI(
535                "Expecting SMS of length %s from %s" % (length, ad_tx.serial))
536            ad_rx2.messaging_droid.logI(
537                "Expecting SMS of length %s from %s" % (length2, ad_tx2.serial))
538
539            tasks = [
540                (ad_tx.messaging_droid.smsSendTextMessage,
541                (phonenumber_rx, text, True)),
542                (ad_tx2.messaging_droid.smsSendTextMessage,
543                (phonenumber_rx2, text2, True))]
544            multithread_func(log, tasks)
545            try:
546                tasks = [
547                    (ad_tx.messaging_ed.pop_events, ("(%s|%s|%s|%s)" % (
548                        EventSmsSentSuccess,
549                        EventSmsSentFailure,
550                        EventSmsDeliverSuccess,
551                        EventSmsDeliverFailure), max_wait_time)),
552                    (ad_tx2.messaging_ed.pop_events, ("(%s|%s|%s|%s)" % (
553                        EventSmsSentSuccess,
554                        EventSmsSentFailure,
555                        EventSmsDeliverSuccess,
556                        EventSmsDeliverFailure), max_wait_time))
557                ]
558                results = run_multithread_func(log, tasks)
559                res = True
560                _ad = ad_tx
561                for ad, events in [(ad_tx, results[0]),(ad_tx2, results[1])]:
562                    _ad = ad
563                    for event in events:
564                        ad.log.info("Got event %s", event["name"])
565                        if event["name"] == EventSmsSentFailure or \
566                            event["name"] == EventSmsDeliverFailure:
567                            if event.get("data") and event["data"].get("Reason"):
568                                ad.log.error("%s with reason: %s",
569                                                event["name"],
570                                                event["data"]["Reason"])
571                            res = False
572                        elif event["name"] == EventSmsSentSuccess or \
573                            event["name"] == EventSmsDeliverSuccess:
574                            break
575                if not res:
576                    return False
577            except Empty:
578                _ad.log.error("No %s or %s event for SMS of length %s.",
579                                EventSmsSentSuccess, EventSmsSentFailure,
580                                length)
581                return False
582            if ad_rx == ad_rx2:
583                if not wait_for_matching_mt_sms_in_collision(
584                    log,
585                    ad_rx,
586                    phonenumber_tx,
587                    phonenumber_tx2,
588                    text,
589                    text2,
590                    max_wait_time=MAX_WAIT_TIME_SMS_RECEIVE_IN_COLLISION):
591
592                    ad_rx.log.error(
593                        "No matching received SMS of length %s from %s.",
594                        length,
595                        ad_rx.serial)
596                    return False
597            else:
598                if not wait_for_matching_mt_sms_in_collision_with_mo_sms(
599                    log,
600                    ad_rx,
601                    ad_rx2,
602                    phonenumber_tx,
603                    phonenumber_tx2,
604                    text,
605                    text2,
606                    max_wait_time=MAX_WAIT_TIME_SMS_RECEIVE_IN_COLLISION):
607                    return False
608        except Exception as e:
609            log.error("Exception error %s", e)
610            raise
611        finally:
612            ad_rx.messaging_droid.smsStopTrackingIncomingSmsMessage()
613            ad_rx2.messaging_droid.smsStopTrackingIncomingSmsMessage()
614    return True
615
616def sms_rx_power_off_multiple_send_receive_verify(
617        log,
618        ad_rx,
619        ad_tx,
620        ad_tx2,
621        array_message_length,
622        array_message2_length,
623        num_array_message,
624        num_array_message2,
625        max_wait_time=MAX_WAIT_TIME_SMS_RECEIVE_IN_COLLISION):
626
627    rx_sub_id = get_outgoing_message_sub_id(ad_rx)
628
629    _, tx_sub_id, _ = get_subid_on_same_network_of_host_ad(
630        [ad_rx, ad_tx, ad_tx2],
631        host_sub_id=rx_sub_id)
632    set_subid_for_message(ad_tx, tx_sub_id)
633
634    _, _, tx2_sub_id = get_subid_on_same_network_of_host_ad(
635        [ad_rx, ad_tx, ad_tx2],
636        host_sub_id=rx_sub_id)
637    set_subid_for_message(ad_tx2, tx2_sub_id)
638
639    if not sms_rx_power_off_multiple_send_receive_verify_for_subscription(
640        log,
641        ad_tx,
642        ad_tx2,
643        ad_rx,
644        tx_sub_id,
645        tx2_sub_id,
646        rx_sub_id,
647        rx_sub_id,
648        array_message_length,
649        array_message2_length,
650        num_array_message,
651        num_array_message2):
652        log_messaging_screen_shot(
653            ad_rx, test_name="sms rx subid: %s" % rx_sub_id)
654        log_messaging_screen_shot(
655            ad_tx, test_name="sms tx subid: %s" % tx_sub_id)
656        log_messaging_screen_shot(
657            ad_tx2, test_name="sms tx subid: %s" % tx2_sub_id)
658        return False
659    return True
660
661def sms_rx_power_off_multiple_send_receive_verify_for_subscription(
662        log,
663        ad_tx,
664        ad_tx2,
665        ad_rx,
666        subid_tx,
667        subid_tx2,
668        subid_rx,
669        subid_rx2,
670        array_message_length,
671        array_message2_length,
672        num_array_message,
673        num_array_message2,
674        max_wait_time=MAX_WAIT_TIME_SMS_RECEIVE_IN_COLLISION):
675
676    phonenumber_tx = ad_tx.telephony['subscription'][subid_tx]['phone_num']
677    phonenumber_tx2 = ad_tx2.telephony['subscription'][subid_tx2]['phone_num']
678    phonenumber_rx = ad_rx.telephony['subscription'][subid_rx]['phone_num']
679    phonenumber_rx2 = ad_rx.telephony['subscription'][subid_rx2]['phone_num']
680
681    if not toggle_airplane_mode(log, ad_rx, True):
682        ad_rx.log.error("Failed to enable Airplane Mode")
683        return False
684    ad_rx.stop_services()
685    ad_rx.log.info("Rebooting......")
686    ad_rx.adb.reboot()
687
688    message_dict = {phonenumber_tx: [], phonenumber_tx2: []}
689    for index in range(max(num_array_message, num_array_message2)):
690        array_message = [rand_ascii_str(array_message_length)]
691        array_message2 = [rand_ascii_str(array_message2_length)]
692        for text, text2 in zip(array_message, array_message2):
693            message_dict[phonenumber_tx].append(text)
694            message_dict[phonenumber_tx2].append(text2)
695            length = len(text)
696            length2 = len(text2)
697
698            ad_tx.log.info("Sending SMS from %s to %s, len: %s, content: %s.",
699                           phonenumber_tx, phonenumber_rx, length, text)
700            ad_tx2.log.info("Sending SMS from %s to %s, len: %s, content: %s.",
701                           phonenumber_tx2, phonenumber_rx2, length2, text2)
702
703            try:
704                for ad in (ad_tx, ad_tx2):
705                    ad.send_keycode("BACK")
706                    if not getattr(ad, "messaging_droid", None):
707                        ad.messaging_droid, ad.messaging_ed = ad.get_droid()
708                        ad.messaging_ed.start()
709                    else:
710                        try:
711                            if not ad.messaging_droid.is_live:
712                                ad.messaging_droid, ad.messaging_ed = \
713                                    ad.get_droid()
714                                ad.messaging_ed.start()
715                            else:
716                                ad.messaging_ed.clear_all_events()
717                            ad.messaging_droid.logI(
718                                "Start sms_send_receive_verify_for_subscription"
719                                " test")
720                        except Exception:
721                            ad.log.info("Create new sl4a session for messaging")
722                            ad.messaging_droid, ad.messaging_ed = ad.get_droid()
723                            ad.messaging_ed.start()
724
725                ad_tx.messaging_ed.clear_events(EventSmsSentSuccess)
726                ad_tx.messaging_ed.clear_events(EventSmsSentFailure)
727                ad_tx2.messaging_ed.clear_events(EventSmsSentSuccess)
728                ad_tx2.messaging_ed.clear_events(EventSmsSentFailure)
729
730                if index < num_array_message and index < num_array_message2:
731                    ad_tx.messaging_droid.logI(
732                        "Sending SMS of length %s" % length)
733                    ad_tx2.messaging_droid.logI(
734                        "Sending SMS of length %s" % length2)
735                    tasks = [
736                        (ad_tx.messaging_droid.smsSendTextMessage,
737                        (phonenumber_rx, text, True)),
738                        (ad_tx2.messaging_droid.smsSendTextMessage,
739                        (phonenumber_rx2, text2, True))]
740                    multithread_func(log, tasks)
741                else:
742                    if index < num_array_message:
743                        ad_tx.messaging_droid.logI(
744                            "Sending SMS of length %s" % length)
745                        ad_tx.messaging_droid.smsSendTextMessage(
746                            phonenumber_rx, text, True)
747                    if index < num_array_message2:
748                        ad_tx2.messaging_droid.logI(
749                            "Sending SMS of length %s" % length2)
750                        ad_tx2.messaging_droid.smsSendTextMessage(
751                            phonenumber_rx2, text2, True)
752
753                try:
754                    if index < num_array_message and index < num_array_message2:
755                        tasks = [
756                            (ad_tx.messaging_ed.pop_events, ("(%s|%s|%s|%s)" % (
757                                EventSmsSentSuccess,
758                                EventSmsSentFailure,
759                                EventSmsDeliverSuccess,
760                                EventSmsDeliverFailure),
761                                max_wait_time)),
762                            (ad_tx2.messaging_ed.pop_events, ("(%s|%s|%s|%s)" % (
763                                EventSmsSentSuccess,
764                                EventSmsSentFailure,
765                                EventSmsDeliverSuccess,
766                                EventSmsDeliverFailure),
767                                max_wait_time))
768                        ]
769                        results = run_multithread_func(log, tasks)
770                        res = True
771                        _ad = ad_tx
772                        for ad, events in [
773                            (ad_tx, results[0]), (ad_tx2, results[1])]:
774                            _ad = ad
775                            for event in events:
776                                ad.log.info("Got event %s", event["name"])
777                                if event["name"] == EventSmsSentFailure or \
778                                    event["name"] == EventSmsDeliverFailure:
779                                    if event.get("data") and \
780                                        event["data"].get("Reason"):
781                                        ad.log.error("%s with reason: %s",
782                                                        event["name"],
783                                                        event["data"]["Reason"])
784                                    res = False
785                                elif event["name"] == EventSmsSentSuccess or \
786                                    event["name"] == EventSmsDeliverSuccess:
787                                    break
788                        if not res:
789                            return False
790                    else:
791                        if index < num_array_message:
792                            result = ad_tx.messaging_ed.pop_events(
793                                "(%s|%s|%s|%s)" % (
794                                    EventSmsSentSuccess,
795                                    EventSmsSentFailure,
796                                    EventSmsDeliverSuccess,
797                                    EventSmsDeliverFailure),
798                                max_wait_time)
799                            res = True
800                            _ad = ad_tx
801                            for ad, events in [(ad_tx, result)]:
802                                _ad = ad
803                                for event in events:
804                                    ad.log.info("Got event %s", event["name"])
805                                    if event["name"] == EventSmsSentFailure or \
806                                        event["name"] == EventSmsDeliverFailure:
807                                        if event.get("data") and \
808                                            event["data"].get("Reason"):
809                                            ad.log.error(
810                                                "%s with reason: %s",
811                                                event["name"],
812                                                event["data"]["Reason"])
813                                        res = False
814                                    elif event["name"] == EventSmsSentSuccess \
815                                        or event["name"] == EventSmsDeliverSuccess:
816                                        break
817                            if not res:
818                                return False
819                        if index < num_array_message2:
820                            result = ad_tx2.messaging_ed.pop_events(
821                                "(%s|%s|%s|%s)" % (
822                                    EventSmsSentSuccess,
823                                    EventSmsSentFailure,
824                                    EventSmsDeliverSuccess,
825                                    EventSmsDeliverFailure),
826                                max_wait_time)
827                            res = True
828                            _ad = ad_tx2
829                            for ad, events in [(ad_tx2, result)]:
830                                _ad = ad
831                                for event in events:
832                                    ad.log.info("Got event %s", event["name"])
833                                    if event["name"] == EventSmsSentFailure or \
834                                        event["name"] == EventSmsDeliverFailure:
835                                        if event.get("data") and \
836                                            event["data"].get("Reason"):
837                                            ad.log.error(
838                                                "%s with reason: %s",
839                                                event["name"],
840                                                event["data"]["Reason"])
841                                        res = False
842                                    elif event["name"] == EventSmsSentSuccess \
843                                        or event["name"] == EventSmsDeliverSuccess:
844                                        break
845                            if not res:
846                                return False
847
848
849                except Empty:
850                    _ad.log.error("No %s or %s event for SMS of length %s.",
851                                    EventSmsSentSuccess, EventSmsSentFailure,
852                                    length)
853                    return False
854
855            except Exception as e:
856                log.error("Exception error %s", e)
857                raise
858
859    ad_rx.wait_for_boot_completion()
860    ad_rx.root_adb()
861    ad_rx.start_services(skip_setup_wizard=False)
862
863    output = ad_rx.adb.logcat("-t 1")
864    match = re.search(r"\d+-\d+\s\d+:\d+:\d+.\d+", output)
865    if match:
866        ad_rx.test_log_begin_time = match.group(0)
867
868    ad_rx.messaging_droid, ad_rx.messaging_ed = ad_rx.get_droid()
869    ad_rx.messaging_ed.start()
870    ad_rx.messaging_droid.smsStartTrackingIncomingSmsMessage()
871    time.sleep(1)  #sleep 100ms after starting event tracking
872
873    if not toggle_airplane_mode(log, ad_rx, False):
874        ad_rx.log.error("Failed to disable Airplane Mode")
875        return False
876
877    res = True
878    try:
879        if not wait_for_matching_multiple_sms(log,
880                ad_rx,
881                phonenumber_tx,
882                phonenumber_tx2,
883                messages=message_dict,
884                max_wait_time=max_wait_time):
885            res =  False
886    except Exception as e:
887        log.error("Exception error %s", e)
888        raise
889    finally:
890        ad_rx.messaging_droid.smsStopTrackingIncomingSmsMessage()
891
892    return res
893
894def is_sms_match(event, phonenumber_tx, text):
895    """Return True if 'text' equals to event['data']['Text']
896        and phone number match.
897
898    Args:
899        event: Event object to verify.
900        phonenumber_tx: phone number for sender.
901        text: text string to verify.
902
903    Returns:
904        Return True if 'text' equals to event['data']['Text']
905            and phone number match.
906    """
907    return (check_phone_number_match(event['data']['Sender'], phonenumber_tx)
908            and event['data']['Text'].strip() == text)
909
910def is_sms_partial_match(event, phonenumber_tx, text):
911    """Return True if 'text' starts with event['data']['Text']
912        and phone number match.
913
914    Args:
915        event: Event object to verify.
916        phonenumber_tx: phone number for sender.
917        text: text string to verify.
918
919    Returns:
920        Return True if 'text' starts with event['data']['Text']
921            and phone number match.
922    """
923    event_text = event['data']['Text'].strip()
924    if event_text.startswith("("):
925        event_text = event_text.split(")")[-1]
926    return (check_phone_number_match(event['data']['Sender'], phonenumber_tx)
927            and text.startswith(event_text))
928
929def is_sms_in_collision_match(
930    event, phonenumber_tx, phonenumber_tx2, text, text2):
931    event_text = event['data']['Text'].strip()
932    if event_text.startswith("("):
933        event_text = event_text.split(")")[-1]
934
935    for phonenumber, txt in [[phonenumber_tx, text], [phonenumber_tx2, text2]]:
936        if check_phone_number_match(
937            event['data']['Sender'], phonenumber) and txt.startswith(event_text):
938            return True
939    return False
940
941def is_sms_in_collision_partial_match(
942    event, phonenumber_tx, phonenumber_tx2, text, text2):
943    for phonenumber, txt in [[phonenumber_tx, text], [phonenumber_tx2, text2]]:
944        if check_phone_number_match(
945            event['data']['Sender'], phonenumber) and \
946                event['data']['Text'].strip() == txt:
947            return True
948    return False
949
950def is_sms_match_among_multiple_sms(
951    event, phonenumber_tx, phonenumber_tx2, texts=[], texts2=[]):
952    for txt in texts:
953        if check_phone_number_match(
954            event['data']['Sender'], phonenumber_tx) and \
955                event['data']['Text'].strip() == txt:
956                return True
957
958    for txt in texts2:
959        if check_phone_number_match(
960            event['data']['Sender'], phonenumber_tx2) and \
961                event['data']['Text'].strip() == txt:
962                return True
963
964    return False
965
966def is_sms_partial_match_among_multiple_sms(
967    event, phonenumber_tx, phonenumber_tx2, texts=[], texts2=[]):
968    event_text = event['data']['Text'].strip()
969    if event_text.startswith("("):
970        event_text = event_text.split(")")[-1]
971
972    for txt in texts:
973        if check_phone_number_match(
974            event['data']['Sender'], phonenumber_tx) and \
975                txt.startswith(event_text):
976                return True
977
978    for txt in texts2:
979        if check_phone_number_match(
980            event['data']['Sender'], phonenumber_tx2) and \
981                txt.startswith(event_text):
982                return True
983
984    return False
985
986def wait_for_matching_sms(log,
987                          ad_rx,
988                          phonenumber_tx,
989                          text,
990                          max_wait_time=MAX_WAIT_TIME_SMS_RECEIVE,
991                          allow_multi_part_long_sms=True):
992    """Wait for matching incoming SMS.
993
994    Args:
995        log: Log object.
996        ad_rx: Receiver's Android Device Object
997        phonenumber_tx: Sender's phone number.
998        text: SMS content string.
999        allow_multi_part_long_sms: is long SMS allowed to be received as
1000            multiple short SMS. This is optional, default value is True.
1001
1002    Returns:
1003        True if matching incoming SMS is received.
1004    """
1005    if not allow_multi_part_long_sms:
1006        try:
1007            ad_rx.messaging_ed.wait_for_event(EventSmsReceived, is_sms_match,
1008                                              max_wait_time, phonenumber_tx,
1009                                              text)
1010            ad_rx.log.info("Got event %s", EventSmsReceived)
1011            return True
1012        except Empty:
1013            ad_rx.log.error("No matched SMS received event.")
1014            return False
1015    else:
1016        try:
1017            received_sms = ''
1018            remaining_text = text
1019            while (remaining_text != ''):
1020                event = ad_rx.messaging_ed.wait_for_event(
1021                    EventSmsReceived, is_sms_partial_match, max_wait_time,
1022                    phonenumber_tx, remaining_text)
1023                event_text = event['data']['Text'].split(")")[-1].strip()
1024                event_text_length = len(event_text)
1025                ad_rx.log.info("Got event %s of text length %s from %s",
1026                               EventSmsReceived, event_text_length,
1027                               phonenumber_tx)
1028                remaining_text = remaining_text[event_text_length:]
1029                received_sms += event_text
1030            ad_rx.log.info("Received SMS of length %s", len(received_sms))
1031            return True
1032        except Empty:
1033            ad_rx.log.error(
1034                "Missing SMS received event of text length %s from %s",
1035                len(remaining_text), phonenumber_tx)
1036            if received_sms != '':
1037                ad_rx.log.error(
1038                    "Only received partial matched SMS of length %s",
1039                    len(received_sms))
1040            return False
1041
1042def wait_for_matching_mt_sms_in_collision(log,
1043                          ad_rx,
1044                          phonenumber_tx,
1045                          phonenumber_tx2,
1046                          text,
1047                          text2,
1048                          allow_multi_part_long_sms=True,
1049                          max_wait_time=MAX_WAIT_TIME_SMS_RECEIVE_IN_COLLISION):
1050
1051    if not allow_multi_part_long_sms:
1052        try:
1053            ad_rx.messaging_ed.wait_for_event(
1054                EventSmsReceived,
1055                is_sms_in_collision_match,
1056                max_wait_time,
1057                phonenumber_tx,
1058                phonenumber_tx2,
1059                text,
1060                text2)
1061            ad_rx.log.info("Got event %s", EventSmsReceived)
1062            return True
1063        except Empty:
1064            ad_rx.log.error("No matched SMS received event.")
1065            return False
1066    else:
1067        try:
1068            received_sms = ''
1069            received_sms2 = ''
1070            remaining_text = text
1071            remaining_text2 = text2
1072            while (remaining_text != '' or remaining_text2 != ''):
1073                event = ad_rx.messaging_ed.wait_for_event(
1074                    EventSmsReceived,
1075                    is_sms_in_collision_partial_match,
1076                    max_wait_time,
1077                    phonenumber_tx,
1078                    phonenumber_tx2,
1079                    remaining_text,
1080                    remaining_text2)
1081                event_text = event['data']['Text'].split(")")[-1].strip()
1082                event_text_length = len(event_text)
1083
1084                if event_text in remaining_text:
1085                    ad_rx.log.info("Got event %s of text length %s from %s",
1086                                   EventSmsReceived, event_text_length,
1087                                   phonenumber_tx)
1088                    remaining_text = remaining_text[event_text_length:]
1089                    received_sms += event_text
1090                elif event_text in remaining_text2:
1091                    ad_rx.log.info("Got event %s of text length %s from %s",
1092                                   EventSmsReceived, event_text_length,
1093                                   phonenumber_tx2)
1094                    remaining_text2 = remaining_text2[event_text_length:]
1095                    received_sms2 += event_text
1096
1097            ad_rx.log.info("Received SMS of length %s", len(received_sms))
1098            ad_rx.log.info("Received SMS of length %s", len(received_sms2))
1099            return True
1100        except Empty:
1101            ad_rx.log.error(
1102                "Missing SMS received event.")
1103            if received_sms != '':
1104                ad_rx.log.error(
1105                    "Only received partial matched SMS of length %s from %s",
1106                    len(received_sms), phonenumber_tx)
1107            if received_sms2 != '':
1108                ad_rx.log.error(
1109                    "Only received partial matched SMS of length %s from %s",
1110                    len(received_sms2), phonenumber_tx2)
1111            return False
1112
1113def wait_for_matching_mt_sms_in_collision_with_mo_sms(log,
1114                          ad_rx,
1115                          ad_rx2,
1116                          phonenumber_tx,
1117                          phonenumber_tx2,
1118                          text,
1119                          text2,
1120                          allow_multi_part_long_sms=True,
1121                          max_wait_time=MAX_WAIT_TIME_SMS_RECEIVE_IN_COLLISION):
1122
1123    if not allow_multi_part_long_sms:
1124        result = True
1125        try:
1126            ad_rx.messaging_ed.wait_for_call_offhook_event(
1127                EventSmsReceived,
1128                is_sms_match,
1129                max_wait_time,
1130                phonenumber_tx,
1131                text)
1132            ad_rx.log.info("Got event %s", EventSmsReceived)
1133        except Empty:
1134            ad_rx.log.error("No matched SMS received event.")
1135            result = False
1136
1137        try:
1138            ad_rx2.messaging_ed.wait_for_call_offhook_event(
1139                EventSmsReceived,
1140                is_sms_match,
1141                max_wait_time,
1142                phonenumber_tx2,
1143                text2)
1144            ad_rx2.log.info("Got event %s", EventSmsReceived)
1145        except Empty:
1146            ad_rx2.log.error("No matched SMS received event.")
1147            result = False
1148
1149        return result
1150    else:
1151        result = True
1152        try:
1153            received_sms = ''
1154            remaining_text = text
1155            while remaining_text != '':
1156                event = ad_rx.messaging_ed.wait_for_event(
1157                    EventSmsReceived, is_sms_partial_match, max_wait_time,
1158                    phonenumber_tx, remaining_text)
1159                event_text = event['data']['Text'].split(")")[-1].strip()
1160                event_text_length = len(event_text)
1161
1162                if event_text in remaining_text:
1163                    ad_rx.log.info("Got event %s of text length %s from %s",
1164                                   EventSmsReceived, event_text_length,
1165                                   phonenumber_tx)
1166                    remaining_text = remaining_text[event_text_length:]
1167                    received_sms += event_text
1168
1169            ad_rx.log.info("Received SMS of length %s", len(received_sms))
1170        except Empty:
1171            ad_rx.log.error(
1172                "Missing SMS received event.")
1173            if received_sms != '':
1174                ad_rx.log.error(
1175                    "Only received partial matched SMS of length %s from %s",
1176                    len(received_sms), phonenumber_tx)
1177            result = False
1178
1179        try:
1180            received_sms2 = ''
1181            remaining_text2 = text2
1182            while remaining_text2 != '':
1183                event2 = ad_rx2.messaging_ed.wait_for_event(
1184                    EventSmsReceived, is_sms_partial_match, max_wait_time,
1185                    phonenumber_tx2, remaining_text2)
1186                event_text2 = event2['data']['Text'].split(")")[-1].strip()
1187                event_text_length2 = len(event_text2)
1188
1189                if event_text2 in remaining_text2:
1190                    ad_rx2.log.info("Got event %s of text length %s from %s",
1191                                   EventSmsReceived, event_text_length2,
1192                                   phonenumber_tx2)
1193                    remaining_text2 = remaining_text2[event_text_length2:]
1194                    received_sms2 += event_text2
1195
1196            ad_rx2.log.info("Received SMS of length %s", len(received_sms2))
1197        except Empty:
1198            ad_rx2.log.error(
1199                "Missing SMS received event.")
1200            if received_sms2 != '':
1201                ad_rx2.log.error(
1202                    "Only received partial matched SMS of length %s from %s",
1203                    len(received_sms2), phonenumber_tx2)
1204            result = False
1205
1206        return result
1207
1208def wait_for_matching_multiple_sms(log,
1209                        ad_rx,
1210                        phonenumber_tx,
1211                        phonenumber_tx2,
1212                        messages={},
1213                        allow_multi_part_long_sms=True,
1214                        max_wait_time=MAX_WAIT_TIME_SMS_RECEIVE):
1215
1216    if not allow_multi_part_long_sms:
1217        try:
1218            ad_rx.messaging_ed.wait_for_event(
1219                EventSmsReceived,
1220                is_sms_match_among_multiple_sms,
1221                max_wait_time,
1222                phonenumber_tx,
1223                phonenumber_tx2,
1224                messages[phonenumber_tx],
1225                messages[phonenumber_tx2])
1226            ad_rx.log.info("Got event %s", EventSmsReceived)
1227            return True
1228        except Empty:
1229            ad_rx.log.error("No matched SMS received event.")
1230            return False
1231    else:
1232        all_msgs = []
1233        for tx, msgs in messages.items():
1234            for msg in msgs:
1235                all_msgs.append([tx, msg, msg, ''])
1236
1237        all_msgs_copy = all_msgs.copy()
1238
1239        try:
1240            while (all_msgs != []):
1241                event = ad_rx.messaging_ed.wait_for_event(
1242                    EventSmsReceived,
1243                    is_sms_partial_match_among_multiple_sms,
1244                    max_wait_time,
1245                    phonenumber_tx,
1246                    phonenumber_tx2,
1247                    messages[phonenumber_tx],
1248                    messages[phonenumber_tx2])
1249                event_text = event['data']['Text'].split(")")[-1].strip()
1250                event_text_length = len(event_text)
1251
1252                for msg in all_msgs_copy:
1253                    if event_text in msg[2]:
1254                        ad_rx.log.info("Got event %s of text length %s from %s",
1255                                       EventSmsReceived, event_text_length,
1256                                       msg[0])
1257                        msg[2] = msg[2][event_text_length:]
1258                        msg[3] += event_text
1259
1260                        if msg[2] == "":
1261                            all_msgs.remove(msg)
1262
1263            ad_rx.log.info("Received all SMS' sent when power-off.")
1264        except Empty:
1265            ad_rx.log.error(
1266                "Missing SMS received event.")
1267
1268            for msg in all_msgs_copy:
1269                if msg[3] != '':
1270                    ad_rx.log.error(
1271                        "Only received partial matched SMS of length %s from %s",
1272                        len(msg[3]), msg[0])
1273            return False
1274
1275        return True
1276
1277def wait_for_sending_sms(ad_tx, max_wait_time=MAX_WAIT_TIME_SMS_RECEIVE):
1278    try:
1279        events = ad_tx.messaging_ed.pop_events(
1280            "(%s|%s|%s|%s)" %
1281            (EventSmsSentSuccess, EventSmsSentFailure,
1282                EventSmsDeliverSuccess,
1283                EventSmsDeliverFailure), max_wait_time)
1284        for event in events:
1285            ad_tx.log.info("Got event %s", event["name"])
1286            if event["name"] == EventSmsSentFailure or \
1287                event["name"] == EventSmsDeliverFailure:
1288                if event.get("data") and event["data"].get("Reason"):
1289                    ad_tx.log.error("%s with reason: %s",
1290                                    event["name"],
1291                                    event["data"]["Reason"])
1292                return False
1293            elif event["name"] == EventSmsSentSuccess or \
1294                event["name"] == EventSmsDeliverSuccess:
1295                return True
1296    except Empty:
1297        ad_tx.log.error("No %s or %s event for SMS.",
1298                        EventSmsSentSuccess, EventSmsSentFailure)
1299        return False
1300
1301def voice_call_in_collision_with_mt_sms_msim(
1302        log,
1303        ad_primary,
1304        ad_sms,
1305        ad_voice,
1306        sms_subid_ad_primary,
1307        sms_subid_ad_sms,
1308        voice_subid_ad_primary,
1309        voice_subid_ad_voice,
1310        array_message,
1311        ad_hangup=None,
1312        verify_caller_func=None,
1313        verify_callee_func=None,
1314        call_direction="mo",
1315        wait_time_in_call=WAIT_TIME_IN_CALL,
1316        incall_ui_display=INCALL_UI_DISPLAY_FOREGROUND,
1317        dialing_number_length=None,
1318        video_state=None):
1319
1320    ad_tx = ad_sms
1321    ad_rx = ad_primary
1322    subid_tx = sms_subid_ad_sms
1323    subid_rx = sms_subid_ad_primary
1324
1325    if call_direction == "mo":
1326        ad_caller = ad_primary
1327        ad_callee = ad_voice
1328        subid_caller = voice_subid_ad_primary
1329        subid_callee = voice_subid_ad_voice
1330    elif call_direction == "mt":
1331        ad_callee = ad_primary
1332        ad_caller = ad_voice
1333        subid_callee = voice_subid_ad_primary
1334        subid_caller = voice_subid_ad_voice
1335
1336
1337    phonenumber_tx = ad_tx.telephony['subscription'][subid_tx]['phone_num']
1338    phonenumber_rx = ad_rx.telephony['subscription'][subid_rx]['phone_num']
1339
1340    tel_result_wrapper = TelResultWrapper(CallResult('SUCCESS'))
1341
1342    for ad in (ad_tx, ad_rx):
1343        ad.send_keycode("BACK")
1344        if not getattr(ad, "messaging_droid", None):
1345            ad.messaging_droid, ad.messaging_ed = ad.get_droid()
1346            ad.messaging_ed.start()
1347        else:
1348            try:
1349                if not ad.messaging_droid.is_live:
1350                    ad.messaging_droid, ad.messaging_ed = ad.get_droid()
1351                    ad.messaging_ed.start()
1352                else:
1353                    ad.messaging_ed.clear_all_events()
1354            except Exception:
1355                ad.log.info("Create new sl4a session for messaging")
1356                ad.messaging_droid, ad.messaging_ed = ad.get_droid()
1357                ad.messaging_ed.start()
1358
1359    if not verify_caller_func:
1360        verify_caller_func = is_phone_in_call
1361    if not verify_callee_func:
1362        verify_callee_func = is_phone_in_call
1363
1364    caller_number = ad_caller.telephony['subscription'][subid_caller][
1365        'phone_num']
1366    callee_number = ad_callee.telephony['subscription'][subid_callee][
1367        'phone_num']
1368    if dialing_number_length:
1369        skip_test = False
1370        trunc_position = 0 - int(dialing_number_length)
1371        try:
1372            caller_area_code = caller_number[:trunc_position]
1373            callee_area_code = callee_number[:trunc_position]
1374            callee_dial_number = callee_number[trunc_position:]
1375        except:
1376            skip_test = True
1377        if caller_area_code != callee_area_code:
1378            skip_test = True
1379        if skip_test:
1380            msg = "Cannot make call from %s to %s by %s digits" % (
1381                caller_number, callee_number, dialing_number_length)
1382            ad_caller.log.info(msg)
1383            raise signals.TestSkip(msg)
1384        else:
1385            callee_number = callee_dial_number
1386
1387    msg = "Call from %s to %s" % (caller_number, callee_number)
1388    if video_state:
1389        msg = "Video %s" % msg
1390        video = True
1391    else:
1392        video = False
1393    if ad_hangup:
1394        msg = "%s for duration of %s seconds" % (msg, wait_time_in_call)
1395    ad_caller.log.info(msg)
1396
1397    for ad in (ad_caller, ad_callee):
1398        call_ids = ad.droid.telecomCallGetCallIds()
1399        setattr(ad, "call_ids", call_ids)
1400        if call_ids:
1401            ad.log.info("Pre-exist CallId %s before making call", call_ids)
1402
1403    ad_caller.ed.clear_events(EventCallStateChanged)
1404    call_begin_time = get_device_epoch_time(ad)
1405    ad_caller.droid.telephonyStartTrackingCallStateForSubscription(subid_caller)
1406
1407    for text in array_message:
1408        length = len(text)
1409        ad_tx.log.info("Sending SMS from %s to %s, len: %s, content: %s.",
1410                       phonenumber_tx, phonenumber_rx, length, text)
1411        try:
1412            ad_rx.messaging_ed.clear_events(EventSmsReceived)
1413            ad_tx.messaging_ed.clear_events(EventSmsSentSuccess)
1414            ad_tx.messaging_ed.clear_events(EventSmsSentFailure)
1415            ad_rx.messaging_droid.smsStartTrackingIncomingSmsMessage()
1416            time.sleep(1)  #sleep 100ms after starting event tracking
1417            ad_tx.messaging_droid.logI("Sending SMS of length %s" % length)
1418            ad_rx.messaging_droid.logI("Expecting SMS of length %s" % length)
1419            ad_caller.log.info("Make a phone call to %s", callee_number)
1420
1421            tasks = [
1422                (ad_tx.messaging_droid.smsSendTextMessage,
1423                (phonenumber_rx, text, True)),
1424                (ad_caller.droid.telecomCallNumber,
1425                (callee_number, video))]
1426
1427            run_multithread_func(log, tasks)
1428
1429            try:
1430                # Verify OFFHOOK state
1431                if not wait_for_call_offhook_for_subscription(
1432                        log,
1433                        ad_caller,
1434                        subid_caller,
1435                        event_tracking_started=True):
1436                    ad_caller.log.info(
1437                        "sub_id %s not in call offhook state", subid_caller)
1438                    last_call_drop_reason(ad_caller, begin_time=call_begin_time)
1439
1440                    ad_caller.log.error("Initiate call failed.")
1441                    tel_result_wrapper.result_value = CallResult(
1442                                                        'INITIATE_FAILED')
1443                    return tel_result_wrapper
1444                else:
1445                    ad_caller.log.info("Caller initate call successfully")
1446            finally:
1447                ad_caller.droid.telephonyStopTrackingCallStateChangeForSubscription(
1448                    subid_caller)
1449                if incall_ui_display == INCALL_UI_DISPLAY_FOREGROUND:
1450                    ad_caller.droid.telecomShowInCallScreen()
1451                elif incall_ui_display == INCALL_UI_DISPLAY_BACKGROUND:
1452                    ad_caller.droid.showHomeScreen()
1453
1454            if not wait_and_answer_call_for_subscription(
1455                    log,
1456                    ad_callee,
1457                    subid_callee,
1458                    incoming_number=caller_number,
1459                    caller=ad_caller,
1460                    incall_ui_display=incall_ui_display,
1461                    video_state=video_state):
1462                ad_callee.log.error("Answer call fail.")
1463                tel_result_wrapper.result_value = CallResult(
1464                    'NO_RING_EVENT_OR_ANSWER_FAILED')
1465                return tel_result_wrapper
1466            else:
1467                ad_callee.log.info("Callee answered the call successfully")
1468
1469            for ad, call_func in zip([ad_caller, ad_callee],
1470                                     [verify_caller_func, verify_callee_func]):
1471                call_ids = ad.droid.telecomCallGetCallIds()
1472                new_call_ids = set(call_ids) - set(ad.call_ids)
1473                if not new_call_ids:
1474                    ad.log.error(
1475                        "No new call ids are found after call establishment")
1476                    ad.log.error("telecomCallGetCallIds returns %s",
1477                                 ad.droid.telecomCallGetCallIds())
1478                    tel_result_wrapper.result_value = CallResult(
1479                                                        'NO_CALL_ID_FOUND')
1480                for new_call_id in new_call_ids:
1481                    if not wait_for_in_call_active(ad, call_id=new_call_id):
1482                        tel_result_wrapper.result_value = CallResult(
1483                            'CALL_STATE_NOT_ACTIVE_DURING_ESTABLISHMENT')
1484                    else:
1485                        ad.log.info(
1486                            "callProperties = %s",
1487                            ad.droid.telecomCallGetProperties(new_call_id))
1488
1489                if not ad.droid.telecomCallGetAudioState():
1490                    ad.log.error("Audio is not in call state")
1491                    tel_result_wrapper.result_value = CallResult(
1492                        'AUDIO_STATE_NOT_INCALL_DURING_ESTABLISHMENT')
1493
1494                if call_func(log, ad):
1495                    ad.log.info("Call is in %s state", call_func.__name__)
1496                else:
1497                    ad.log.error("Call is not in %s state, voice in RAT %s",
1498                                 call_func.__name__,
1499                                 ad.droid.telephonyGetCurrentVoiceNetworkType())
1500                    tel_result_wrapper.result_value = CallResult(
1501                        'CALL_DROP_OR_WRONG_STATE_DURING_ESTABLISHMENT')
1502            if not tel_result_wrapper:
1503                return tel_result_wrapper
1504
1505            if not wait_for_sending_sms(
1506                ad_tx,
1507                max_wait_time=MAX_WAIT_TIME_SMS_SENT_SUCCESS_IN_COLLISION):
1508                return False
1509
1510            tasks = [
1511                (wait_for_matching_sms,
1512                (log, ad_rx, phonenumber_tx, text,
1513                MAX_WAIT_TIME_SMS_RECEIVE_IN_COLLISION, True)),
1514                (wait_for_call_end,
1515                (log, ad_caller, ad_callee, ad_hangup, verify_caller_func,
1516                    verify_callee_func, call_begin_time, 5, tel_result_wrapper,
1517                    WAIT_TIME_IN_CALL))]
1518
1519            results = run_multithread_func(log, tasks)
1520
1521            if not results[0]:
1522                ad_rx.log.error("No matching received SMS of length %s.",
1523                                length)
1524                return False
1525
1526            tel_result_wrapper = results[1]
1527
1528        except Exception as e:
1529            log.error("Exception error %s", e)
1530            raise
1531        finally:
1532            ad_rx.messaging_droid.smsStopTrackingIncomingSmsMessage()
1533
1534    return tel_result_wrapper
1535
1536
1537def is_mms_match(event, phonenumber_tx, text):
1538    """Return True if 'text' equals to event['data']['Text']
1539        and phone number match.
1540
1541    Args:
1542        event: Event object to verify.
1543        phonenumber_tx: phone number for sender.
1544        text: text string to verify.
1545
1546    Returns:
1547        Return True if 'text' equals to event['data']['Text']
1548            and phone number match.
1549    """
1550    #TODO:  add mms matching after mms message parser is added in sl4a. b/34276948
1551    return True
1552
1553
1554def wait_for_matching_mms(log,
1555                          ad_rx,
1556                          phonenumber_tx,
1557                          text,
1558                          max_wait_time=MAX_WAIT_TIME_MMS_RECEIVE):
1559    """Wait for matching incoming SMS.
1560
1561    Args:
1562        log: Log object.
1563        ad_rx: Receiver's Android Device Object
1564        phonenumber_tx: Sender's phone number.
1565        text: SMS content string.
1566        allow_multi_part_long_sms: is long SMS allowed to be received as
1567            multiple short SMS. This is optional, default value is True.
1568
1569    Returns:
1570        True if matching incoming SMS is received.
1571    """
1572    try:
1573        #TODO: add mms matching after mms message parser is added in sl4a. b/34276948
1574        ad_rx.messaging_ed.wait_for_event(EventMmsDownloaded, is_mms_match,
1575                                          max_wait_time, phonenumber_tx, text)
1576        ad_rx.log.info("Got event %s", EventMmsDownloaded)
1577        return True
1578    except Empty:
1579        ad_rx.log.warning("No matched MMS downloaded event.")
1580        return False
1581
1582
1583def mms_send_receive_verify(log,
1584                            ad_tx,
1585                            ad_rx,
1586                            array_message,
1587                            max_wait_time=MAX_WAIT_TIME_MMS_RECEIVE,
1588                            expected_result=True,
1589                            slot_id_rx=None):
1590    """Send MMS, receive MMS, and verify content and sender's number.
1591
1592        Send (several) MMS from droid_tx to droid_rx.
1593        Verify MMS is sent, delivered and received.
1594        Verify received content and sender's number are correct.
1595
1596    Args:
1597        log: Log object.
1598        ad_tx: Sender's Android Device Object
1599        ad_rx: Receiver's Android Device Object
1600        array_message: the array of message to send/receive
1601    """
1602    subid_tx = get_outgoing_message_sub_id(ad_tx)
1603    if slot_id_rx is None:
1604        subid_rx = get_incoming_message_sub_id(ad_rx)
1605    else:
1606        subid_rx = get_subid_from_slot_index(log, ad_rx, slot_id_rx)
1607
1608    result = mms_send_receive_verify_for_subscription(
1609        log, ad_tx, ad_rx, subid_tx, subid_rx, array_message, max_wait_time)
1610    if result != expected_result:
1611        log_messaging_screen_shot(ad_tx, test_name="mms_tx")
1612        log_messaging_screen_shot(ad_rx, test_name="mms_rx")
1613    return result == expected_result
1614
1615
1616def sms_mms_send_logcat_check(ad, type, begin_time):
1617    type = type.upper()
1618    log_results = ad.search_logcat(
1619        "%s Message sent successfully" % type, begin_time=begin_time)
1620    if log_results:
1621        ad.log.info("Found %s sent successful log message: %s", type,
1622                    log_results[-1]["log_message"])
1623        return True
1624    else:
1625        log_results = ad.search_logcat(
1626            "ProcessSentMessageAction: Done sending %s message" % type,
1627            begin_time=begin_time)
1628        if log_results:
1629            for log_result in log_results:
1630                if "status is SUCCEEDED" in log_result["log_message"]:
1631                    ad.log.info(
1632                        "Found BugleDataModel %s send succeed log message: %s",
1633                        type, log_result["log_message"])
1634                    return True
1635    return False
1636
1637
1638def sms_mms_receive_logcat_check(ad, type, begin_time):
1639    type = type.upper()
1640    smshandle_logs = ad.search_logcat(
1641        "InboundSmsHandler: No broadcast sent on processing EVENT_BROADCAST_SMS",
1642        begin_time=begin_time)
1643    if smshandle_logs:
1644        ad.log.warning("Found %s", smshandle_logs[-1]["log_message"])
1645    log_results = ad.search_logcat(
1646        "New %s Received" % type, begin_time=begin_time) or \
1647        ad.search_logcat("New %s Downloaded" % type, begin_time=begin_time)
1648    if log_results:
1649        ad.log.info("Found SL4A %s received log message: %s", type,
1650                    log_results[-1]["log_message"])
1651        return True
1652    else:
1653        log_results = ad.search_logcat(
1654            "Received %s message" % type, begin_time=begin_time)
1655        if log_results:
1656            ad.log.info("Found %s received log message: %s", type,
1657                        log_results[-1]["log_message"])
1658        log_results = ad.search_logcat(
1659            "ProcessDownloadedMmsAction", begin_time=begin_time)
1660        for log_result in log_results:
1661            ad.log.info("Found %s", log_result["log_message"])
1662            if "status is SUCCEEDED" in log_result["log_message"]:
1663                ad.log.info("Download succeed with ProcessDownloadedMmsAction")
1664                return True
1665    return False
1666
1667
1668#TODO: add mms matching after mms message parser is added in sl4a. b/34276948
1669def mms_send_receive_verify_for_subscription(
1670        log,
1671        ad_tx,
1672        ad_rx,
1673        subid_tx,
1674        subid_rx,
1675        array_payload,
1676        max_wait_time=MAX_WAIT_TIME_MMS_RECEIVE):
1677    """Send MMS, receive MMS, and verify content and sender's number.
1678
1679        Send (several) MMS from droid_tx to droid_rx.
1680        Verify MMS is sent, delivered and received.
1681        Verify received content and sender's number are correct.
1682
1683    Args:
1684        log: Log object.
1685        ad_tx: Sender's Android Device Object..
1686        ad_rx: Receiver's Android Device Object.
1687        subid_tx: Sender's subscription ID to be used for SMS
1688        subid_rx: Receiver's subscription ID to be used for SMS
1689        array_message: the array of message to send/receive
1690    """
1691
1692    phonenumber_tx = ad_tx.telephony['subscription'][subid_tx]['phone_num']
1693    phonenumber_rx = ad_rx.telephony['subscription'][subid_rx]['phone_num']
1694    toggle_enforce = False
1695
1696    for ad in (ad_tx, ad_rx):
1697        if "Permissive" not in ad.adb.shell("su root getenforce"):
1698            ad.adb.shell("su root setenforce 0")
1699            toggle_enforce = True
1700        if not getattr(ad, "messaging_droid", None):
1701            ad.messaging_droid, ad.messaging_ed = ad.get_droid()
1702            ad.messaging_ed.start()
1703        else:
1704            try:
1705                if not ad.messaging_droid.is_live:
1706                    ad.messaging_droid, ad.messaging_ed = ad.get_droid()
1707                    ad.messaging_ed.start()
1708                else:
1709                    ad.messaging_ed.clear_all_events()
1710                ad.messaging_droid.logI(
1711                    "Start mms_send_receive_verify_for_subscription test")
1712            except Exception:
1713                ad.log.info("Create new sl4a session for messaging")
1714                ad.messaging_droid, ad.messaging_ed = ad.get_droid()
1715                ad.messaging_ed.start()
1716
1717    for subject, message, filename in array_payload:
1718        ad_tx.messaging_ed.clear_events(EventMmsSentSuccess)
1719        ad_tx.messaging_ed.clear_events(EventMmsSentFailure)
1720        ad_rx.messaging_ed.clear_events(EventMmsDownloaded)
1721        ad_rx.messaging_droid.smsStartTrackingIncomingMmsMessage()
1722        ad_tx.log.info(
1723            "Sending MMS from %s to %s, subject: %s, message: %s, file: %s.",
1724            phonenumber_tx, phonenumber_rx, subject, message, filename)
1725        try:
1726            ad_tx.messaging_droid.smsSendMultimediaMessage(
1727                phonenumber_rx, subject, message, phonenumber_tx, filename)
1728            try:
1729                events = ad_tx.messaging_ed.pop_events(
1730                    "(%s|%s)" % (EventMmsSentSuccess,
1731                                 EventMmsSentFailure), max_wait_time)
1732                for event in events:
1733                    ad_tx.log.info("Got event %s", event["name"])
1734                    if event["name"] == EventMmsSentFailure:
1735                        if event.get("data") and event["data"].get("Reason"):
1736                            ad_tx.log.error("%s with reason: %s",
1737                                            event["name"],
1738                                            event["data"]["Reason"])
1739                        return False
1740                    elif event["name"] == EventMmsSentSuccess:
1741                        break
1742            except Empty:
1743                ad_tx.log.warning("No %s or %s event.", EventMmsSentSuccess,
1744                                  EventMmsSentFailure)
1745                return False
1746
1747            if not wait_for_matching_mms(log, ad_rx, phonenumber_tx,
1748                                         message, max_wait_time):
1749                return False
1750        except Exception as e:
1751            log.error("Exception error %s", e)
1752            raise
1753        finally:
1754            ad_rx.messaging_droid.smsStopTrackingIncomingMmsMessage()
1755            for ad in (ad_tx, ad_rx):
1756                if toggle_enforce:
1757                    ad.send_keycode("BACK")
1758                    ad.adb.shell("su root setenforce 1")
1759    return True
1760
1761
1762def mms_receive_verify_after_call_hangup(
1763        log, ad_tx, ad_rx, array_message,
1764        max_wait_time=MAX_WAIT_TIME_MMS_RECEIVE):
1765    """Verify the suspanded MMS during call will send out after call release.
1766
1767        Hangup call from droid_tx to droid_rx.
1768        Verify MMS is sent, delivered and received.
1769        Verify received content and sender's number are correct.
1770
1771    Args:
1772        log: Log object.
1773        ad_tx: Sender's Android Device Object
1774        ad_rx: Receiver's Android Device Object
1775        array_message: the array of message to send/receive
1776    """
1777    return mms_receive_verify_after_call_hangup_for_subscription(
1778        log, ad_tx, ad_rx, get_outgoing_message_sub_id(ad_tx),
1779        get_incoming_message_sub_id(ad_rx), array_message, max_wait_time)
1780
1781
1782#TODO: add mms matching after mms message parser is added in sl4a. b/34276948
1783def mms_receive_verify_after_call_hangup_for_subscription(
1784        log,
1785        ad_tx,
1786        ad_rx,
1787        subid_tx,
1788        subid_rx,
1789        array_payload,
1790        max_wait_time=MAX_WAIT_TIME_MMS_RECEIVE):
1791    """Verify the suspanded MMS during call will send out after call release.
1792
1793        Hangup call from droid_tx to droid_rx.
1794        Verify MMS is sent, delivered and received.
1795        Verify received content and sender's number are correct.
1796
1797    Args:
1798        log: Log object.
1799        ad_tx: Sender's Android Device Object..
1800        ad_rx: Receiver's Android Device Object.
1801        subid_tx: Sender's subscription ID to be used for SMS
1802        subid_rx: Receiver's subscription ID to be used for SMS
1803        array_message: the array of message to send/receive
1804    """
1805
1806    phonenumber_tx = ad_tx.telephony['subscription'][subid_tx]['phone_num']
1807    phonenumber_rx = ad_rx.telephony['subscription'][subid_rx]['phone_num']
1808    for ad in (ad_tx, ad_rx):
1809        if not getattr(ad, "messaging_droid", None):
1810            ad.messaging_droid, ad.messaging_ed = ad.get_droid()
1811            ad.messaging_ed.start()
1812    for subject, message, filename in array_payload:
1813        ad_rx.log.info(
1814            "Waiting MMS from %s to %s, subject: %s, message: %s, file: %s.",
1815            phonenumber_tx, phonenumber_rx, subject, message, filename)
1816        ad_rx.messaging_droid.smsStartTrackingIncomingMmsMessage()
1817        time.sleep(5)
1818        try:
1819            hangup_call(log, ad_tx)
1820            hangup_call(log, ad_rx)
1821            try:
1822                ad_tx.messaging_ed.pop_event(EventMmsSentSuccess,
1823                                             max_wait_time)
1824                ad_tx.log.info("Got event %s", EventMmsSentSuccess)
1825            except Empty:
1826                log.warning("No sent_success event.")
1827            if not wait_for_matching_mms(log, ad_rx, phonenumber_tx, message):
1828                return False
1829        finally:
1830            ad_rx.messaging_droid.smsStopTrackingIncomingMmsMessage()
1831    return True
1832
1833
1834def log_messaging_screen_shot(ad, test_name=""):
1835    ad.ensure_screen_on()
1836    ad.send_keycode("HOME")
1837    ad.adb.shell("am start -n com.google.android.apps.messaging/.ui."
1838                 "ConversationListActivity")
1839    time.sleep(3)
1840    ad.screenshot(test_name)
1841    ad.adb.shell("am start -n com.google.android.apps.messaging/com.google."
1842                 "android.apps.messaging.ui.conversation."
1843                 "LaunchConversationShimActivity -e conversation_id 1")
1844    time.sleep(3)
1845    ad.screenshot(test_name)
1846    ad.send_keycode("HOME")