blob: 3b4ed380d4815784588484bbdd61aa21621d5982 [file] [log] [blame]
jasonkmluff0d5b92019-03-21 11:24:45 +08001#!/usr/bin/env python3.5
2#
3# Copyright 2019 - Google
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17import time
18import re
19import os
jasonkmlu903ece82019-05-16 14:56:19 +080020import math
21import collections
22import shutil
jasonkmlu4fcdcad2019-07-10 14:35:12 +080023import fnmatch
24import posixpath
jasonkmluff0d5b92019-03-21 11:24:45 +080025
26from acts import utils
27from acts import signals
28from acts.controllers.android_device import list_adb_devices
29from acts.controllers.android_device import list_fastboot_devices
30from acts.controllers.android_device import DEFAULT_QXDM_LOG_PATH
31from acts.controllers.android_device import SL4A_APK_NAME
32from acts.test_utils.wifi import wifi_test_utils as wutils
33from acts.test_utils.tel import tel_test_utils as tutils
34from acts.utils import get_current_epoch_time
35
36WifiEnums = wutils.WifiEnums
37PULL_TIMEOUT = 300
jasonkmlu66fda532019-07-16 11:12:45 +080038GNSSSTATUS_LOG_PATH = (
39 "/storage/emulated/0/Android/data/com.android.gpstool/files/")
jasonkmlu214f0d62019-04-08 19:53:59 +080040QXDM_MASKS = ["GPS.cfg", "GPS-general.cfg", "default.cfg"]
jasonkmlu4fcdcad2019-07-10 14:35:12 +080041TTFF_REPORT = collections.namedtuple(
42 "TTFF_REPORT", "ttff_loop ttff_sec ttff_pe ttff_cn")
43TRACK_REPORT = collections.namedtuple(
44 "TRACK_REPORT", "track_l5flag track_pe track_top4cn track_cn")
jasonkmlu38bd4d12019-10-04 16:38:48 +080045LOCAL_PROP_FILE_CONTENTS = """\
46log.tag.LocationManagerService=VERBOSE
47log.tag.GnssLocationProvider=VERBOSE
48log.tag.GnssMeasurementsProvider=VERBOSE
49log.tag.GpsNetInitiatedHandler=VERBOSE
50log.tag.GnssNetworkConnectivityHandler=VERBOSE
51log.tag.ConnectivityService=VERBOSE
52log.tag.ConnectivityManager=VERBOSE
53log.tag.GnssVisibilityControl=VERBOSE"""
jasonkmluff0d5b92019-03-21 11:24:45 +080054
55
56class GnssTestUtilsError(Exception):
57 pass
58
59def remount_device(ad):
60 """Remount device file system to read and write.
61
62 Args:
63 ad: An AndroidDevice object.
64 """
jasonkmlu81b8b032019-06-21 15:18:27 +080065 for retries in range(5):
jasonkmluff0d5b92019-03-21 11:24:45 +080066 ad.root_adb()
67 remount_result = ad.adb.remount()
68 ad.log.info("Attempt %d - %s" % (retries + 1, remount_result))
jasonkmlu81b8b032019-06-21 15:18:27 +080069 if "remount succeeded" in remount_result:
jasonkmluff0d5b92019-03-21 11:24:45 +080070 break
71 if ad.adb.getprop("ro.boot.veritymode") == "enforcing":
jasonkmluff0d5b92019-03-21 11:24:45 +080072 disable_verity_result = ad.adb.disable_verity()
jasonkmlu214f0d62019-04-08 19:53:59 +080073 reboot(ad)
74
75def reboot(ad):
76 """Reboot device and check if mobile data is available.
77
78 Args:
79 ad: An AndroidDevice object.
80 """
81 ad.log.info("Reboot device to make changes take effect.")
82 ad.reboot()
83 ad.unlock_screen(password=None)
84 if not int(ad.adb.shell("settings get global mobile_data")) == 1:
85 set_mobile_data(ad, True)
jasonkmlu49c32812019-04-12 18:11:10 +080086 utils.sync_device_time(ad)
jasonkmlu180a08c2019-04-23 17:24:55 +080087 if ad.model == "sailfish" or ad.model == "marlin":
88 remount_device(ad)
89 ad.adb.shell("echo at@test=8 >> /dev/at_mdm0")
jasonkmluff0d5b92019-03-21 11:24:45 +080090
91def enable_gnss_verbose_logging(ad):
jasonkmlu81b8b032019-06-21 15:18:27 +080092 """Enable GNSS VERBOSE Logging and persistent logcat.
jasonkmluff0d5b92019-03-21 11:24:45 +080093
94 Args:
95 ad: An AndroidDevice object.
96 """
97 remount_device(ad)
jasonkmlu97ac56e2019-05-29 15:04:51 +080098 ad.log.info("Enable GNSS VERBOSE Logging and persistent logcat.")
jasonkmluff0d5b92019-03-21 11:24:45 +080099 ad.adb.shell("echo DEBUG_LEVEL = 5 >> /vendor/etc/gps.conf")
jasonkmlu38bd4d12019-10-04 16:38:48 +0800100 ad.adb.shell("echo %r >> /data/local.prop" % LOCAL_PROP_FILE_CONTENTS)
jasonkmluff0d5b92019-03-21 11:24:45 +0800101 ad.adb.shell("chmod 644 /data/local.prop")
jasonkmlu180a08c2019-04-23 17:24:55 +0800102 ad.adb.shell("setprop persist.logd.size 16777216")
jasonkmluff0d5b92019-03-21 11:24:45 +0800103 ad.adb.shell("setprop persist.vendor.radio.adb_log_on 1")
jasonkmlu81b8b032019-06-21 15:18:27 +0800104 ad.adb.shell("setprop persist.logd.logpersistd logcatd")
jasonkmluff0d5b92019-03-21 11:24:45 +0800105 ad.adb.shell("setprop log.tag.copresGcore VERBOSE")
106 ad.adb.shell("sync")
107
jasonkmlu81b8b032019-06-21 15:18:27 +0800108def enable_compact_and_particle_fusion_log(ad):
109 """Enable CompactLog and FLP particle fusion log.
110
111 Args:
112 ad: An AndroidDevice object.
113 """
114 ad.root_adb()
115 ad.log.info("Enable CompactLog and FLP particle fusion log.")
116 ad.adb.shell("am broadcast -a com.google.gservices.intent.action."
117 "GSERVICES_OVERRIDE -e location:compact_log_enabled true")
118 ad.adb.shell("am broadcast -a com.google.gservices.intent.action."
jasonkmlueb9183d2019-08-06 10:52:58 +0800119 "GSERVICES_OVERRIDE -e location:proks_config 28")
120 ad.adb.shell("am broadcast -a com.google.gservices.intent.action."
jasonkmlud8b2acf2019-08-23 16:48:27 +0800121 "GSERVICES_OVERRIDE -e location:flp_use_particle_fusion true")
jasonkmlu81b8b032019-06-21 15:18:27 +0800122 ad.adb.shell("am broadcast -a com.google.gservices.intent.action."
jasonkmlud8b2acf2019-08-23 16:48:27 +0800123 "GSERVICES_OVERRIDE -e "
124 "location:flp_particle_fusion_extended_bug_report true")
jasonkmlueb9183d2019-08-06 10:52:58 +0800125 ad.adb.shell("am broadcast -a com.google.gservices.intent.action."
jasonkmlud8b2acf2019-08-23 16:48:27 +0800126 "GSERVICES_OVERRIDE -e location:flp_event_log_size 86400")
127 ad.adb.shell("am broadcast -a com.google.gservices.intent.action."
128 "GSERVICES_OVERRIDE -e "
129 "location:flp_particle_fusion_bug_report_window_sec 86400")
130 ad.adb.shell("am broadcast -a com.google.gservices.intent.action."
131 "GSERVICES_OVERRIDE -e location:"
132 "flp_particle_fusion_bug_report_max_buffer_size 86400")
jasonkmlu81b8b032019-06-21 15:18:27 +0800133 ad.adb.shell("am force-stop com.google.android.gms")
134 ad.adb.shell("am broadcast -a com.google.android.gms.INITIALIZE")
jasonkmlud8b2acf2019-08-23 16:48:27 +0800135 ad.adb.shell("dumpsys activity service com.google.android.location."
136 "internal.GoogleLocationManagerService")
jasonkmlu81b8b032019-06-21 15:18:27 +0800137
jasonkmluff0d5b92019-03-21 11:24:45 +0800138def disable_xtra_throttle(ad):
139 """Disable XTRA throttle will have no limit to download XTRA data.
140
141 Args:
142 ad: An AndroidDevice object.
143 """
144 remount_device(ad)
145 ad.log.info("Disable XTRA Throttle.")
146 ad.adb.shell("echo XTRA_TEST_ENABLED=1 >> /vendor/etc/gps.conf")
147 ad.adb.shell("echo XTRA_THROTTLE_ENABLED=0 >> /vendor/etc/gps.conf")
148
149def enable_supl_mode(ad):
150 """Enable SUPL back on for next test item.
151
152 Args:
153 ad: An AndroidDevice object.
154 """
155 remount_device(ad)
156 ad.log.info("Enable SUPL mode.")
157 ad.adb.shell("echo SUPL_MODE=1 >> /etc/gps_debug.conf")
158
159def disable_supl_mode(ad):
160 """Kill SUPL to test XTRA only test item.
161
162 Args:
163 ad: An AndroidDevice object.
164 """
165 remount_device(ad)
166 ad.log.info("Disable SUPL mode.")
167 ad.adb.shell("echo SUPL_MODE=0 >> /etc/gps_debug.conf")
jasonkmlu214f0d62019-04-08 19:53:59 +0800168 reboot(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800169
170def kill_xtra_daemon(ad):
171 """Kill XTRA daemon to test SUPL only test item.
172
173 Args:
174 ad: An AndroidDevice object.
175 """
176 ad.root_adb()
177 ad.log.info("Disable XTRA-daemon until next reboot.")
178 ad.adb.shell("killall xtra-daemon")
179
180def disable_private_dns_mode(ad):
181 """Due to b/118365122, it's better to disable private DNS mode while
182 testing. 8.8.8.8 private dns sever is unstable now, sometimes server
183 will not response dns query suddenly.
184
185 Args:
186 ad: An AndroidDevice object.
187 """
188 tutils.get_operator_name(ad.log, ad, subId=None)
189 if ad.adb.shell("settings get global private_dns_mode") != "off":
190 ad.log.info("Disable Private DNS mode.")
191 ad.adb.shell("settings put global private_dns_mode off")
192
193def _init_device(ad):
194 """Init GNSS test devices.
195
196 Args:
197 ad: An AndroidDevice object.
198 """
199 enable_gnss_verbose_logging(ad)
jasonkmlu81b8b032019-06-21 15:18:27 +0800200 enable_compact_and_particle_fusion_log(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800201 disable_xtra_throttle(ad)
202 enable_supl_mode(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800203 ad.adb.shell("settings put system screen_off_timeout 1800000")
204 wutils.wifi_toggle_state(ad, False)
205 ad.log.info("Setting Bluetooth state to False")
206 ad.droid.bluetoothToggleState(False)
jasonkmluff0d5b92019-03-21 11:24:45 +0800207 set_gnss_qxdm_mask(ad, QXDM_MASKS)
jasonkmluff0d5b92019-03-21 11:24:45 +0800208 check_location_service(ad)
209 set_wifi_and_bt_scanning(ad, True)
jasonkmlu214f0d62019-04-08 19:53:59 +0800210 disable_private_dns_mode(ad)
jasonkmlu81b8b032019-06-21 15:18:27 +0800211 init_gtw_gpstool(ad)
jasonkmlu180a08c2019-04-23 17:24:55 +0800212 reboot(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800213
214def connect_to_wifi_network(ad, network):
215 """Connection logic for open and psk wifi networks.
216
217 Args:
218 ad: An AndroidDevice object.
219 network: Dictionary with network info.
220 """
221 SSID = network[WifiEnums.SSID_KEY]
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800222 wutils.start_wifi_connection_scan_and_return_status(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800223 wutils.wifi_connect(ad, network, num_of_tries=5)
224
225def set_wifi_and_bt_scanning(ad, state=True):
226 """Set Wi-Fi and Bluetooth scanning on/off in Settings -> Location
227
228 Args:
229 ad: An AndroidDevice object.
jasonkmlu81b8b032019-06-21 15:18:27 +0800230 state: True to turn on "Wi-Fi and Bluetooth scanning".
231 False to turn off "Wi-Fi and Bluetooth scanning".
jasonkmluff0d5b92019-03-21 11:24:45 +0800232 """
233 ad.root_adb()
234 if state:
235 ad.adb.shell("settings put global wifi_scan_always_enabled 1")
236 ad.adb.shell("settings put global ble_scan_always_enabled 1")
237 ad.log.info("Wi-Fi and Bluetooth scanning are enabled")
238 else:
239 ad.adb.shell("settings put global wifi_scan_always_enabled 0")
240 ad.adb.shell("settings put global ble_scan_always_enabled 0")
241 ad.log.info("Wi-Fi and Bluetooth scanning are disabled")
242
243def check_location_service(ad):
244 """Set location service on.
245 Verify if location service is available.
246
247 Args:
248 ad: An AndroidDevice object.
jasonkmluff0d5b92019-03-21 11:24:45 +0800249 """
jasonkmlu81b8b032019-06-21 15:18:27 +0800250 remount_device(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800251 utils.set_location_service(ad, True)
jasonkmlu81b8b032019-06-21 15:18:27 +0800252 location_mode = int(ad.adb.shell("settings get secure location_mode"))
253 ad.log.info("Current Location Mode >> %d" % location_mode)
254 if location_mode != 3:
255 raise signals.TestFailure("Failed to turn Location on")
jasonkmluff0d5b92019-03-21 11:24:45 +0800256
257def clear_logd_gnss_qxdm_log(ad):
258 """Clear /data/misc/logd,
259 /storage/emulated/0/Android/data/com.android.gpstool/files and
260 /data/vendor/radio/diag_logs/logs from previous test item then reboot.
261
262 Args:
263 ad: An AndroidDevice object.
264 """
265 remount_device(ad)
266 ad.log.info("Clear Logd, GNSS and QXDM Log from previous test item.")
267 ad.adb.shell("rm -rf /data/misc/logd", ignore_status=True)
268 ad.adb.shell("rm -rf %s" % GNSSSTATUS_LOG_PATH, ignore_status=True)
269 output_path = os.path.join(DEFAULT_QXDM_LOG_PATH, "logs")
270 ad.adb.shell("rm -rf %s" % output_path, ignore_status=True)
jasonkmlu214f0d62019-04-08 19:53:59 +0800271 reboot(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800272
jasonkmlu81b8b032019-06-21 15:18:27 +0800273def get_gnss_qxdm_log(ad, qdb_path):
jasonkmluff0d5b92019-03-21 11:24:45 +0800274 """Get /storage/emulated/0/Android/data/com.android.gpstool/files and
jasonkmlu81b8b032019-06-21 15:18:27 +0800275 /data/vendor/radio/diag_logs/logs for test item.
jasonkmluff0d5b92019-03-21 11:24:45 +0800276
277 Args:
278 ad: An AndroidDevice object.
jasonkmlu81b8b032019-06-21 15:18:27 +0800279 qdb_path: The path of qdsp6m.qdb on different projects.
jasonkmluff0d5b92019-03-21 11:24:45 +0800280 """
jasonkmlu903ece82019-05-16 14:56:19 +0800281 log_path = ad.device_log_path
jasonkmluff0d5b92019-03-21 11:24:45 +0800282 utils.create_dir(log_path)
jasonkmlu903ece82019-05-16 14:56:19 +0800283 gnss_log_name = "gnssstatus_log_%s_%s" % (ad.model, ad.serial)
284 gnss_log_path = os.path.join(log_path, gnss_log_name)
jasonkmluff0d5b92019-03-21 11:24:45 +0800285 utils.create_dir(gnss_log_path)
286 ad.log.info("Pull GnssStatus Log to %s" % gnss_log_path)
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800287 ad.adb.pull("%s %s" % (GNSSSTATUS_LOG_PATH+".", gnss_log_path),
jasonkmluff0d5b92019-03-21 11:24:45 +0800288 timeout=PULL_TIMEOUT, ignore_status=True)
jasonkmlu903ece82019-05-16 14:56:19 +0800289 shutil.make_archive(gnss_log_path, "zip", gnss_log_path)
290 shutil.rmtree(gnss_log_path)
291 output_path = os.path.join(DEFAULT_QXDM_LOG_PATH, "logs/.")
jasonkmluff0d5b92019-03-21 11:24:45 +0800292 file_count = ad.adb.shell("find %s -type f -iname *.qmdl | wc -l" % output_path)
293 if not int(file_count) == 0:
jasonkmlu903ece82019-05-16 14:56:19 +0800294 qxdm_log_name = "QXDM_%s_%s" % (ad.model, ad.serial)
295 qxdm_log_path = os.path.join(log_path, qxdm_log_name)
jasonkmluff0d5b92019-03-21 11:24:45 +0800296 utils.create_dir(qxdm_log_path)
297 ad.log.info("Pull QXDM Log %s to %s" % (output_path, qxdm_log_path))
298 ad.adb.pull("%s %s" % (output_path, qxdm_log_path),
299 timeout=PULL_TIMEOUT, ignore_status=True)
jasonkmlu81b8b032019-06-21 15:18:27 +0800300 for path in qdb_path:
301 output = ad.adb.pull("%s %s" % (path, qxdm_log_path),
302 timeout=PULL_TIMEOUT, ignore_status=True)
303 if "No such file or directory" in output:
304 continue
305 break
jasonkmlu903ece82019-05-16 14:56:19 +0800306 shutil.make_archive(qxdm_log_path, "zip", qxdm_log_path)
307 shutil.rmtree(qxdm_log_path)
jasonkmluff0d5b92019-03-21 11:24:45 +0800308 else:
309 ad.log.error("QXDM file count is %d. There is no QXDM log on device."
310 % int(file_count))
311
jasonkmluff0d5b92019-03-21 11:24:45 +0800312def set_mobile_data(ad, state):
313 """Set mobile data on or off and check mobile data state.
314
315 Args:
316 ad: An AndroidDevice object.
317 state: True to enable mobile data. False to disable mobile data.
318 """
319 ad.root_adb()
320 if state:
321 ad.log.info("Enable mobile data.")
322 ad.adb.shell("svc data enable")
323 else:
324 ad.log.info("Disable mobile data.")
325 ad.adb.shell("svc data disable")
326 time.sleep(5)
327 out = int(ad.adb.shell("settings get global mobile_data"))
328 if state and out == 1:
329 ad.log.info("Mobile data is enabled and set to %d" % out)
330 elif not state and out == 0:
331 ad.log.info("Mobile data is disabled and set to %d" % out)
332 else:
333 ad.log.error("Mobile data is at unknown state and set to %d" % out)
334
jasonkmlu81b8b032019-06-21 15:18:27 +0800335def gnss_trigger_modem_ssr(ad, dwelltime=60):
336 """Trigger modem SSR crash and verify if modem crash and recover successfully.
jasonkmluff0d5b92019-03-21 11:24:45 +0800337
338 Args:
339 ad: An AndroidDevice object.
340
341 Returns:
jasonkmlu81b8b032019-06-21 15:18:27 +0800342 True if success.
343 False if failed.
jasonkmluff0d5b92019-03-21 11:24:45 +0800344 """
jasonkmlu81b8b032019-06-21 15:18:27 +0800345 begin_time = get_current_epoch_time()
346 ad.root_adb()
347 cmds = ("echo restart > /sys/kernel/debug/msm_subsys/modem",
348 r"echo 'at+cfun=1,1\r' > /dev/at_mdm0")
349 for cmd in cmds:
350 ad.log.info("Triggering modem SSR crash by %s" % cmd)
351 output = ad.adb.shell(cmd, ignore_status=True)
352 if "No such file or directory" in output:
353 continue
354 break
355 time.sleep(dwelltime)
jasonkmluff0d5b92019-03-21 11:24:45 +0800356 ad.send_keycode("HOME")
jasonkmlu81b8b032019-06-21 15:18:27 +0800357 logcat_results = ad.search_logcat("SSRObserver", begin_time)
358 if logcat_results:
359 for ssr in logcat_results:
360 if "mSubsystem='modem', mCrashReason" in ssr["log_message"]:
361 ad.log.debug(ssr["log_message"])
362 ad.log.info("Triggering modem SSR crash successfully.")
363 return True
364 raise signals.TestFailure("Failed to trigger modem SSR crash")
365 raise signals.TestFailure("No SSRObserver found in logcat")
jasonkmluff0d5b92019-03-21 11:24:45 +0800366
367def check_xtra_download(ad, begin_time):
368 """Verify XTRA download success log message in logcat.
369
370 Args:
371 ad: An AndroidDevice object.
372 begin_time: test begin time
373
374 Returns:
375 True: xtra_download if XTRA downloaded and injected successfully
376 otherwise return False.
377 """
378 ad.send_keycode("HOME")
379 logcat_results = ad.search_logcat("XTRA download success. "
380 "inject data into modem", begin_time)
381 if logcat_results:
jasonkmlu81b8b032019-06-21 15:18:27 +0800382 ad.log.debug("%s" % logcat_results[-1]["log_message"])
jasonkmluff0d5b92019-03-21 11:24:45 +0800383 ad.log.info("XTRA downloaded and injected successfully.")
384 return True
385 ad.log.error("XTRA downloaded FAIL.")
386 return False
387
388def pull_gtw_gpstool(ad):
389 """Pull GTW_GPSTool apk from device.
390
391 Args:
392 ad: An AndroidDevice object.
393 """
394 out = ad.adb.shell("pm path com.android.gpstool")
395 result = re.search(r"package:(.*)", out)
396 if not result:
397 tutils.abort_all_tests(ad.log, "Couldn't find GTW GPSTool apk")
398 else:
399 GTW_GPSTool_apk = result.group(1)
400 ad.log.info("Get GTW GPSTool apk from %s" % GTW_GPSTool_apk)
401 apkdir = "/tmp/GNSS/"
402 utils.create_dir(apkdir)
403 ad.pull_files([GTW_GPSTool_apk], apkdir)
404
405def reinstall_gtw_gpstool(ad):
406 """Reinstall GTW_GPSTool apk.
407
408 Args:
409 ad: An AndroidDevice object.
410 """
411 ad.log.info("Re-install GTW GPSTool")
jasonkmlu903ece82019-05-16 14:56:19 +0800412 ad.adb.install("-r -g -t /tmp/GNSS/base.apk")
jasonkmluff0d5b92019-03-21 11:24:45 +0800413
jasonkmlu180a08c2019-04-23 17:24:55 +0800414def init_gtw_gpstool(ad):
415 """Init GTW_GPSTool apk.
416
417 Args:
418 ad: An AndroidDevice object.
419 """
420 remount_device(ad)
421 pull_gtw_gpstool(ad)
422 ad.adb.shell("settings put global verifier_verify_adb_installs 0")
jasonkmlu180a08c2019-04-23 17:24:55 +0800423 reinstall_gtw_gpstool(ad)
424
jasonkmluff0d5b92019-03-21 11:24:45 +0800425def fastboot_factory_reset(ad):
426 """Factory reset the device in fastboot mode.
427 Pull sl4a apk from device. Terminate all sl4a sessions,
428 Reboot the device to bootloader,
429 factory reset the device by fastboot.
430 Reboot the device. wait for device to complete booting
431 Re-install and start an sl4a session.
432
433 Args:
434 ad: An AndroidDevice object.
435
436 Returns:
437 True if factory reset process complete.
438 """
439 status = True
440 skip_setup_wizard = True
441 out = ad.adb.shell("pm path %s" % SL4A_APK_NAME)
442 result = re.search(r"package:(.*)", out)
443 if not result:
444 tutils.abort_all_tests(ad.log, "Couldn't find sl4a apk")
445 else:
446 sl4a_apk = result.group(1)
447 ad.log.info("Get sl4a apk from %s" % sl4a_apk)
448 ad.pull_files([sl4a_apk], "/tmp/")
449 pull_gtw_gpstool(ad)
450 tutils.stop_qxdm_logger(ad)
451 ad.stop_services()
452 attempts = 3
453 for i in range(1, attempts + 1):
454 try:
455 if ad.serial in list_adb_devices():
456 ad.log.info("Reboot to bootloader")
457 ad.adb.reboot("bootloader", ignore_status=True)
458 time.sleep(10)
459 if ad.serial in list_fastboot_devices():
460 ad.log.info("Factory reset in fastboot")
461 ad.fastboot._w(timeout=300, ignore_status=True)
462 time.sleep(30)
463 ad.log.info("Reboot in fastboot")
464 ad.fastboot.reboot()
465 ad.wait_for_boot_completion()
466 ad.root_adb()
467 if ad.skip_sl4a:
468 break
469 if ad.is_sl4a_installed():
470 break
471 ad.log.info("Re-install sl4a")
472 ad.adb.shell("settings put global verifier_verify_adb_installs 0")
jasonkmlu903ece82019-05-16 14:56:19 +0800473 ad.adb.install("-r -g -t /tmp/base.apk")
jasonkmluff0d5b92019-03-21 11:24:45 +0800474 reinstall_gtw_gpstool(ad)
475 time.sleep(10)
476 break
477 except Exception as e:
478 ad.log.error(e)
479 if i == attempts:
480 tutils.abort_all_tests(ad.log, str(e))
481 time.sleep(5)
482 try:
483 ad.start_adb_logcat()
484 except Exception as e:
485 ad.log.error(e)
486 if skip_setup_wizard:
487 ad.exit_setup_wizard()
488 if ad.skip_sl4a:
489 return status
490 tutils.bring_up_sl4a(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800491 return status
492
493def clear_aiding_data_by_gtw_gpstool(ad):
494 """Launch GTW GPSTool and Clear all GNSS aiding data.
495 Wait 5 seconds for GTW GPStool to clear all GNSS aiding
496 data properly.
497
498 Args:
499 ad: An AndroidDevice object.
500 """
501 ad.log.info("Launch GTW GPSTool and Clear all GNSS aiding data")
502 ad.adb.shell("am start -S -n com.android.gpstool/.GPSTool --es mode clear")
503 time.sleep(10)
504
jasonkmlu81b8b032019-06-21 15:18:27 +0800505def start_gnss_by_gtw_gpstool(ad, state, type="gnss"):
jasonkmluff0d5b92019-03-21 11:24:45 +0800506 """Start or stop GNSS on GTW_GPSTool.
507
508 Args:
509 ad: An AndroidDevice object.
510 state: True to start GNSS. False to Stop GNSS.
jasonkmlu81b8b032019-06-21 15:18:27 +0800511 type: Different API for location fix. Use gnss/flp/nmea
jasonkmluff0d5b92019-03-21 11:24:45 +0800512 """
513 if state:
jasonkmlu81b8b032019-06-21 15:18:27 +0800514 ad.adb.shell("am start -S -n com.android.gpstool/.GPSTool "
515 "--es mode gps --es type %s" % type)
jasonkmluff0d5b92019-03-21 11:24:45 +0800516 if not state:
jasonkmlu81b8b032019-06-21 15:18:27 +0800517 ad.log.info("Stop %s on GTW_GPSTool." % type)
jasonkmluff0d5b92019-03-21 11:24:45 +0800518 ad.adb.shell("am broadcast -a com.android.gpstool.stop_gps_action")
519 time.sleep(3)
520
jasonkmlu81b8b032019-06-21 15:18:27 +0800521def process_gnss_by_gtw_gpstool(ad, criteria, type="gnss"):
jasonkmluff0d5b92019-03-21 11:24:45 +0800522 """Launch GTW GPSTool and Clear all GNSS aiding data
523 Start GNSS tracking on GTW_GPSTool.
524
525 Args:
526 ad: An AndroidDevice object.
527 criteria: Criteria for current test item.
jasonkmlu81b8b032019-06-21 15:18:27 +0800528 type: Different API for location fix. Use gnss/flp/nmea
jasonkmluff0d5b92019-03-21 11:24:45 +0800529
530 Returns:
531 True: First fix TTFF are within criteria.
532 False: First fix TTFF exceed criteria.
533 """
534 retries = 3
535 for i in range(retries):
536 begin_time = get_current_epoch_time()
537 clear_aiding_data_by_gtw_gpstool(ad)
jasonkmlu81b8b032019-06-21 15:18:27 +0800538 ad.log.info("Start %s on GTW_GPSTool - attempt %d" % (type.upper(), i+1))
539 start_gnss_by_gtw_gpstool(ad, True, type)
jasonkmluff0d5b92019-03-21 11:24:45 +0800540 for _ in range(10 + criteria):
541 logcat_results = ad.search_logcat("First fixed", begin_time)
542 if logcat_results:
jasonkmlu81b8b032019-06-21 15:18:27 +0800543 ad.log.debug(logcat_results[-1]["log_message"])
jasonkmluff0d5b92019-03-21 11:24:45 +0800544 first_fixed = int(logcat_results[-1]["log_message"].split()[-1])
jasonkmlu81b8b032019-06-21 15:18:27 +0800545 ad.log.info("%s First fixed = %.3f seconds" %
546 (type.upper(), first_fixed/1000))
547 if (first_fixed/1000) <= criteria:
jasonkmluff0d5b92019-03-21 11:24:45 +0800548 return True
jasonkmlu81b8b032019-06-21 15:18:27 +0800549 start_gnss_by_gtw_gpstool(ad, False, type)
550 raise signals.TestFailure("Fail to get %s location fixed within "
551 "%d seconds criteria." %
552 (type.upper(), criteria))
jasonkmluff0d5b92019-03-21 11:24:45 +0800553 time.sleep(1)
jasonkmlua4a569f2019-04-10 14:25:31 +0800554 if not ad.is_adb_logcat_on:
555 ad.start_adb_logcat()
jasonkmlu97ac56e2019-05-29 15:04:51 +0800556 check_currrent_focus_app(ad)
jasonkmlu81b8b032019-06-21 15:18:27 +0800557 start_gnss_by_gtw_gpstool(ad, False, type)
558 raise signals.TestFailure("Fail to get %s location fixed within %d attempts."
559 % (type.upper(), retries))
jasonkmluff0d5b92019-03-21 11:24:45 +0800560
561def start_ttff_by_gtw_gpstool(ad, ttff_mode, iteration):
562 """Identify which TTFF mode for different test items.
563
564 Args:
565 ad: An AndroidDevice object.
566 ttff_mode: TTFF Test mode for current test item.
567 iteration: Iteration of TTFF cycles.
568 """
jasonkmlu97ac56e2019-05-29 15:04:51 +0800569 begin_time = get_current_epoch_time()
jasonkmlu81b8b032019-06-21 15:18:27 +0800570 if ttff_mode == "hs" or ttff_mode == "ws":
571 ad.log.info("Wait 5 minutes to start TTFF %s..." % ttff_mode.upper())
jasonkmluff0d5b92019-03-21 11:24:45 +0800572 time.sleep(300)
573 if ttff_mode == "cs":
574 ad.log.info("Start TTFF Cold Start...")
575 time.sleep(3)
jasonkmlu97ac56e2019-05-29 15:04:51 +0800576 for i in range(1, 4):
577 ad.adb.shell("am broadcast -a com.android.gpstool.ttff_action "
578 "--es ttff %s --es cycle %d" % (ttff_mode, iteration))
jasonkmlu81b8b032019-06-21 15:18:27 +0800579 time.sleep(1)
jasonkmlu97ac56e2019-05-29 15:04:51 +0800580 if ad.search_logcat("act=com.android.gpstool.start_test_action",
581 begin_time):
582 ad.log.info("Send TTFF start_test_action successfully.")
583 break
584 if i == 3:
585 check_currrent_focus_app(ad)
586 raise signals.TestFailure("Fail to send TTFF start_test_action.")
jasonkmluff0d5b92019-03-21 11:24:45 +0800587
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800588def gnss_tracking_via_gtw_gpstool(ad, criteria, type="gnss", testtime=60):
jasonkmlu66fda532019-07-16 11:12:45 +0800589 """Start GNSS/FLP tracking tests for input testtime on GTW_GPSTool.
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800590
591 Args:
592 ad: An AndroidDevice object.
593 criteria: Criteria for current TTFF.
594 type: Different API for location fix. Use gnss/flp/nmea
595 testtime: Tracking test time for minutes. Default set to 60 minutes.
596 """
597 process_gnss_by_gtw_gpstool(ad, criteria, type)
598 ad.log.info("Start %s tracking test for %d minutes" % (type.upper(),
599 testtime))
600 begin_time = get_current_epoch_time()
601 while get_current_epoch_time() - begin_time < testtime * 60 * 1000 :
602 if not ad.is_adb_logcat_on:
603 ad.start_adb_logcat()
604 crash_result = ad.search_logcat("Force finishing activity "
605 "com.android.gpstool/.GPSTool",
606 begin_time)
607 if crash_result:
608 raise signals.TestFailure("GPSTool crashed. Abort test.")
609 ad.log.info("Successfully tested for %d minutes" % testtime)
610 start_gnss_by_gtw_gpstool(ad, False, type)
611
612def parse_gtw_gpstool_log(ad, true_position, type="gnss"):
613 """Process GNSS/FLP API logs from GTW GPSTool and output track_data to
614 test_run_info for ACTS plugin to parse and display on MobileHarness as
615 Property.
616
617 Args:
618 ad: An AndroidDevice object.
619 true_position: Coordinate as [latitude, longitude] to calculate
620 position error.
621 type: Different API for location fix. Use gnss/flp/nmea
622 """
623 test_logfile = {}
624 track_data = {}
625 history_top4_cn = 0
626 history_cn = 0
627 file_count = int(ad.adb.shell("find %s -type f -iname *.txt | wc -l"
628 % GNSSSTATUS_LOG_PATH))
629 if file_count != 1:
630 ad.log.error("%d API logs exist." % file_count)
631 dir = ad.adb.shell("ls %s" % GNSSSTATUS_LOG_PATH).split()
632 for path_key in dir:
633 if fnmatch.fnmatch(path_key, "*.txt"):
634 logpath = posixpath.join(GNSSSTATUS_LOG_PATH, path_key)
635 out = ad.adb.shell("wc -c %s" % logpath)
636 file_size = int(out.split(" ")[0])
637 if file_size < 2000:
638 ad.log.info("Skip log %s due to log size %d bytes" %
639 (path_key, file_size))
640 continue
641 test_logfile = logpath
642 if not test_logfile:
643 raise signals.TestFailure("Failed to get test log file in device.")
644 lines = ad.adb.shell("cat %s" % test_logfile).split("\n")
645 for line in lines:
646 if "History Avg Top4" in line:
647 history_top4_cn = float(line.split(":")[-1].strip())
648 if "History Avg" in line:
649 history_cn = float(line.split(":")[-1].strip())
650 if "L5 used in fix" in line:
651 l5flag = line.split(":")[-1].strip()
652 if "Latitude" in line:
653 track_lat = float(line.split(":")[-1].strip())
654 if "Longitude" in line:
655 track_long = float(line.split(":")[-1].strip())
656 if "Time" in line:
657 track_utc = line.split("Time:")[-1].strip()
658 if track_utc in track_data.keys():
659 continue
660 track_pe = calculate_position_error(ad, track_lat, track_long,
661 true_position)
662 track_data[track_utc] = TRACK_REPORT(track_l5flag=l5flag,
663 track_pe=track_pe,
664 track_top4cn=history_top4_cn,
665 track_cn=history_cn)
666 ad.log.debug(track_data)
667 prop_basename = "TestResult %s_tracking_" % type.upper()
668 time_list = sorted(track_data.keys())
669 l5flag_list = [track_data[key].track_l5flag for key in time_list]
670 pe_list = [float(track_data[key].track_pe) for key in time_list]
671 top4cn_list = [float(track_data[key].track_top4cn) for key in time_list]
672 cn_list = [float(track_data[key].track_cn) for key in time_list]
673 ad.log.info(prop_basename+"StartTime %s" % time_list[0].replace(" ", "-"))
674 ad.log.info(prop_basename+"EndTime %s" % time_list[-1].replace(" ", "-"))
675 ad.log.info(prop_basename+"TotalFixPoints %d" % len(time_list))
676 ad.log.info(prop_basename+"L5FixRate "+'{percent:.2%}'.format(
677 percent=l5flag_list.count("true")/len(l5flag_list)))
678 ad.log.info(prop_basename+"AvgDis %.1f" % (sum(pe_list)/len(pe_list)))
679 ad.log.info(prop_basename+"MaxDis %.1f" % max(pe_list))
680 ad.log.info(prop_basename+"AvgTop4Signal %.1f" % top4cn_list[-1])
681 ad.log.info(prop_basename+"AvgSignal %.1f" % cn_list[-1])
682
jasonkmlu81b8b032019-06-21 15:18:27 +0800683def process_ttff_by_gtw_gpstool(ad, begin_time, true_position, type="gnss"):
684 """Process TTFF and record results in ttff_data.
jasonkmluff0d5b92019-03-21 11:24:45 +0800685
686 Args:
687 ad: An AndroidDevice object.
jasonkmlu903ece82019-05-16 14:56:19 +0800688 begin_time: test begin time.
jasonkmlu733738f2019-09-02 18:59:42 +0800689 true_position: Coordinate as [latitude, longitude] to calculate
690 position error.
jasonkmlu81b8b032019-06-21 15:18:27 +0800691 type: Different API for location fix. Use gnss/flp/nmea
jasonkmluff0d5b92019-03-21 11:24:45 +0800692
693 Returns:
jasonkmlu81b8b032019-06-21 15:18:27 +0800694 ttff_data: A dict of all TTFF data.
jasonkmluff0d5b92019-03-21 11:24:45 +0800695 """
jasonkmlu903ece82019-05-16 14:56:19 +0800696 ttff_data = {}
jasonkmlu733738f2019-09-02 18:59:42 +0800697 ttff_loop_time = get_current_epoch_time()
jasonkmlu97ac56e2019-05-29 15:04:51 +0800698 while True:
jasonkmlu733738f2019-09-02 18:59:42 +0800699 if get_current_epoch_time() - ttff_loop_time >= 120000:
700 raise signals.TestFailure("Fail to search specific GPSService "
701 "message in logcat. Abort test.")
jasonkmlu97ac56e2019-05-29 15:04:51 +0800702 if not ad.is_adb_logcat_on:
703 ad.start_adb_logcat()
704 stop_gps_results = ad.search_logcat("stop gps test", begin_time)
705 if stop_gps_results:
706 ad.send_keycode("HOME")
707 break
708 crash_result = ad.search_logcat("Force finishing activity "
709 "com.android.gpstool/.GPSTool",
710 begin_time)
711 if crash_result:
jasonkmlu81b8b032019-06-21 15:18:27 +0800712 raise signals.TestFailure("GPSTool crashed. Abort test.")
jasonkmlu97ac56e2019-05-29 15:04:51 +0800713 logcat_results = ad.search_logcat("write TTFF log", begin_time)
714 if logcat_results:
715 ttff_log = logcat_results[-1]["log_message"].split()
716 ttff_loop = int(ttff_log[8].split(":")[-1])
jasonkmlu97ac56e2019-05-29 15:04:51 +0800717 if ttff_loop in ttff_data.keys():
718 continue
jasonkmlu733738f2019-09-02 18:59:42 +0800719 ttff_loop_time = get_current_epoch_time()
jasonkmlu81b8b032019-06-21 15:18:27 +0800720 ttff_sec = float(ttff_log[11])
721 if ttff_sec != 0.0:
722 ttff_cn = float(ttff_log[18].strip("]"))
723 if type == "gnss":
jasonkmlu733738f2019-09-02 18:59:42 +0800724 gnss_results = ad.search_logcat("GPSService: Check item",
725 begin_time)
jasonkmlu81b8b032019-06-21 15:18:27 +0800726 if gnss_results:
727 ad.log.debug(gnss_results[-1]["log_message"])
jasonkmlu733738f2019-09-02 18:59:42 +0800728 gnss_location_log = \
729 gnss_results[-1]["log_message"].split()
730 ttff_lat = float(
731 gnss_location_log[8].split("=")[-1].strip(","))
732 ttff_lon = float(
733 gnss_location_log[9].split("=")[-1].strip(","))
jasonkmlu81b8b032019-06-21 15:18:27 +0800734 elif type == "flp":
jasonkmlu733738f2019-09-02 18:59:42 +0800735 flp_results = ad.search_logcat("GPSService: FLP Location",
736 begin_time)
jasonkmlu81b8b032019-06-21 15:18:27 +0800737 if flp_results:
738 ad.log.debug(flp_results[-1]["log_message"])
jasonkmlu733738f2019-09-02 18:59:42 +0800739 flp_location_log = \
740 flp_results[-1]["log_message"].split()
jasonkmlu81b8b032019-06-21 15:18:27 +0800741 ttff_lat = float(flp_location_log[8].split(",")[0])
742 ttff_lon = float(flp_location_log[8].split(",")[1])
743 else:
744 ttff_cn = float(ttff_log[19].strip("]"))
jasonkmlu97ac56e2019-05-29 15:04:51 +0800745 ttff_lat = 0.0
746 ttff_lon = 0.0
jasonkmlu97ac56e2019-05-29 15:04:51 +0800747 ttff_pe = calculate_position_error(ad, ttff_lat, ttff_lon,
748 true_position)
749 ttff_data[ttff_loop] = TTFF_REPORT(ttff_loop=ttff_loop,
750 ttff_sec=ttff_sec,
751 ttff_pe=ttff_pe,
752 ttff_cn=ttff_cn)
753 ad.log.info("Loop %d = %.1f seconds, "
754 "Position Error = %.1f meters, "
755 "Average Signal = %.1f dbHz"
756 % (ttff_loop, ttff_sec, ttff_pe, ttff_cn))
757 return ttff_data
jasonkmluff0d5b92019-03-21 11:24:45 +0800758
jasonkmlu903ece82019-05-16 14:56:19 +0800759def check_ttff_data(ad, ttff_data, ttff_mode, criteria):
jasonkmlu81b8b032019-06-21 15:18:27 +0800760 """Verify all TTFF results from ttff_data.
jasonkmluff0d5b92019-03-21 11:24:45 +0800761
762 Args:
763 ad: An AndroidDevice object.
jasonkmlu903ece82019-05-16 14:56:19 +0800764 ttff_data: TTFF data of secs, position error and signal strength.
jasonkmluff0d5b92019-03-21 11:24:45 +0800765 ttff_mode: TTFF Test mode for current test item.
766 criteria: Criteria for current test item.
767
768 Returns:
769 True: All TTFF results are within criteria.
770 False: One or more TTFF results exceed criteria or Timeout.
771 """
772 ad.log.info("%d iterations of TTFF %s tests finished."
jasonkmlu903ece82019-05-16 14:56:19 +0800773 % (len(ttff_data.keys()), ttff_mode))
jasonkmluff0d5b92019-03-21 11:24:45 +0800774 ad.log.info("%s PASS criteria is %d seconds" % (ttff_mode, criteria))
jasonkmlu81b8b032019-06-21 15:18:27 +0800775 ad.log.debug("%s TTFF data: %s" % (ttff_mode, ttff_data))
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800776 ttff_property_key_and_value(ad, ttff_data, ttff_mode)
jasonkmlu903ece82019-05-16 14:56:19 +0800777 if len(ttff_data.keys()) == 0:
jasonkmluff0d5b92019-03-21 11:24:45 +0800778 ad.log.error("GTW_GPSTool didn't process TTFF properly.")
779 return False
jasonkmlu903ece82019-05-16 14:56:19 +0800780 elif any(float(ttff_data[key].ttff_sec) == 0.0 for key in ttff_data.keys()):
jasonkmluff0d5b92019-03-21 11:24:45 +0800781 ad.log.error("One or more TTFF %s Timeout" % ttff_mode)
782 return False
jasonkmlu903ece82019-05-16 14:56:19 +0800783 elif any(float(ttff_data[key].ttff_sec) >= criteria for key in ttff_data.keys()):
jasonkmluff0d5b92019-03-21 11:24:45 +0800784 ad.log.error("One or more TTFF %s are over test criteria %d seconds"
785 % (ttff_mode, criteria))
786 return False
787 ad.log.info("All TTFF %s are within test criteria %d seconds."
788 % (ttff_mode, criteria))
789 return True
790
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800791def ttff_property_key_and_value(ad, ttff_data, ttff_mode):
jasonkmlu81b8b032019-06-21 15:18:27 +0800792 """Output ttff_data to test_run_info for ACTS plugin to parse and display
793 on MobileHarness as Property.
794
795 Args:
796 ad: An AndroidDevice object.
797 ttff_data: TTFF data of secs, position error and signal strength.
798 ttff_mode: TTFF Test mode for current test item.
799 """
800 prop_basename = "TestResult "+ttff_mode.replace(" ", "_")+"_TTFF_"
801 sec_list = [float(ttff_data[key].ttff_sec) for key in ttff_data.keys()]
802 pe_list = [float(ttff_data[key].ttff_pe) for key in ttff_data.keys()]
803 cn_list = [float(ttff_data[key].ttff_cn) for key in ttff_data.keys()]
804 timeoutcount = sec_list.count(0.0)
805 avgttff = sum(sec_list)/(len(sec_list) - timeoutcount)
806 if timeoutcount != 0:
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800807 maxttff = 9527
jasonkmlu81b8b032019-06-21 15:18:27 +0800808 else:
809 maxttff = max(sec_list)
810 avgdis = sum(pe_list)/len(pe_list)
811 maxdis = max(pe_list)
812 avgcn = sum(cn_list)/len(cn_list)
813 ad.log.info(prop_basename+"AvgTime %.1f" % avgttff)
814 ad.log.info(prop_basename+"MaxTime %.1f" % maxttff)
815 ad.log.info(prop_basename+"TimeoutCount %d" % timeoutcount)
816 ad.log.info(prop_basename+"AvgDis %.1f" % avgdis)
817 ad.log.info(prop_basename+"MaxDis %.1f" % maxdis)
818 ad.log.info(prop_basename+"AvgSignal %.1f" % avgcn)
819
jasonkmlu903ece82019-05-16 14:56:19 +0800820def calculate_position_error(ad, latitude, longitude, true_position):
821 """Use haversine formula to calculate position error base on true location
822 coordinate.
823
824 Args:
825 ad: An AndroidDevice object.
826 latitude: latitude of location fixed in the present.
827 longitude: longitude of location fixed in the present.
828 true_position: [latitude, longitude] of true location coordinate.
829
830 Returns:
831 position_error of location fixed in the present.
832 """
833 radius = 6371009
834 dlat = math.radians(latitude - true_position[0])
835 dlon = math.radians(longitude - true_position[1])
836 a = math.sin(dlat/2) * math.sin(dlat/2) + \
837 math.cos(math.radians(true_position[0])) * \
838 math.cos(math.radians(latitude)) * math.sin(dlon/2) * math.sin(dlon/2)
839 c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
840 return radius * c
841
jasonkmluff0d5b92019-03-21 11:24:45 +0800842def launch_google_map(ad):
843 """Launch Google Map via intent.
844
845 Args:
846 ad: An AndroidDevice object.
847 """
848 ad.log.info("Launch Google Map.")
849 try:
850 ad.adb.shell("am start -S -n com.google.android.apps.maps/"
851 "com.google.android.maps.MapsActivity")
852 ad.send_keycode("BACK")
853 ad.force_stop_apk("com.google.android.apps.maps")
854 ad.adb.shell("am start -S -n com.google.android.apps.maps/"
855 "com.google.android.maps.MapsActivity")
856 except Exception as e:
857 ad.log.error(e)
858 raise signals.TestFailure("Failed to launch google map.")
jasonkmlu903ece82019-05-16 14:56:19 +0800859 check_currrent_focus_app(ad)
jasonkmlu49c32812019-04-12 18:11:10 +0800860
jasonkmlu903ece82019-05-16 14:56:19 +0800861def check_currrent_focus_app(ad):
862 """Check to see current focused window and app.
jasonkmlu49c32812019-04-12 18:11:10 +0800863
864 Args:
865 ad: An AndroidDevice object.
jasonkmlu49c32812019-04-12 18:11:10 +0800866 """
jasonkmlu903ece82019-05-16 14:56:19 +0800867 time.sleep(1)
868 current = ad.adb.shell("dumpsys window | grep -E 'mCurrentFocus|mFocusedApp'")
jasonkmlu81b8b032019-06-21 15:18:27 +0800869 ad.log.debug("\n"+current)
jasonkmluff0d5b92019-03-21 11:24:45 +0800870
871def check_location_api(ad, retries):
872 """Verify if GnssLocationProvider API reports location.
873
874 Args:
875 ad: An AndroidDevice object.
876 retries: Retry time.
877
878 Returns:
879 True: GnssLocationProvider API reports location.
880 otherwise return False.
881 """
882 for i in range(retries):
883 begin_time = get_current_epoch_time()
884 ad.log.info("Try to get location report from GnssLocationProvider API "
885 "- attempt %d" % (i+1))
886 while get_current_epoch_time() - begin_time <= 30000:
887 logcat_results = ad.search_logcat("REPORT_LOCATION", begin_time)
888 if logcat_results:
889 ad.log.info("%s" % logcat_results[-1]["log_message"])
890 ad.log.info("GnssLocationProvider reports location successfully.")
891 return True
892 if not ad.is_adb_logcat_on:
893 ad.start_adb_logcat()
894 ad.log.error("GnssLocationProvider is unable to report location.")
895 return False
896
897def check_network_location(ad, retries, location_type):
898 """Verify if NLP reports location after requesting via GPSTool.
899
900 Args:
901 ad: An AndroidDevice object.
902 retries: Retry time.
903 location_type: neworkLocationType of cell or wifi.
904
905 Returns:
906 True: NLP reports location.
907 otherwise return False.
908 """
909 for i in range(retries):
910 time.sleep(1)
911 begin_time = get_current_epoch_time()
912 ad.log.info("Try to get NLP status - attempt %d" % (i+1))
913 ad.adb.shell("am start -S -n com.android.gpstool/.GPSTool --es mode nlp")
914 while get_current_epoch_time() - begin_time <= 30000:
915 logcat_results = ad.search_logcat(
916 "LocationManagerService: incoming location: Location", begin_time)
917 if logcat_results:
918 for logcat_result in logcat_results:
919 if location_type in logcat_result["log_message"]:
920 ad.log.info(logcat_result["log_message"])
921 ad.send_keycode("BACK")
922 return True
923 if not ad.is_adb_logcat_on:
924 ad.start_adb_logcat()
925 ad.send_keycode("BACK")
926 ad.log.error("Unable to report network location \"%s\"." % location_type)
927 return False
928
jasonkmlu8d6bbfc2019-03-29 15:57:43 +0800929def set_attenuator_gnss_signal(ad, attenuator, atten_value):
jasonkmluff0d5b92019-03-21 11:24:45 +0800930 """Set attenuation value for different GNSS signal.
931
932 Args:
933 ad: An AndroidDevice object.
jasonkmlu8d6bbfc2019-03-29 15:57:43 +0800934 attenuator: The attenuator object.
jasonkmluff0d5b92019-03-21 11:24:45 +0800935 atten_value: attenuation value
936 """
jasonkmluff0d5b92019-03-21 11:24:45 +0800937 try:
jasonkmlu81b8b032019-06-21 15:18:27 +0800938 ad.log.info("Set attenuation value to \"%d\" for GNSS signal." % atten_value)
jasonkmlu8d6bbfc2019-03-29 15:57:43 +0800939 attenuator[0].set_atten(atten_value)
jasonkmlu81b8b032019-06-21 15:18:27 +0800940 except Exception as e:
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800941 ad.log.error(e)
jasonkmluff0d5b92019-03-21 11:24:45 +0800942
943def set_battery_saver_mode(ad, state):
944 """Enable or diable battery saver mode via adb.
945
946 Args:
947 ad: An AndroidDevice object.
948 state: True is enable Battery Saver mode. False is disable.
949 """
950 ad.root_adb()
951 if state:
952 ad.log.info("Enable Battery Saver mode.")
953 ad.adb.shell("cmd battery unplug")
954 ad.adb.shell("settings put global low_power 1")
955 else:
956 ad.log.info("Disable Battery Saver mode.")
957 ad.adb.shell("settings put global low_power 0")
958 ad.adb.shell("cmd battery reset")
959
960def set_gnss_qxdm_mask(ad, masks):
961 """Find defined gnss qxdm mask and set as default logging mask.
962
963 Args:
964 ad: An AndroidDevice object.
965 masks: Defined gnss qxdm mask.
966 """
967 try:
968 for mask in masks:
969 if not tutils.find_qxdm_log_mask(ad, mask):
970 continue
971 tutils.set_qxdm_logger_command(ad, mask)
972 break
973 except Exception as e:
974 ad.log.error(e)
jasonkmlu903ece82019-05-16 14:56:19 +0800975 raise signals.TestFailure("Failed to set any QXDM masks.")
976
977def start_youtube_video(ad, url=None, retries=0):
978 """Start youtube video and verify if audio is in music state.
jasonkmlu81b8b032019-06-21 15:18:27 +0800979
jasonkmlu903ece82019-05-16 14:56:19 +0800980 Args:
981 ad: An AndroidDevice object.
982 url: Youtube video url.
983 retries: Retry times if audio is not in music state.
jasonkmlu81b8b032019-06-21 15:18:27 +0800984
jasonkmlu903ece82019-05-16 14:56:19 +0800985 Returns:
986 True if youtube video is playing normally.
987 False if youtube video is not playing properly.
988 """
989 for i in range(retries):
990 ad.log.info("Open an youtube video - attempt %d" % (i+1))
991 ad.adb.shell("am start -a android.intent.action.VIEW -d \"%s\"" % url)
992 time.sleep(2)
993 out = ad.adb.shell("dumpsys activity | grep NewVersionAvailableActivity")
994 if out:
995 ad.log.info("Skip Youtube New Version Update.")
996 ad.send_keycode("BACK")
997 if tutils.wait_for_state(ad.droid.audioIsMusicActive, True, 15, 1):
998 ad.log.info("Started a video in youtube, audio is in MUSIC state")
999 return True
1000 ad.log.info("Force-Stop youtube and reopen youtube again.")
1001 ad.force_stop_apk("com.google.android.youtube")
jasonkmlu903ece82019-05-16 14:56:19 +08001002 check_currrent_focus_app(ad)
jasonkmlu81b8b032019-06-21 15:18:27 +08001003 raise signals.TestFailure("Started a video in youtube, "
1004 "but audio is not in MUSIC state")
1005
1006def get_baseband_and_gms_version(ad, extra_msg=""):
1007 """Get current radio baseband and GMSCore version of AndroidDevice object.
1008
1009 Args:
1010 ad: An AndroidDevice object.
1011 """
1012 try:
1013 baseband_version = ad.adb.getprop("gsm.version.baseband")
1014 gms_version = ad.adb.shell("dumpsys package com.google.android.gms | "
1015 "grep versionName").split("\n")[0].split("=")[1]
1016 if not extra_msg:
1017 ad.log.info("TestResult Baseband_Version %s" % baseband_version)
1018 ad.log.info("TestResult GMS_Version %s" % gms_version.replace(" ", ""))
1019 else:
1020 ad.log.info("%s, Baseband_Version = %s" % (extra_msg, baseband_version))
1021 except Exception as e:
1022 ad.log.error(e)