blob: 7b5c8414e633fcdb26b3bccccc2e0378746a5a2c [file] [log] [blame]
jasonkmlu4ba30a02020-04-09 14:16:49 +08001#!/usr/bin/env python3
jasonkmluff0d5b92019-03-21 11:24:45 +08002#
jasonkmludc430ec2020-03-27 10:40:39 +08003# Copyright 2020 - Google
jasonkmluff0d5b92019-03-21 11:24:45 +08004#
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
jasonkmlu903ece82019-05-16 14:56:19 +080021import shutil
jasonkmlu4fcdcad2019-07-10 14:35:12 +080022import fnmatch
23import posixpath
jasonkmlu5e7817c2020-05-08 14:06:43 +080024import tempfile
jasonkmlu8cc1c1e2020-01-06 17:18:27 +080025from collections import namedtuple
jasonkmluff0d5b92019-03-21 11:24:45 +080026
27from acts import utils
jasonkmlu9387b5a2021-04-23 03:28:40 +080028from acts import asserts
jasonkmluff0d5b92019-03-21 11:24:45 +080029from acts import signals
jasonkmlucb654ac2020-07-01 11:08:33 +080030from acts.libs.proc import job
jasonkmluff0d5b92019-03-21 11:24:45 +080031from acts.controllers.android_device import list_adb_devices
32from acts.controllers.android_device import list_fastboot_devices
33from acts.controllers.android_device import DEFAULT_QXDM_LOG_PATH
34from acts.controllers.android_device import SL4A_APK_NAME
Xianyuan Jia24299b72020-10-21 13:52:47 -070035from acts_contrib.test_utils.wifi import wifi_test_utils as wutils
Markus Liue26ef8a2021-10-19 15:20:35 +080036from acts_contrib.test_utils.tel import tel_logging_utils as tlutils
Xianyuan Jia24299b72020-10-21 13:52:47 -070037from acts_contrib.test_utils.tel import tel_test_utils as tutils
38from acts_contrib.test_utils.instrumentation.device.command.instrumentation_command_builder import InstrumentationCommandBuilder
39from acts_contrib.test_utils.instrumentation.device.command.instrumentation_command_builder import InstrumentationTestCommandBuilder
jasonkmluff0d5b92019-03-21 11:24:45 +080040from acts.utils import get_current_epoch_time
jasonkmlucb654ac2020-07-01 11:08:33 +080041from acts.utils import epoch_to_human_time
jasonkmluff0d5b92019-03-21 11:24:45 +080042
43WifiEnums = wutils.WifiEnums
44PULL_TIMEOUT = 300
jasonkmlu66fda532019-07-16 11:12:45 +080045GNSSSTATUS_LOG_PATH = (
46 "/storage/emulated/0/Android/data/com.android.gpstool/files/")
jasonkmlu214f0d62019-04-08 19:53:59 +080047QXDM_MASKS = ["GPS.cfg", "GPS-general.cfg", "default.cfg"]
jasonkmlucb654ac2020-07-01 11:08:33 +080048TTFF_REPORT = namedtuple(
49 "TTFF_REPORT", "utc_time ttff_loop ttff_sec ttff_pe ttff_ant_cn "
50 "ttff_base_cn")
jasonkmlu8cc1c1e2020-01-06 17:18:27 +080051TRACK_REPORT = namedtuple(
jasonkmlucb654ac2020-07-01 11:08:33 +080052 "TRACK_REPORT", "l5flag pe ant_top4cn ant_cn base_top4cn base_cn")
jasonkmlu6ea2a2b2020-11-02 13:29:41 +080053LOCAL_PROP_FILE_CONTENTS = """\
jasonkmlu38bd4d12019-10-04 16:38:48 +080054log.tag.LocationManagerService=VERBOSE
55log.tag.GnssLocationProvider=VERBOSE
56log.tag.GnssMeasurementsProvider=VERBOSE
57log.tag.GpsNetInitiatedHandler=VERBOSE
jasonkmlu6ea2a2b2020-11-02 13:29:41 +080058log.tag.GnssNetInitiatedHandler=VERBOSE
jasonkmlu38bd4d12019-10-04 16:38:48 +080059log.tag.GnssNetworkConnectivityHandler=VERBOSE
60log.tag.ConnectivityService=VERBOSE
61log.tag.ConnectivityManager=VERBOSE
jasonkmludc430ec2020-03-27 10:40:39 +080062log.tag.GnssVisibilityControl=VERBOSE
63log.tag.NtpTimeHelper=VERBOSE
jasonkmlu6ea2a2b2020-11-02 13:29:41 +080064log.tag.NtpTrustedTime=VERBOSE
65log.tag.GnssPsdsDownloader=VERBOSE
66log.tag.Gnss=VERBOSE
67log.tag.GnssConfiguration=VERBOSE"""
jasonkmlu4ba30a02020-04-09 14:16:49 +080068TEST_PACKAGE_NAME = "com.google.android.apps.maps"
jasonkmludc430ec2020-03-27 10:40:39 +080069LOCATION_PERMISSIONS = [
jasonkmlu4ba30a02020-04-09 14:16:49 +080070 "android.permission.ACCESS_FINE_LOCATION",
71 "android.permission.ACCESS_COARSE_LOCATION"
jasonkmludc430ec2020-03-27 10:40:39 +080072]
jasonkmlu4ba30a02020-04-09 14:16:49 +080073GNSSTOOL_PACKAGE_NAME = "com.android.gpstool"
74GNSSTOOL_PERMISSIONS = [
75 "android.permission.ACCESS_FINE_LOCATION",
76 "android.permission.READ_EXTERNAL_STORAGE",
77 "android.permission.ACCESS_COARSE_LOCATION",
78 "android.permission.CALL_PHONE",
79 "android.permission.WRITE_CONTACTS",
80 "android.permission.CAMERA",
81 "android.permission.WRITE_EXTERNAL_STORAGE",
82 "android.permission.READ_CONTACTS",
83 "android.permission.ACCESS_BACKGROUND_LOCATION"
84]
jasonkmluc0939182021-02-19 18:34:28 +080085DISABLE_LTO_FILE_CONTENTS = """\
86LONGTERM_PSDS_SERVER_1="http://"
87LONGTERM_PSDS_SERVER_2="http://"
88LONGTERM_PSDS_SERVER_3="http://"
89NORMAL_PSDS_SERVER="http://"
90REALTIME_PSDS_SERVER="http://"
91"""
jasonkmlu4ba30a02020-04-09 14:16:49 +080092
jasonkmluff0d5b92019-03-21 11:24:45 +080093
jasonkmluff0d5b92019-03-21 11:24:45 +080094class GnssTestUtilsError(Exception):
95 pass
96
jasonkmlu0f546de2019-12-13 20:58:41 +080097
jasonkmluff0d5b92019-03-21 11:24:45 +080098def remount_device(ad):
99 """Remount device file system to read and write.
100
101 Args:
102 ad: An AndroidDevice object.
103 """
jasonkmlu81b8b032019-06-21 15:18:27 +0800104 for retries in range(5):
jasonkmluff0d5b92019-03-21 11:24:45 +0800105 ad.root_adb()
Scott Hong7f3945f2020-02-20 18:04:56 +0800106 if ad.adb.getprop("ro.boot.veritymode") == "enforcing":
jasonkmlu6ea2a2b2020-11-02 13:29:41 +0800107 ad.adb.disable_verity()
Scott Hong7f3945f2020-02-20 18:04:56 +0800108 reboot(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800109 remount_result = ad.adb.remount()
110 ad.log.info("Attempt %d - %s" % (retries + 1, remount_result))
jasonkmlu81b8b032019-06-21 15:18:27 +0800111 if "remount succeeded" in remount_result:
jasonkmluff0d5b92019-03-21 11:24:45 +0800112 break
jasonkmlu214f0d62019-04-08 19:53:59 +0800113
jasonkmlu0f546de2019-12-13 20:58:41 +0800114
jasonkmlu214f0d62019-04-08 19:53:59 +0800115def reboot(ad):
116 """Reboot device and check if mobile data is available.
117
118 Args:
119 ad: An AndroidDevice object.
120 """
121 ad.log.info("Reboot device to make changes take effect.")
122 ad.reboot()
123 ad.unlock_screen(password=None)
124 if not int(ad.adb.shell("settings get global mobile_data")) == 1:
125 set_mobile_data(ad, True)
jasonkmlu49c32812019-04-12 18:11:10 +0800126 utils.sync_device_time(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800127
jasonkmlu0f546de2019-12-13 20:58:41 +0800128
jasonkmluff0d5b92019-03-21 11:24:45 +0800129def enable_gnss_verbose_logging(ad):
jasonkmlu81b8b032019-06-21 15:18:27 +0800130 """Enable GNSS VERBOSE Logging and persistent logcat.
jasonkmluff0d5b92019-03-21 11:24:45 +0800131
132 Args:
133 ad: An AndroidDevice object.
134 """
135 remount_device(ad)
jasonkmlu97ac56e2019-05-29 15:04:51 +0800136 ad.log.info("Enable GNSS VERBOSE Logging and persistent logcat.")
jasonkmluc0939182021-02-19 18:34:28 +0800137 if check_chipset_vendor_by_qualcomm(ad):
138 ad.adb.shell("echo -e '\nDEBUG_LEVEL = 5' >> /vendor/etc/gps.conf")
139 else:
140 ad.adb.shell("echo LogEnabled=true >> /data/vendor/gps/libgps.conf")
141 ad.adb.shell("chown gps.system /data/vendor/gps/libgps.conf")
jasonkmlu38bd4d12019-10-04 16:38:48 +0800142 ad.adb.shell("echo %r >> /data/local.prop" % LOCAL_PROP_FILE_CONTENTS)
jasonkmluff0d5b92019-03-21 11:24:45 +0800143 ad.adb.shell("chmod 644 /data/local.prop")
jasonkmluc1ec3052019-10-25 14:57:53 +0800144 ad.adb.shell("setprop persist.logd.logpersistd.size 20000")
jasonkmlu180a08c2019-04-23 17:24:55 +0800145 ad.adb.shell("setprop persist.logd.size 16777216")
jasonkmluff0d5b92019-03-21 11:24:45 +0800146 ad.adb.shell("setprop persist.vendor.radio.adb_log_on 1")
jasonkmlu81b8b032019-06-21 15:18:27 +0800147 ad.adb.shell("setprop persist.logd.logpersistd logcatd")
jasonkmluff0d5b92019-03-21 11:24:45 +0800148 ad.adb.shell("setprop log.tag.copresGcore VERBOSE")
149 ad.adb.shell("sync")
150
jasonkmlu0f546de2019-12-13 20:58:41 +0800151
jasonkmlu8cc1c1e2020-01-06 17:18:27 +0800152def get_am_flags(value):
153 """Returns the (value, type) flags for a given python value."""
154 if type(value) is bool:
155 return str(value).lower(), 'boolean'
156 elif type(value) is str:
157 return value, 'string'
158 raise ValueError("%s should be either 'boolean' or 'string'" % value)
159
160
jasonkmlu81b8b032019-06-21 15:18:27 +0800161def enable_compact_and_particle_fusion_log(ad):
jasonkmlu8cc1c1e2020-01-06 17:18:27 +0800162 """Enable CompactLog, FLP particle fusion log and disable gms
163 location-based quake monitoring.
jasonkmlu81b8b032019-06-21 15:18:27 +0800164
165 Args:
166 ad: An AndroidDevice object.
167 """
168 ad.root_adb()
jasonkmlu8cc1c1e2020-01-06 17:18:27 +0800169 ad.log.info("Enable FLP flags and Disable GMS location-based quake "
170 "monitoring.")
171 overrides = {
172 'compact_log_enabled': True,
173 'flp_use_particle_fusion': True,
174 'flp_particle_fusion_extended_bug_report': True,
175 'flp_event_log_size': '86400',
176 'proks_config': '28',
177 'flp_particle_fusion_bug_report_window_sec': '86400',
178 'flp_particle_fusion_bug_report_max_buffer_size': '86400',
179 'seismic_data_collection': False,
180 'Ealert__enable': False,
181 }
182 for flag, python_value in overrides.items():
183 value, type = get_am_flags(python_value)
184 cmd = ("am broadcast -a com.google.android.gms.phenotype.FLAG_OVERRIDE "
185 "--es package com.google.android.location --es user \* "
186 "--esa flags %s --esa values %s --esa types %s "
187 "com.google.android.gms" % (flag, value, type))
188 ad.adb.shell(cmd)
jasonkmlu81b8b032019-06-21 15:18:27 +0800189 ad.adb.shell("am force-stop com.google.android.gms")
190 ad.adb.shell("am broadcast -a com.google.android.gms.INITIALIZE")
jasonkmlu81b8b032019-06-21 15:18:27 +0800191
jasonkmlu0f546de2019-12-13 20:58:41 +0800192
jasonkmluff0d5b92019-03-21 11:24:45 +0800193def disable_xtra_throttle(ad):
194 """Disable XTRA throttle will have no limit to download XTRA data.
195
196 Args:
197 ad: An AndroidDevice object.
198 """
199 remount_device(ad)
200 ad.log.info("Disable XTRA Throttle.")
Scott Hongaccd8a12020-03-03 20:12:17 +0800201 ad.adb.shell("echo -e '\nXTRA_TEST_ENABLED=1' >> /vendor/etc/gps.conf")
202 ad.adb.shell("echo -e '\nXTRA_THROTTLE_ENABLED=0' >> /vendor/etc/gps.conf")
jasonkmluff0d5b92019-03-21 11:24:45 +0800203
jasonkmlu0f546de2019-12-13 20:58:41 +0800204
jasonkmluff0d5b92019-03-21 11:24:45 +0800205def enable_supl_mode(ad):
206 """Enable SUPL back on for next test item.
207
208 Args:
209 ad: An AndroidDevice object.
210 """
211 remount_device(ad)
212 ad.log.info("Enable SUPL mode.")
Scott Hongaccd8a12020-03-03 20:12:17 +0800213 ad.adb.shell("echo -e '\nSUPL_MODE=1' >> /etc/gps_debug.conf")
jasonkmluc0939182021-02-19 18:34:28 +0800214 if not check_chipset_vendor_by_qualcomm(ad):
215 lto_mode(ad, True)
216 else:
217 reboot(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800218
jasonkmlu0f546de2019-12-13 20:58:41 +0800219
jasonkmluff0d5b92019-03-21 11:24:45 +0800220def disable_supl_mode(ad):
jasonkmluc0939182021-02-19 18:34:28 +0800221 """Kill SUPL to test XTRA/LTO only test item.
jasonkmluff0d5b92019-03-21 11:24:45 +0800222
223 Args:
224 ad: An AndroidDevice object.
225 """
226 remount_device(ad)
227 ad.log.info("Disable SUPL mode.")
Scott Hongaccd8a12020-03-03 20:12:17 +0800228 ad.adb.shell("echo -e '\nSUPL_MODE=0' >> /etc/gps_debug.conf")
jasonkmluc0939182021-02-19 18:34:28 +0800229 if not check_chipset_vendor_by_qualcomm(ad):
230 lto_mode(ad, True)
231 else:
232 reboot(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800233
jasonkmlu0f546de2019-12-13 20:58:41 +0800234
jasonkmluff0d5b92019-03-21 11:24:45 +0800235def kill_xtra_daemon(ad):
236 """Kill XTRA daemon to test SUPL only test item.
237
238 Args:
239 ad: An AndroidDevice object.
240 """
241 ad.root_adb()
jasonkmluc0939182021-02-19 18:34:28 +0800242 if check_chipset_vendor_by_qualcomm(ad):
243 ad.log.info("Disable XTRA-daemon until next reboot.")
244 ad.adb.shell("killall xtra-daemon", ignore_status=True)
245 else:
246 lto_mode(ad, False)
jasonkmluff0d5b92019-03-21 11:24:45 +0800247
jasonkmlu0f546de2019-12-13 20:58:41 +0800248
jasonkmluff0d5b92019-03-21 11:24:45 +0800249def disable_private_dns_mode(ad):
250 """Due to b/118365122, it's better to disable private DNS mode while
251 testing. 8.8.8.8 private dns sever is unstable now, sometimes server
252 will not response dns query suddenly.
253
254 Args:
255 ad: An AndroidDevice object.
256 """
257 tutils.get_operator_name(ad.log, ad, subId=None)
258 if ad.adb.shell("settings get global private_dns_mode") != "off":
259 ad.log.info("Disable Private DNS mode.")
260 ad.adb.shell("settings put global private_dns_mode off")
261
jasonkmlu0f546de2019-12-13 20:58:41 +0800262
jasonkmluff0d5b92019-03-21 11:24:45 +0800263def _init_device(ad):
264 """Init GNSS test devices.
265
266 Args:
267 ad: An AndroidDevice object.
268 """
269 enable_gnss_verbose_logging(ad)
jasonkmlu81b8b032019-06-21 15:18:27 +0800270 enable_compact_and_particle_fusion_log(ad)
jasonkmluc0939182021-02-19 18:34:28 +0800271 if check_chipset_vendor_by_qualcomm(ad):
272 disable_xtra_throttle(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800273 enable_supl_mode(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800274 ad.adb.shell("settings put system screen_off_timeout 1800000")
275 wutils.wifi_toggle_state(ad, False)
276 ad.log.info("Setting Bluetooth state to False")
277 ad.droid.bluetoothToggleState(False)
jasonkmluff0d5b92019-03-21 11:24:45 +0800278 check_location_service(ad)
279 set_wifi_and_bt_scanning(ad, True)
jasonkmlu214f0d62019-04-08 19:53:59 +0800280 disable_private_dns_mode(ad)
jasonkmlu180a08c2019-04-23 17:24:55 +0800281 reboot(ad)
jasonkmlu4ba30a02020-04-09 14:16:49 +0800282 init_gtw_gpstool(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800283
jasonkmlu0f546de2019-12-13 20:58:41 +0800284
jasonkmluff0d5b92019-03-21 11:24:45 +0800285def connect_to_wifi_network(ad, network):
286 """Connection logic for open and psk wifi networks.
287
288 Args:
289 ad: An AndroidDevice object.
290 network: Dictionary with network info.
291 """
292 SSID = network[WifiEnums.SSID_KEY]
jasonkmlub663d3e2019-12-30 15:11:07 +0800293 ad.ed.clear_all_events()
294 wutils.reset_wifi(ad)
295 wutils.start_wifi_connection_scan_and_ensure_network_found(ad, SSID)
jasonkmluff0d5b92019-03-21 11:24:45 +0800296 wutils.wifi_connect(ad, network, num_of_tries=5)
297
jasonkmlu0f546de2019-12-13 20:58:41 +0800298
jasonkmluff0d5b92019-03-21 11:24:45 +0800299def set_wifi_and_bt_scanning(ad, state=True):
300 """Set Wi-Fi and Bluetooth scanning on/off in Settings -> Location
301
302 Args:
303 ad: An AndroidDevice object.
jasonkmlu81b8b032019-06-21 15:18:27 +0800304 state: True to turn on "Wi-Fi and Bluetooth scanning".
305 False to turn off "Wi-Fi and Bluetooth scanning".
jasonkmluff0d5b92019-03-21 11:24:45 +0800306 """
307 ad.root_adb()
308 if state:
309 ad.adb.shell("settings put global wifi_scan_always_enabled 1")
310 ad.adb.shell("settings put global ble_scan_always_enabled 1")
311 ad.log.info("Wi-Fi and Bluetooth scanning are enabled")
312 else:
313 ad.adb.shell("settings put global wifi_scan_always_enabled 0")
314 ad.adb.shell("settings put global ble_scan_always_enabled 0")
315 ad.log.info("Wi-Fi and Bluetooth scanning are disabled")
316
jasonkmlu0f546de2019-12-13 20:58:41 +0800317
jasonkmluff0d5b92019-03-21 11:24:45 +0800318def check_location_service(ad):
319 """Set location service on.
320 Verify if location service is available.
321
322 Args:
323 ad: An AndroidDevice object.
jasonkmluff0d5b92019-03-21 11:24:45 +0800324 """
jasonkmlu81b8b032019-06-21 15:18:27 +0800325 remount_device(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800326 utils.set_location_service(ad, True)
jasonkmlu81b8b032019-06-21 15:18:27 +0800327 location_mode = int(ad.adb.shell("settings get secure location_mode"))
328 ad.log.info("Current Location Mode >> %d" % location_mode)
329 if location_mode != 3:
jasonkmlu78540632019-11-15 18:04:20 +0800330 raise signals.TestError("Failed to turn Location on")
jasonkmluff0d5b92019-03-21 11:24:45 +0800331
jasonkmlu0f546de2019-12-13 20:58:41 +0800332
jasonkmluff0d5b92019-03-21 11:24:45 +0800333def clear_logd_gnss_qxdm_log(ad):
334 """Clear /data/misc/logd,
335 /storage/emulated/0/Android/data/com.android.gpstool/files and
336 /data/vendor/radio/diag_logs/logs from previous test item then reboot.
337
338 Args:
339 ad: An AndroidDevice object.
340 """
341 remount_device(ad)
jasonkmlu9387b5a2021-04-23 03:28:40 +0800342 ad.log.info("Clear Logd, GNSS and PixelLogger Log from previous test item.")
jasonkmluff0d5b92019-03-21 11:24:45 +0800343 ad.adb.shell("rm -rf /data/misc/logd", ignore_status=True)
Scott Hong0ccbc752020-10-12 14:18:49 +0800344 ad.adb.shell(
345 'find %s -name "*.txt" -type f -delete' % GNSSSTATUS_LOG_PATH,
346 ignore_status=True)
jasonkmluc0939182021-02-19 18:34:28 +0800347 if check_chipset_vendor_by_qualcomm(ad):
jasonkmlu9b278f92021-04-20 01:06:50 +0800348 diag_logs = (
349 "/sdcard/Android/data/com.android.pixellogger/files/logs/diag_logs")
350 ad.adb.shell("rm -rf %s" % diag_logs, ignore_status=True)
jasonkmluc0939182021-02-19 18:34:28 +0800351 output_path = posixpath.join(DEFAULT_QXDM_LOG_PATH, "logs")
352 else:
353 output_path = ("/sdcard/Android/data/com.android.pixellogger/files"
354 "/logs/gps/")
jasonkmluff0d5b92019-03-21 11:24:45 +0800355 ad.adb.shell("rm -rf %s" % output_path, ignore_status=True)
jasonkmlu214f0d62019-04-08 19:53:59 +0800356 reboot(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800357
jasonkmlu0f546de2019-12-13 20:58:41 +0800358
jasonkmlu81b8b032019-06-21 15:18:27 +0800359def get_gnss_qxdm_log(ad, qdb_path):
jasonkmluff0d5b92019-03-21 11:24:45 +0800360 """Get /storage/emulated/0/Android/data/com.android.gpstool/files and
jasonkmlu81b8b032019-06-21 15:18:27 +0800361 /data/vendor/radio/diag_logs/logs for test item.
jasonkmluff0d5b92019-03-21 11:24:45 +0800362
363 Args:
364 ad: An AndroidDevice object.
jasonkmlu81b8b032019-06-21 15:18:27 +0800365 qdb_path: The path of qdsp6m.qdb on different projects.
jasonkmluff0d5b92019-03-21 11:24:45 +0800366 """
jasonkmlu903ece82019-05-16 14:56:19 +0800367 log_path = ad.device_log_path
Mark De Ruyter72f8df92020-02-12 13:44:49 -0800368 os.makedirs(log_path, exist_ok=True)
jasonkmlu903ece82019-05-16 14:56:19 +0800369 gnss_log_name = "gnssstatus_log_%s_%s" % (ad.model, ad.serial)
jasonkmlu670cfbc2019-11-27 18:58:21 +0800370 gnss_log_path = posixpath.join(log_path, gnss_log_name)
Mark De Ruyter72f8df92020-02-12 13:44:49 -0800371 os.makedirs(gnss_log_path, exist_ok=True)
jasonkmluff0d5b92019-03-21 11:24:45 +0800372 ad.log.info("Pull GnssStatus Log to %s" % gnss_log_path)
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800373 ad.adb.pull("%s %s" % (GNSSSTATUS_LOG_PATH+".", gnss_log_path),
jasonkmluff0d5b92019-03-21 11:24:45 +0800374 timeout=PULL_TIMEOUT, ignore_status=True)
jasonkmlu903ece82019-05-16 14:56:19 +0800375 shutil.make_archive(gnss_log_path, "zip", gnss_log_path)
376 shutil.rmtree(gnss_log_path)
jasonkmluc0939182021-02-19 18:34:28 +0800377 if check_chipset_vendor_by_qualcomm(ad):
jasonkmlu9b278f92021-04-20 01:06:50 +0800378 output_path = (
379 "/sdcard/Android/data/com.android.pixellogger/files/logs/diag_logs")
jasonkmluc0939182021-02-19 18:34:28 +0800380 else:
jasonkmlu9b278f92021-04-20 01:06:50 +0800381 output_path = (
382 "/sdcard/Android/data/com.android.pixellogger/files/logs/gps/")
jasonkmlu9387b5a2021-04-23 03:28:40 +0800383 qxdm_log_name = "PixelLogger_%s_%s" % (ad.model, ad.serial)
384 qxdm_log_path = posixpath.join(log_path, qxdm_log_name)
385 os.makedirs(qxdm_log_path, exist_ok=True)
386 ad.log.info("Pull PixelLogger Log %s to %s" % (output_path,
387 qxdm_log_path))
388 ad.adb.pull("%s %s" % (output_path, qxdm_log_path),
389 timeout=PULL_TIMEOUT, ignore_status=True)
390 if check_chipset_vendor_by_qualcomm(ad):
jasonkmlu81b8b032019-06-21 15:18:27 +0800391 for path in qdb_path:
392 output = ad.adb.pull("%s %s" % (path, qxdm_log_path),
393 timeout=PULL_TIMEOUT, ignore_status=True)
394 if "No such file or directory" in output:
395 continue
396 break
jasonkmlu9387b5a2021-04-23 03:28:40 +0800397 shutil.make_archive(qxdm_log_path, "zip", qxdm_log_path)
398 shutil.rmtree(qxdm_log_path)
jasonkmluff0d5b92019-03-21 11:24:45 +0800399
jasonkmlu0f546de2019-12-13 20:58:41 +0800400
jasonkmluff0d5b92019-03-21 11:24:45 +0800401def set_mobile_data(ad, state):
402 """Set mobile data on or off and check mobile data state.
403
404 Args:
405 ad: An AndroidDevice object.
406 state: True to enable mobile data. False to disable mobile data.
407 """
408 ad.root_adb()
409 if state:
410 ad.log.info("Enable mobile data.")
411 ad.adb.shell("svc data enable")
412 else:
413 ad.log.info("Disable mobile data.")
414 ad.adb.shell("svc data disable")
415 time.sleep(5)
416 out = int(ad.adb.shell("settings get global mobile_data"))
417 if state and out == 1:
418 ad.log.info("Mobile data is enabled and set to %d" % out)
419 elif not state and out == 0:
420 ad.log.info("Mobile data is disabled and set to %d" % out)
421 else:
422 ad.log.error("Mobile data is at unknown state and set to %d" % out)
423
jasonkmlu0f546de2019-12-13 20:58:41 +0800424
jasonkmlu78540632019-11-15 18:04:20 +0800425def gnss_trigger_modem_ssr_by_adb(ad, dwelltime=60):
426 """Trigger modem SSR crash by adb and verify if modem crash and recover
jasonkmlu035eee12019-10-08 17:11:20 +0800427 successfully.
jasonkmluff0d5b92019-03-21 11:24:45 +0800428
429 Args:
430 ad: An AndroidDevice object.
jasonkmlu78540632019-11-15 18:04:20 +0800431 dwelltime: Waiting time for modem reset. Default is 60 seconds.
jasonkmluff0d5b92019-03-21 11:24:45 +0800432
433 Returns:
jasonkmlu81b8b032019-06-21 15:18:27 +0800434 True if success.
435 False if failed.
jasonkmluff0d5b92019-03-21 11:24:45 +0800436 """
jasonkmlu81b8b032019-06-21 15:18:27 +0800437 begin_time = get_current_epoch_time()
438 ad.root_adb()
439 cmds = ("echo restart > /sys/kernel/debug/msm_subsys/modem",
440 r"echo 'at+cfun=1,1\r' > /dev/at_mdm0")
441 for cmd in cmds:
442 ad.log.info("Triggering modem SSR crash by %s" % cmd)
443 output = ad.adb.shell(cmd, ignore_status=True)
444 if "No such file or directory" in output:
445 continue
446 break
447 time.sleep(dwelltime)
jasonkmluff0d5b92019-03-21 11:24:45 +0800448 ad.send_keycode("HOME")
jasonkmlu81b8b032019-06-21 15:18:27 +0800449 logcat_results = ad.search_logcat("SSRObserver", begin_time)
450 if logcat_results:
451 for ssr in logcat_results:
452 if "mSubsystem='modem', mCrashReason" in ssr["log_message"]:
453 ad.log.debug(ssr["log_message"])
454 ad.log.info("Triggering modem SSR crash successfully.")
455 return True
jasonkmlu78540632019-11-15 18:04:20 +0800456 raise signals.TestError("Failed to trigger modem SSR crash")
457 raise signals.TestError("No SSRObserver found in logcat")
458
jasonkmlu0f546de2019-12-13 20:58:41 +0800459
jasonkmlu78540632019-11-15 18:04:20 +0800460def gnss_trigger_modem_ssr_by_mds(ad, dwelltime=60):
461 """Trigger modem SSR crash by mds tool and verify if modem crash and recover
462 successfully.
463
464 Args:
465 ad: An AndroidDevice object.
466 dwelltime: Waiting time for modem reset. Default is 60 seconds.
467 """
468 mds_check = ad.adb.shell("pm path com.google.mdstest")
469 if not mds_check:
470 raise signals.TestError("MDS Tool is not properly installed.")
471 ad.root_adb()
472 cmd = ('am instrument -w -e request "4b 25 03 00" '
473 '"com.google.mdstest/com.google.mdstest.instrument'
474 '.ModemCommandInstrumentation"')
475 ad.log.info("Triggering modem SSR crash by MDS")
476 output = ad.adb.shell(cmd, ignore_status=True)
477 ad.log.debug(output)
478 time.sleep(dwelltime)
479 ad.send_keycode("HOME")
480 if "SUCCESS" in output:
481 ad.log.info("Triggering modem SSR crash by MDS successfully.")
482 else:
483 raise signals.TestError(
484 "Failed to trigger modem SSR crash by MDS. \n%s" % output)
485
jasonkmlu0f546de2019-12-13 20:58:41 +0800486
jasonkmluff0d5b92019-03-21 11:24:45 +0800487def check_xtra_download(ad, begin_time):
488 """Verify XTRA download success log message in logcat.
489
490 Args:
491 ad: An AndroidDevice object.
492 begin_time: test begin time
493
494 Returns:
495 True: xtra_download if XTRA downloaded and injected successfully
496 otherwise return False.
497 """
498 ad.send_keycode("HOME")
jasonkmluc0939182021-02-19 18:34:28 +0800499 if check_chipset_vendor_by_qualcomm(ad):
500 xtra_results = ad.search_logcat("XTRA download success. "
501 "inject data into modem", begin_time)
502 if xtra_results:
503 ad.log.debug("%s" % xtra_results[-1]["log_message"])
504 ad.log.info("XTRA downloaded and injected successfully.")
505 return True
506 ad.log.error("XTRA downloaded FAIL.")
507 else:
508 lto_results = ad.search_logcat("GnssPsdsAidl: injectPsdsData: "
509 "psdsType: 1", begin_time)
510 if lto_results:
511 ad.log.debug("%s" % lto_results[-1]["log_message"])
512 ad.log.info("LTO downloaded and injected successfully.")
513 return True
514 ad.log.error("LTO downloaded and inject FAIL.")
jasonkmluff0d5b92019-03-21 11:24:45 +0800515 return False
516
jasonkmlu0f546de2019-12-13 20:58:41 +0800517
jasonkmlu5e7817c2020-05-08 14:06:43 +0800518def pull_package_apk(ad, package_name):
519 """Pull apk of given package_name from device.
jasonkmluff0d5b92019-03-21 11:24:45 +0800520
521 Args:
522 ad: An AndroidDevice object.
jasonkmlu5e7817c2020-05-08 14:06:43 +0800523 package_name: Package name of apk to pull.
524
525 Returns:
526 The temp path of pulled apk.
jasonkmluff0d5b92019-03-21 11:24:45 +0800527 """
jasonkmlu6ea2a2b2020-11-02 13:29:41 +0800528 apk_path = None
jasonkmlu5e7817c2020-05-08 14:06:43 +0800529 out = ad.adb.shell("pm path %s" % package_name)
jasonkmluff0d5b92019-03-21 11:24:45 +0800530 result = re.search(r"package:(.*)", out)
531 if not result:
jasonkmlu5e7817c2020-05-08 14:06:43 +0800532 tutils.abort_all_tests(ad.log, "Couldn't find apk of %s" % package_name)
jasonkmluff0d5b92019-03-21 11:24:45 +0800533 else:
jasonkmlu5e7817c2020-05-08 14:06:43 +0800534 apk_source = result.group(1)
535 ad.log.info("Get apk of %s from %s" % (package_name, apk_source))
536 apk_path = tempfile.mkdtemp()
537 ad.pull_files([apk_source], apk_path)
538 return apk_path
jasonkmluff0d5b92019-03-21 11:24:45 +0800539
jasonkmlu0f546de2019-12-13 20:58:41 +0800540
jasonkmlu9387b5a2021-04-23 03:28:40 +0800541def pull_gnss_cfg_file(ad, file):
542 """Pull given gnss cfg file from device.
543
544 Args:
545 ad: An AndroidDevice object.
546 file: CFG file in device to pull.
547
548 Returns:
549 The temp path of pulled gnss cfg file in host.
550 """
551 ad.root_adb()
552 host_dest = tempfile.mkdtemp()
553 ad.pull_files(file, host_dest)
554 for path_key in os.listdir(host_dest):
555 if fnmatch.fnmatch(path_key, "*.cfg"):
556 gnss_cfg_file = os.path.join(host_dest, path_key)
557 break
558 else:
559 raise signals.TestError("No cfg file is found in %s" % host_dest)
560 return gnss_cfg_file
561
562
jasonkmlu5e7817c2020-05-08 14:06:43 +0800563def reinstall_package_apk(ad, package_name, apk_path):
564 """Reinstall apk of given package_name.
jasonkmluff0d5b92019-03-21 11:24:45 +0800565
566 Args:
567 ad: An AndroidDevice object.
jasonkmlu5e7817c2020-05-08 14:06:43 +0800568 package_name: Package name of apk.
569 apk_path: The temp path of pulled apk.
jasonkmluff0d5b92019-03-21 11:24:45 +0800570 """
jasonkmlu5e7817c2020-05-08 14:06:43 +0800571 for path_key in os.listdir(apk_path):
572 if fnmatch.fnmatch(path_key, "*.apk"):
573 apk_path = os.path.join(apk_path, path_key)
574 break
575 else:
576 raise signals.TestError("No apk is found in %s" % apk_path)
577 ad.log.info("Re-install %s with path: %s" % (package_name, apk_path))
578 ad.adb.shell("settings put global verifier_verify_adb_installs 0")
579 ad.adb.install("-r -d -g --user 0 %s" % apk_path)
580 package_check = ad.adb.shell("pm path %s" % package_name)
581 if not package_check:
582 tutils.abort_all_tests(
583 ad.log, "%s is not properly re-installed." % package_name)
584 ad.log.info("%s is re-installed successfully." % package_name)
jasonkmluff0d5b92019-03-21 11:24:45 +0800585
jasonkmlu0f546de2019-12-13 20:58:41 +0800586
jasonkmlu180a08c2019-04-23 17:24:55 +0800587def init_gtw_gpstool(ad):
588 """Init GTW_GPSTool apk.
589
590 Args:
591 ad: An AndroidDevice object.
592 """
593 remount_device(ad)
jasonkmlu5e7817c2020-05-08 14:06:43 +0800594 gpstool_path = pull_package_apk(ad, "com.android.gpstool")
595 reinstall_package_apk(ad, "com.android.gpstool", gpstool_path)
jasonkmlu180a08c2019-04-23 17:24:55 +0800596
jasonkmlu0f546de2019-12-13 20:58:41 +0800597
jasonkmluff0d5b92019-03-21 11:24:45 +0800598def fastboot_factory_reset(ad):
599 """Factory reset the device in fastboot mode.
600 Pull sl4a apk from device. Terminate all sl4a sessions,
601 Reboot the device to bootloader,
602 factory reset the device by fastboot.
603 Reboot the device. wait for device to complete booting
604 Re-install and start an sl4a session.
605
606 Args:
607 ad: An AndroidDevice object.
608
609 Returns:
610 True if factory reset process complete.
611 """
612 status = True
613 skip_setup_wizard = True
jasonkmlu9387b5a2021-04-23 03:28:40 +0800614 gnss_cfg_path = "/vendor/etc/mdlog"
615 default_gnss_cfg = "/vendor/etc/mdlog/DEFAULT+SECURITY+FULLDPL+GPS.cfg"
jasonkmlu5e7817c2020-05-08 14:06:43 +0800616 sl4a_path = pull_package_apk(ad, SL4A_APK_NAME)
617 gpstool_path = pull_package_apk(ad, "com.android.gpstool")
618 mds_path = pull_package_apk(ad, "com.google.mdstest")
jasonkmlu9387b5a2021-04-23 03:28:40 +0800619 if check_chipset_vendor_by_qualcomm(ad):
620 gnss_cfg_file = pull_gnss_cfg_file(ad, default_gnss_cfg)
621 stop_pixel_logger(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800622 ad.stop_services()
623 attempts = 3
624 for i in range(1, attempts + 1):
625 try:
626 if ad.serial in list_adb_devices():
627 ad.log.info("Reboot to bootloader")
628 ad.adb.reboot("bootloader", ignore_status=True)
629 time.sleep(10)
630 if ad.serial in list_fastboot_devices():
631 ad.log.info("Factory reset in fastboot")
632 ad.fastboot._w(timeout=300, ignore_status=True)
633 time.sleep(30)
634 ad.log.info("Reboot in fastboot")
635 ad.fastboot.reboot()
636 ad.wait_for_boot_completion()
637 ad.root_adb()
638 if ad.skip_sl4a:
639 break
640 if ad.is_sl4a_installed():
641 break
jasonkmlu5e7817c2020-05-08 14:06:43 +0800642 reinstall_package_apk(ad, SL4A_APK_NAME, sl4a_path)
643 reinstall_package_apk(ad, "com.android.gpstool", gpstool_path)
644 reinstall_package_apk(ad, "com.google.mdstest", mds_path)
jasonkmlu9387b5a2021-04-23 03:28:40 +0800645 if check_chipset_vendor_by_qualcomm(ad):
646 ad.push_system_file(gnss_cfg_file, gnss_cfg_path)
jasonkmluff0d5b92019-03-21 11:24:45 +0800647 time.sleep(10)
648 break
649 except Exception as e:
650 ad.log.error(e)
651 if i == attempts:
652 tutils.abort_all_tests(ad.log, str(e))
653 time.sleep(5)
654 try:
655 ad.start_adb_logcat()
656 except Exception as e:
657 ad.log.error(e)
658 if skip_setup_wizard:
659 ad.exit_setup_wizard()
660 if ad.skip_sl4a:
661 return status
662 tutils.bring_up_sl4a(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800663 return status
664
jasonkmlu0f546de2019-12-13 20:58:41 +0800665
jasonkmluff0d5b92019-03-21 11:24:45 +0800666def clear_aiding_data_by_gtw_gpstool(ad):
667 """Launch GTW GPSTool and Clear all GNSS aiding data.
668 Wait 5 seconds for GTW GPStool to clear all GNSS aiding
669 data properly.
670
671 Args:
672 ad: An AndroidDevice object.
673 """
jasonkmluc0939182021-02-19 18:34:28 +0800674 if not check_chipset_vendor_by_qualcomm(ad):
675 delete_lto_file(ad)
jasonkmluff0d5b92019-03-21 11:24:45 +0800676 ad.log.info("Launch GTW GPSTool and Clear all GNSS aiding data")
677 ad.adb.shell("am start -S -n com.android.gpstool/.GPSTool --es mode clear")
678 time.sleep(10)
679
Jayakumar Munuswamybc6038c2019-10-30 14:46:38 -0700680
Scott Honga2e430b2020-08-27 15:14:57 +0800681def start_gnss_by_gtw_gpstool(ad,
682 state,
683 type="gnss",
684 bgdisplay=False,
685 freq=0,
686 lowpower=False,
687 meas=False):
jasonkmluff0d5b92019-03-21 11:24:45 +0800688 """Start or stop GNSS on GTW_GPSTool.
689
690 Args:
691 ad: An AndroidDevice object.
692 state: True to start GNSS. False to Stop GNSS.
jasonkmlu81b8b032019-06-21 15:18:27 +0800693 type: Different API for location fix. Use gnss/flp/nmea
Scott Honga2e430b2020-08-27 15:14:57 +0800694 bgdisplay: true to run GTW when Display off. false to not run GTW when
695 Display off.
696 freq: An integer to set location update frequency.
jasonkmlu6ea2a2b2020-11-02 13:29:41 +0800697 meas: A Boolean to set GNSS measurement registration.
Scott Honga2e430b2020-08-27 15:14:57 +0800698 lowpower: A boolean to set GNSS LowPowerMode.
jasonkmluff0d5b92019-03-21 11:24:45 +0800699 """
Scott Honga2e430b2020-08-27 15:14:57 +0800700 cmd = "am start -S -n com.android.gpstool/.GPSTool --es mode gps"
jasonkmluff0d5b92019-03-21 11:24:45 +0800701 if not state:
jasonkmlu81b8b032019-06-21 15:18:27 +0800702 ad.log.info("Stop %s on GTW_GPSTool." % type)
Scott Honga2e430b2020-08-27 15:14:57 +0800703 cmd = "am broadcast -a com.android.gpstool.stop_gps_action"
704 else:
705 options = ("--es type {} --ei freq {} --ez BG {} --ez meas {} --ez "
706 "lowpower {}").format(type, freq, bgdisplay, meas, lowpower)
707 cmd = cmd + " " + options
Scott Honga2e430b2020-08-27 15:14:57 +0800708 ad.adb.shell(cmd)
jasonkmluff0d5b92019-03-21 11:24:45 +0800709 time.sleep(3)
710
Jayakumar Munuswamybc6038c2019-10-30 14:46:38 -0700711
jasonkmlu8721ced2020-10-26 14:37:46 +0800712def process_gnss_by_gtw_gpstool(ad,
713 criteria,
714 type="gnss",
715 clear_data=True,
716 meas_flag=False):
jasonkmluff0d5b92019-03-21 11:24:45 +0800717 """Launch GTW GPSTool and Clear all GNSS aiding data
718 Start GNSS tracking on GTW_GPSTool.
719
720 Args:
721 ad: An AndroidDevice object.
722 criteria: Criteria for current test item.
jasonkmlu81b8b032019-06-21 15:18:27 +0800723 type: Different API for location fix. Use gnss/flp/nmea
jasonkmlu8721ced2020-10-26 14:37:46 +0800724 clear_data: True to clear GNSS aiding data. False is not to. Default
jasonkmlu5a385f22020-06-08 17:14:15 +0800725 set to True.
jasonkmlu8721ced2020-10-26 14:37:46 +0800726 meas_flag: True to enable GnssMeasurement. False is not to. Default
727 set to False.
jasonkmluff0d5b92019-03-21 11:24:45 +0800728
729 Returns:
730 True: First fix TTFF are within criteria.
731 False: First fix TTFF exceed criteria.
732 """
733 retries = 3
734 for i in range(retries):
jasonkmlud68fdf02020-07-23 16:18:11 +0800735 if not ad.is_adb_logcat_on:
736 ad.start_adb_logcat()
737 check_adblog_functionality(ad)
jasonkmlu4ba30a02020-04-09 14:16:49 +0800738 check_location_runtime_permissions(
739 ad, GNSSTOOL_PACKAGE_NAME, GNSSTOOL_PERMISSIONS)
jasonkmluff0d5b92019-03-21 11:24:45 +0800740 begin_time = get_current_epoch_time()
jasonkmlu5a385f22020-06-08 17:14:15 +0800741 if clear_data:
742 clear_aiding_data_by_gtw_gpstool(ad)
jasonkmlu035eee12019-10-08 17:11:20 +0800743 ad.log.info("Start %s on GTW_GPSTool - attempt %d" % (type.upper(),
744 i+1))
jasonkmlu8721ced2020-10-26 14:37:46 +0800745 start_gnss_by_gtw_gpstool(ad, state=True, type=type, meas=meas_flag)
jasonkmluff0d5b92019-03-21 11:24:45 +0800746 for _ in range(10 + criteria):
747 logcat_results = ad.search_logcat("First fixed", begin_time)
748 if logcat_results:
jasonkmlu81b8b032019-06-21 15:18:27 +0800749 ad.log.debug(logcat_results[-1]["log_message"])
jasonkmluff0d5b92019-03-21 11:24:45 +0800750 first_fixed = int(logcat_results[-1]["log_message"].split()[-1])
jasonkmlu81b8b032019-06-21 15:18:27 +0800751 ad.log.info("%s First fixed = %.3f seconds" %
752 (type.upper(), first_fixed/1000))
753 if (first_fixed/1000) <= criteria:
jasonkmluff0d5b92019-03-21 11:24:45 +0800754 return True
jasonkmlu8721ced2020-10-26 14:37:46 +0800755 start_gnss_by_gtw_gpstool(ad, state=False, type=type)
jasonkmlu035eee12019-10-08 17:11:20 +0800756 raise signals.TestFailure("Fail to get %s location fixed "
757 "within %d seconds criteria."
758 % (type.upper(), criteria))
jasonkmluff0d5b92019-03-21 11:24:45 +0800759 time.sleep(1)
jasonkmlu6ea2a2b2020-11-02 13:29:41 +0800760 check_current_focus_app(ad)
jasonkmlu8721ced2020-10-26 14:37:46 +0800761 start_gnss_by_gtw_gpstool(ad, state=False, type=type)
jasonkmlu035eee12019-10-08 17:11:20 +0800762 raise signals.TestFailure("Fail to get %s location fixed within %d "
763 "attempts." % (type.upper(), retries))
jasonkmluff0d5b92019-03-21 11:24:45 +0800764
Scott Hong72269692019-12-16 16:59:56 +0800765def start_ttff_by_gtw_gpstool(ad, ttff_mode, iteration, aid_data=False):
jasonkmluff0d5b92019-03-21 11:24:45 +0800766 """Identify which TTFF mode for different test items.
767
768 Args:
769 ad: An AndroidDevice object.
770 ttff_mode: TTFF Test mode for current test item.
771 iteration: Iteration of TTFF cycles.
Scott Hong72269692019-12-16 16:59:56 +0800772 aid_data: Boolean for identify aid_data existed or not
jasonkmluff0d5b92019-03-21 11:24:45 +0800773 """
jasonkmlu97ac56e2019-05-29 15:04:51 +0800774 begin_time = get_current_epoch_time()
Scott Hong72269692019-12-16 16:59:56 +0800775 if (ttff_mode == "hs" or ttff_mode == "ws") and not aid_data:
jasonkmlu81b8b032019-06-21 15:18:27 +0800776 ad.log.info("Wait 5 minutes to start TTFF %s..." % ttff_mode.upper())
jasonkmluff0d5b92019-03-21 11:24:45 +0800777 time.sleep(300)
778 if ttff_mode == "cs":
779 ad.log.info("Start TTFF Cold Start...")
780 time.sleep(3)
jasonkmlu97ac56e2019-05-29 15:04:51 +0800781 for i in range(1, 4):
782 ad.adb.shell("am broadcast -a com.android.gpstool.ttff_action "
783 "--es ttff %s --es cycle %d" % (ttff_mode, iteration))
jasonkmlu81b8b032019-06-21 15:18:27 +0800784 time.sleep(1)
jasonkmlu97ac56e2019-05-29 15:04:51 +0800785 if ad.search_logcat("act=com.android.gpstool.start_test_action",
786 begin_time):
787 ad.log.info("Send TTFF start_test_action successfully.")
788 break
jasonkmlu035eee12019-10-08 17:11:20 +0800789 else:
jasonkmlu6ea2a2b2020-11-02 13:29:41 +0800790 check_current_focus_app(ad)
jasonkmlu78540632019-11-15 18:04:20 +0800791 raise signals.TestError("Fail to send TTFF start_test_action.")
jasonkmluff0d5b92019-03-21 11:24:45 +0800792
jasonkmlu0f546de2019-12-13 20:58:41 +0800793
jasonkmlu8721ced2020-10-26 14:37:46 +0800794def gnss_tracking_via_gtw_gpstool(ad,
795 criteria,
796 type="gnss",
797 testtime=60,
798 meas_flag=False):
jasonkmlu66fda532019-07-16 11:12:45 +0800799 """Start GNSS/FLP tracking tests for input testtime on GTW_GPSTool.
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800800
801 Args:
802 ad: An AndroidDevice object.
803 criteria: Criteria for current TTFF.
804 type: Different API for location fix. Use gnss/flp/nmea
805 testtime: Tracking test time for minutes. Default set to 60 minutes.
jasonkmlu8721ced2020-10-26 14:37:46 +0800806 meas_flag: True to enable GnssMeasurement. False is not to. Default
807 set to False.
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800808 """
jasonkmlu3fcdc2b2021-03-22 19:35:48 +0800809 gnss_crash_list = [".*Fatal signal.*gnss",
810 ".*Fatal signal.*xtra",
811 ".*F DEBUG.*gnss"]
jasonkmlu8721ced2020-10-26 14:37:46 +0800812 process_gnss_by_gtw_gpstool(
813 ad, criteria=criteria, type=type, meas_flag=meas_flag)
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800814 ad.log.info("Start %s tracking test for %d minutes" % (type.upper(),
815 testtime))
816 begin_time = get_current_epoch_time()
jasonkmlu6ea2a2b2020-11-02 13:29:41 +0800817 while get_current_epoch_time() - begin_time < testtime * 60 * 1000:
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800818 if not ad.is_adb_logcat_on:
819 ad.start_adb_logcat()
jasonkmlu3fcdc2b2021-03-22 19:35:48 +0800820 for attr in gnss_crash_list:
821 gnss_crash_result = ad.adb.shell(
822 "logcat -d | grep -E -i '%s'" % attr)
823 if gnss_crash_result:
824 start_gnss_by_gtw_gpstool(ad, state=False, type=type)
825 raise signals.TestFailure(
826 "Test failed due to GNSS HAL crashed. \n%s" %
827 gnss_crash_result)
828 gpstool_crash_result = ad.search_logcat("Force finishing activity "
829 "com.android.gpstool/.GPSTool",
830 begin_time)
831 if gpstool_crash_result:
jasonkmlu78540632019-11-15 18:04:20 +0800832 raise signals.TestError("GPSTool crashed. Abort test.")
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800833 ad.log.info("Successfully tested for %d minutes" % testtime)
jasonkmlu8721ced2020-10-26 14:37:46 +0800834 start_gnss_by_gtw_gpstool(ad, state=False, type=type)
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800835
jasonkmlu0f546de2019-12-13 20:58:41 +0800836
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800837def parse_gtw_gpstool_log(ad, true_position, type="gnss"):
838 """Process GNSS/FLP API logs from GTW GPSTool and output track_data to
839 test_run_info for ACTS plugin to parse and display on MobileHarness as
840 Property.
841
842 Args:
843 ad: An AndroidDevice object.
844 true_position: Coordinate as [latitude, longitude] to calculate
845 position error.
846 type: Different API for location fix. Use gnss/flp/nmea
847 """
848 test_logfile = {}
849 track_data = {}
jasonkmlucb654ac2020-07-01 11:08:33 +0800850 ant_top4_cn = 0
851 ant_cn = 0
852 base_top4_cn = 0
853 base_cn = 0
jasonkmlu6ea2a2b2020-11-02 13:29:41 +0800854 track_lat = 0
855 track_long = 0
jasonkmlu035eee12019-10-08 17:11:20 +0800856 l5flag = "false"
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800857 file_count = int(ad.adb.shell("find %s -type f -iname *.txt | wc -l"
858 % GNSSSTATUS_LOG_PATH))
859 if file_count != 1:
860 ad.log.error("%d API logs exist." % file_count)
jasonkmlu6ea2a2b2020-11-02 13:29:41 +0800861 dir_file = ad.adb.shell("ls %s" % GNSSSTATUS_LOG_PATH).split()
862 for path_key in dir_file:
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800863 if fnmatch.fnmatch(path_key, "*.txt"):
864 logpath = posixpath.join(GNSSSTATUS_LOG_PATH, path_key)
865 out = ad.adb.shell("wc -c %s" % logpath)
866 file_size = int(out.split(" ")[0])
867 if file_size < 2000:
868 ad.log.info("Skip log %s due to log size %d bytes" %
869 (path_key, file_size))
870 continue
871 test_logfile = logpath
872 if not test_logfile:
jasonkmlu78540632019-11-15 18:04:20 +0800873 raise signals.TestError("Failed to get test log file in device.")
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800874 lines = ad.adb.shell("cat %s" % test_logfile).split("\n")
875 for line in lines:
jasonkmlucb654ac2020-07-01 11:08:33 +0800876 if "Antenna_History Avg Top4" in line:
877 ant_top4_cn = float(line.split(":")[-1].strip())
878 elif "Antenna_History Avg" in line:
879 ant_cn = float(line.split(":")[-1].strip())
880 elif "Baseband_History Avg Top4" in line:
881 base_top4_cn = float(line.split(":")[-1].strip())
882 elif "Baseband_History Avg" in line:
883 base_cn = float(line.split(":")[-1].strip())
884 elif "L5 used in fix" in line:
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800885 l5flag = line.split(":")[-1].strip()
jasonkmlucb654ac2020-07-01 11:08:33 +0800886 elif "Latitude" in line:
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800887 track_lat = float(line.split(":")[-1].strip())
jasonkmlucb654ac2020-07-01 11:08:33 +0800888 elif "Longitude" in line:
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800889 track_long = float(line.split(":")[-1].strip())
jasonkmlucb654ac2020-07-01 11:08:33 +0800890 elif "Time" in line:
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800891 track_utc = line.split("Time:")[-1].strip()
892 if track_utc in track_data.keys():
893 continue
jasonkmlu6ea2a2b2020-11-02 13:29:41 +0800894 pe = calculate_position_error(track_lat, track_long, true_position)
jasonkmlucb654ac2020-07-01 11:08:33 +0800895 track_data[track_utc] = TRACK_REPORT(l5flag=l5flag,
896 pe=pe,
897 ant_top4cn=ant_top4_cn,
898 ant_cn=ant_cn,
899 base_top4cn=base_top4_cn,
900 base_cn=base_cn)
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800901 ad.log.debug(track_data)
902 prop_basename = "TestResult %s_tracking_" % type.upper()
903 time_list = sorted(track_data.keys())
jasonkmlucb654ac2020-07-01 11:08:33 +0800904 l5flag_list = [track_data[key].l5flag for key in time_list]
905 pe_list = [float(track_data[key].pe) for key in time_list]
906 ant_top4cn_list = [float(track_data[key].ant_top4cn) for key in time_list]
907 ant_cn_list = [float(track_data[key].ant_cn) for key in time_list]
908 base_top4cn_list = [float(track_data[key].base_top4cn) for key in time_list]
909 base_cn_list = [float(track_data[key].base_cn) for key in time_list]
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800910 ad.log.info(prop_basename+"StartTime %s" % time_list[0].replace(" ", "-"))
911 ad.log.info(prop_basename+"EndTime %s" % time_list[-1].replace(" ", "-"))
912 ad.log.info(prop_basename+"TotalFixPoints %d" % len(time_list))
913 ad.log.info(prop_basename+"L5FixRate "+'{percent:.2%}'.format(
914 percent=l5flag_list.count("true")/len(l5flag_list)))
915 ad.log.info(prop_basename+"AvgDis %.1f" % (sum(pe_list)/len(pe_list)))
916 ad.log.info(prop_basename+"MaxDis %.1f" % max(pe_list))
jasonkmlucb654ac2020-07-01 11:08:33 +0800917 ad.log.info(prop_basename+"Ant_AvgTop4Signal %.1f" % ant_top4cn_list[-1])
918 ad.log.info(prop_basename+"Ant_AvgSignal %.1f" % ant_cn_list[-1])
919 ad.log.info(prop_basename+"Base_AvgTop4Signal %.1f" % base_top4cn_list[-1])
920 ad.log.info(prop_basename+"Base_AvgSignal %.1f" % base_cn_list[-1])
jasonkmlu4fcdcad2019-07-10 14:35:12 +0800921
jasonkmlu0f546de2019-12-13 20:58:41 +0800922
jasonkmlu81b8b032019-06-21 15:18:27 +0800923def process_ttff_by_gtw_gpstool(ad, begin_time, true_position, type="gnss"):
924 """Process TTFF and record results in ttff_data.
jasonkmluff0d5b92019-03-21 11:24:45 +0800925
926 Args:
927 ad: An AndroidDevice object.
jasonkmlu903ece82019-05-16 14:56:19 +0800928 begin_time: test begin time.
jasonkmlu733738f2019-09-02 18:59:42 +0800929 true_position: Coordinate as [latitude, longitude] to calculate
930 position error.
jasonkmlu81b8b032019-06-21 15:18:27 +0800931 type: Different API for location fix. Use gnss/flp/nmea
jasonkmluff0d5b92019-03-21 11:24:45 +0800932
933 Returns:
jasonkmlu81b8b032019-06-21 15:18:27 +0800934 ttff_data: A dict of all TTFF data.
jasonkmluff0d5b92019-03-21 11:24:45 +0800935 """
jasonkmlu6ea2a2b2020-11-02 13:29:41 +0800936 ttff_lat = 0
937 ttff_lon = 0
938 utc_time = epoch_to_human_time(get_current_epoch_time())
jasonkmlu903ece82019-05-16 14:56:19 +0800939 ttff_data = {}
jasonkmlu733738f2019-09-02 18:59:42 +0800940 ttff_loop_time = get_current_epoch_time()
jasonkmlu97ac56e2019-05-29 15:04:51 +0800941 while True:
jasonkmlu733738f2019-09-02 18:59:42 +0800942 if get_current_epoch_time() - ttff_loop_time >= 120000:
jasonkmlu78540632019-11-15 18:04:20 +0800943 raise signals.TestError("Fail to search specific GPSService "
944 "message in logcat. Abort test.")
jasonkmlu97ac56e2019-05-29 15:04:51 +0800945 if not ad.is_adb_logcat_on:
946 ad.start_adb_logcat()
jasonkmlu61b686f2020-07-20 20:07:04 +0800947 logcat_results = ad.search_logcat("write TTFF log", ttff_loop_time)
jasonkmlu97ac56e2019-05-29 15:04:51 +0800948 if logcat_results:
jasonkmlu61b686f2020-07-20 20:07:04 +0800949 ttff_loop_time = get_current_epoch_time()
jasonkmlu97ac56e2019-05-29 15:04:51 +0800950 ttff_log = logcat_results[-1]["log_message"].split()
951 ttff_loop = int(ttff_log[8].split(":")[-1])
jasonkmlu81b8b032019-06-21 15:18:27 +0800952 ttff_sec = float(ttff_log[11])
953 if ttff_sec != 0.0:
jasonkmlucb654ac2020-07-01 11:08:33 +0800954 ttff_ant_cn = float(ttff_log[18].strip("]"))
955 ttff_base_cn = float(ttff_log[25].strip("]"))
jasonkmlu81b8b032019-06-21 15:18:27 +0800956 if type == "gnss":
jasonkmlu733738f2019-09-02 18:59:42 +0800957 gnss_results = ad.search_logcat("GPSService: Check item",
958 begin_time)
jasonkmlu81b8b032019-06-21 15:18:27 +0800959 if gnss_results:
960 ad.log.debug(gnss_results[-1]["log_message"])
jasonkmlu733738f2019-09-02 18:59:42 +0800961 gnss_location_log = \
962 gnss_results[-1]["log_message"].split()
963 ttff_lat = float(
964 gnss_location_log[8].split("=")[-1].strip(","))
965 ttff_lon = float(
966 gnss_location_log[9].split("=")[-1].strip(","))
jasonkmlucb654ac2020-07-01 11:08:33 +0800967 loc_time = int(
968 gnss_location_log[10].split("=")[-1].strip(","))
969 utc_time = epoch_to_human_time(loc_time)
jasonkmlu81b8b032019-06-21 15:18:27 +0800970 elif type == "flp":
jasonkmlu733738f2019-09-02 18:59:42 +0800971 flp_results = ad.search_logcat("GPSService: FLP Location",
972 begin_time)
jasonkmlu81b8b032019-06-21 15:18:27 +0800973 if flp_results:
974 ad.log.debug(flp_results[-1]["log_message"])
jasonkmlucb654ac2020-07-01 11:08:33 +0800975 flp_location_log = flp_results[-1][
976 "log_message"].split()
jasonkmlu81b8b032019-06-21 15:18:27 +0800977 ttff_lat = float(flp_location_log[8].split(",")[0])
978 ttff_lon = float(flp_location_log[8].split(",")[1])
jasonkmlucb654ac2020-07-01 11:08:33 +0800979 utc_time = epoch_to_human_time(get_current_epoch_time())
jasonkmlu81b8b032019-06-21 15:18:27 +0800980 else:
jasonkmlucb654ac2020-07-01 11:08:33 +0800981 ttff_ant_cn = float(ttff_log[19].strip("]"))
982 ttff_base_cn = float(ttff_log[26].strip("]"))
983 ttff_lat = 0
984 ttff_lon = 0
985 utc_time = epoch_to_human_time(get_current_epoch_time())
jasonkmlu2565d892019-11-12 15:31:26 +0800986 ad.log.debug("TTFF Loop %d - (Lat, Lon) = (%s, %s)" % (ttff_loop,
987 ttff_lat,
988 ttff_lon))
jasonkmlu6ea2a2b2020-11-02 13:29:41 +0800989 ttff_pe = calculate_position_error(
990 ttff_lat, ttff_lon, true_position)
jasonkmlucb654ac2020-07-01 11:08:33 +0800991 ttff_data[ttff_loop] = TTFF_REPORT(utc_time=utc_time,
992 ttff_loop=ttff_loop,
jasonkmlu97ac56e2019-05-29 15:04:51 +0800993 ttff_sec=ttff_sec,
994 ttff_pe=ttff_pe,
jasonkmlucb654ac2020-07-01 11:08:33 +0800995 ttff_ant_cn=ttff_ant_cn,
996 ttff_base_cn=ttff_base_cn)
997 ad.log.info("UTC Time = %s, Loop %d = %.1f seconds, "
jasonkmlu97ac56e2019-05-29 15:04:51 +0800998 "Position Error = %.1f meters, "
jasonkmlucb654ac2020-07-01 11:08:33 +0800999 "Antenna Average Signal = %.1f dbHz, "
1000 "Baseband Average Signal = %.1f dbHz" % (utc_time,
1001 ttff_loop,
1002 ttff_sec,
1003 ttff_pe,
1004 ttff_ant_cn,
1005 ttff_base_cn))
1006 stop_gps_results = ad.search_logcat("stop gps test", begin_time)
1007 if stop_gps_results:
1008 ad.send_keycode("HOME")
1009 break
1010 crash_result = ad.search_logcat("Force finishing activity "
1011 "com.android.gpstool/.GPSTool",
1012 begin_time)
1013 if crash_result:
1014 raise signals.TestError("GPSTool crashed. Abort test.")
jasonkmlu9b278f92021-04-20 01:06:50 +08001015 # wait 5 seconds to avoid logs not writing into logcat yet
1016 time.sleep(5)
jasonkmlu97ac56e2019-05-29 15:04:51 +08001017 return ttff_data
jasonkmluff0d5b92019-03-21 11:24:45 +08001018
jasonkmlu0f546de2019-12-13 20:58:41 +08001019
jasonkmlu903ece82019-05-16 14:56:19 +08001020def check_ttff_data(ad, ttff_data, ttff_mode, criteria):
jasonkmlu81b8b032019-06-21 15:18:27 +08001021 """Verify all TTFF results from ttff_data.
jasonkmluff0d5b92019-03-21 11:24:45 +08001022
1023 Args:
1024 ad: An AndroidDevice object.
jasonkmlu903ece82019-05-16 14:56:19 +08001025 ttff_data: TTFF data of secs, position error and signal strength.
jasonkmluff0d5b92019-03-21 11:24:45 +08001026 ttff_mode: TTFF Test mode for current test item.
1027 criteria: Criteria for current test item.
1028
1029 Returns:
1030 True: All TTFF results are within criteria.
1031 False: One or more TTFF results exceed criteria or Timeout.
1032 """
1033 ad.log.info("%d iterations of TTFF %s tests finished."
jasonkmlu903ece82019-05-16 14:56:19 +08001034 % (len(ttff_data.keys()), ttff_mode))
jasonkmluff0d5b92019-03-21 11:24:45 +08001035 ad.log.info("%s PASS criteria is %d seconds" % (ttff_mode, criteria))
jasonkmlu81b8b032019-06-21 15:18:27 +08001036 ad.log.debug("%s TTFF data: %s" % (ttff_mode, ttff_data))
jasonkmlu4fcdcad2019-07-10 14:35:12 +08001037 ttff_property_key_and_value(ad, ttff_data, ttff_mode)
jasonkmlu903ece82019-05-16 14:56:19 +08001038 if len(ttff_data.keys()) == 0:
jasonkmluff0d5b92019-03-21 11:24:45 +08001039 ad.log.error("GTW_GPSTool didn't process TTFF properly.")
1040 return False
jasonkmlu903ece82019-05-16 14:56:19 +08001041 elif any(float(ttff_data[key].ttff_sec) == 0.0 for key in ttff_data.keys()):
jasonkmluff0d5b92019-03-21 11:24:45 +08001042 ad.log.error("One or more TTFF %s Timeout" % ttff_mode)
1043 return False
jasonkmlu035eee12019-10-08 17:11:20 +08001044 elif any(float(ttff_data[key].ttff_sec) >= criteria for key in
1045 ttff_data.keys()):
jasonkmluff0d5b92019-03-21 11:24:45 +08001046 ad.log.error("One or more TTFF %s are over test criteria %d seconds"
1047 % (ttff_mode, criteria))
1048 return False
1049 ad.log.info("All TTFF %s are within test criteria %d seconds."
1050 % (ttff_mode, criteria))
1051 return True
1052
jasonkmlu0f546de2019-12-13 20:58:41 +08001053
jasonkmlu4fcdcad2019-07-10 14:35:12 +08001054def ttff_property_key_and_value(ad, ttff_data, ttff_mode):
jasonkmlu81b8b032019-06-21 15:18:27 +08001055 """Output ttff_data to test_run_info for ACTS plugin to parse and display
1056 on MobileHarness as Property.
1057
1058 Args:
1059 ad: An AndroidDevice object.
1060 ttff_data: TTFF data of secs, position error and signal strength.
1061 ttff_mode: TTFF Test mode for current test item.
1062 """
1063 prop_basename = "TestResult "+ttff_mode.replace(" ", "_")+"_TTFF_"
1064 sec_list = [float(ttff_data[key].ttff_sec) for key in ttff_data.keys()]
1065 pe_list = [float(ttff_data[key].ttff_pe) for key in ttff_data.keys()]
jasonkmlucb654ac2020-07-01 11:08:33 +08001066 ant_cn_list = [float(ttff_data[key].ttff_ant_cn) for key in
1067 ttff_data.keys()]
1068 base_cn_list = [float(ttff_data[key].ttff_base_cn) for key in
jasonkmlu6ea2a2b2020-11-02 13:29:41 +08001069 ttff_data.keys()]
jasonkmlu81b8b032019-06-21 15:18:27 +08001070 timeoutcount = sec_list.count(0.0)
jasonkmluc1ec3052019-10-25 14:57:53 +08001071 if len(sec_list) == timeoutcount:
1072 avgttff = 9527
1073 else:
1074 avgttff = sum(sec_list)/(len(sec_list) - timeoutcount)
jasonkmlu81b8b032019-06-21 15:18:27 +08001075 if timeoutcount != 0:
jasonkmlu4fcdcad2019-07-10 14:35:12 +08001076 maxttff = 9527
jasonkmlu81b8b032019-06-21 15:18:27 +08001077 else:
1078 maxttff = max(sec_list)
1079 avgdis = sum(pe_list)/len(pe_list)
1080 maxdis = max(pe_list)
jasonkmlucb654ac2020-07-01 11:08:33 +08001081 ant_avgcn = sum(ant_cn_list)/len(ant_cn_list)
1082 base_avgcn = sum(base_cn_list)/len(base_cn_list)
jasonkmlu81b8b032019-06-21 15:18:27 +08001083 ad.log.info(prop_basename+"AvgTime %.1f" % avgttff)
1084 ad.log.info(prop_basename+"MaxTime %.1f" % maxttff)
1085 ad.log.info(prop_basename+"TimeoutCount %d" % timeoutcount)
1086 ad.log.info(prop_basename+"AvgDis %.1f" % avgdis)
1087 ad.log.info(prop_basename+"MaxDis %.1f" % maxdis)
jasonkmlucb654ac2020-07-01 11:08:33 +08001088 ad.log.info(prop_basename+"Ant_AvgSignal %.1f" % ant_avgcn)
1089 ad.log.info(prop_basename+"Base_AvgSignal %.1f" % base_avgcn)
jasonkmlu81b8b032019-06-21 15:18:27 +08001090
jasonkmlu0f546de2019-12-13 20:58:41 +08001091
jasonkmlu6ea2a2b2020-11-02 13:29:41 +08001092def calculate_position_error(latitude, longitude, true_position):
jasonkmlu903ece82019-05-16 14:56:19 +08001093 """Use haversine formula to calculate position error base on true location
1094 coordinate.
1095
1096 Args:
jasonkmlu903ece82019-05-16 14:56:19 +08001097 latitude: latitude of location fixed in the present.
1098 longitude: longitude of location fixed in the present.
1099 true_position: [latitude, longitude] of true location coordinate.
1100
1101 Returns:
1102 position_error of location fixed in the present.
1103 """
1104 radius = 6371009
1105 dlat = math.radians(latitude - true_position[0])
1106 dlon = math.radians(longitude - true_position[1])
1107 a = math.sin(dlat/2) * math.sin(dlat/2) + \
1108 math.cos(math.radians(true_position[0])) * \
1109 math.cos(math.radians(latitude)) * math.sin(dlon/2) * math.sin(dlon/2)
1110 c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
1111 return radius * c
1112
jasonkmlu0f546de2019-12-13 20:58:41 +08001113
jasonkmluff0d5b92019-03-21 11:24:45 +08001114def launch_google_map(ad):
1115 """Launch Google Map via intent.
1116
1117 Args:
1118 ad: An AndroidDevice object.
1119 """
1120 ad.log.info("Launch Google Map.")
1121 try:
1122 ad.adb.shell("am start -S -n com.google.android.apps.maps/"
1123 "com.google.android.maps.MapsActivity")
1124 ad.send_keycode("BACK")
1125 ad.force_stop_apk("com.google.android.apps.maps")
1126 ad.adb.shell("am start -S -n com.google.android.apps.maps/"
1127 "com.google.android.maps.MapsActivity")
1128 except Exception as e:
1129 ad.log.error(e)
jasonkmlu78540632019-11-15 18:04:20 +08001130 raise signals.TestError("Failed to launch google map.")
jasonkmlu6ea2a2b2020-11-02 13:29:41 +08001131 check_current_focus_app(ad)
jasonkmlu49c32812019-04-12 18:11:10 +08001132
jasonkmlu0f546de2019-12-13 20:58:41 +08001133
jasonkmlu6ea2a2b2020-11-02 13:29:41 +08001134def check_current_focus_app(ad):
jasonkmlu903ece82019-05-16 14:56:19 +08001135 """Check to see current focused window and app.
jasonkmlu49c32812019-04-12 18:11:10 +08001136
1137 Args:
1138 ad: An AndroidDevice object.
jasonkmlu49c32812019-04-12 18:11:10 +08001139 """
jasonkmlu903ece82019-05-16 14:56:19 +08001140 time.sleep(1)
jasonkmlu035eee12019-10-08 17:11:20 +08001141 current = ad.adb.shell(
1142 "dumpsys window | grep -E 'mCurrentFocus|mFocusedApp'")
jasonkmlu81b8b032019-06-21 15:18:27 +08001143 ad.log.debug("\n"+current)
jasonkmluff0d5b92019-03-21 11:24:45 +08001144
jasonkmlu0f546de2019-12-13 20:58:41 +08001145
jasonkmluff0d5b92019-03-21 11:24:45 +08001146def check_location_api(ad, retries):
1147 """Verify if GnssLocationProvider API reports location.
1148
1149 Args:
1150 ad: An AndroidDevice object.
1151 retries: Retry time.
1152
1153 Returns:
1154 True: GnssLocationProvider API reports location.
1155 otherwise return False.
1156 """
1157 for i in range(retries):
1158 begin_time = get_current_epoch_time()
1159 ad.log.info("Try to get location report from GnssLocationProvider API "
1160 "- attempt %d" % (i+1))
1161 while get_current_epoch_time() - begin_time <= 30000:
1162 logcat_results = ad.search_logcat("REPORT_LOCATION", begin_time)
1163 if logcat_results:
1164 ad.log.info("%s" % logcat_results[-1]["log_message"])
jasonkmlu035eee12019-10-08 17:11:20 +08001165 ad.log.info("GnssLocationProvider reports location "
1166 "successfully.")
jasonkmluff0d5b92019-03-21 11:24:45 +08001167 return True
1168 if not ad.is_adb_logcat_on:
1169 ad.start_adb_logcat()
1170 ad.log.error("GnssLocationProvider is unable to report location.")
1171 return False
1172
Scott Hong72269692019-12-16 16:59:56 +08001173def check_network_location(ad, retries, location_type, criteria=30):
jasonkmluff0d5b92019-03-21 11:24:45 +08001174 """Verify if NLP reports location after requesting via GPSTool.
1175
1176 Args:
1177 ad: An AndroidDevice object.
1178 retries: Retry time.
Scott Hongaccd8a12020-03-03 20:12:17 +08001179 location_type: cell or wifi.
Scott Hong72269692019-12-16 16:59:56 +08001180 criteria: expected nlp return time, default 30 seconds
jasonkmluff0d5b92019-03-21 11:24:45 +08001181
1182 Returns:
1183 True: NLP reports location.
1184 otherwise return False.
1185 """
Scott Hong72269692019-12-16 16:59:56 +08001186 criteria = criteria * 1000
Scott Hongaccd8a12020-03-03 20:12:17 +08001187 search_pattern = ("GPSTool : networkLocationType = %s" % location_type)
jasonkmluff0d5b92019-03-21 11:24:45 +08001188 for i in range(retries):
jasonkmluff0d5b92019-03-21 11:24:45 +08001189 begin_time = get_current_epoch_time()
1190 ad.log.info("Try to get NLP status - attempt %d" % (i+1))
jasonkmlu035eee12019-10-08 17:11:20 +08001191 ad.adb.shell(
1192 "am start -S -n com.android.gpstool/.GPSTool --es mode nlp")
Scott Hong72269692019-12-16 16:59:56 +08001193 while get_current_epoch_time() - begin_time <= criteria:
Scott Hongaccd8a12020-03-03 20:12:17 +08001194 # Search pattern in 1 second interval
1195 time.sleep(1)
1196 result = ad.search_logcat(search_pattern, begin_time)
1197 if result:
1198 ad.log.info("Pattern Found: %s." % result[-1]["log_message"])
1199 ad.send_keycode("BACK")
1200 return True
jasonkmluff0d5b92019-03-21 11:24:45 +08001201 if not ad.is_adb_logcat_on:
1202 ad.start_adb_logcat()
1203 ad.send_keycode("BACK")
1204 ad.log.error("Unable to report network location \"%s\"." % location_type)
1205 return False
1206
jasonkmlu0f546de2019-12-13 20:58:41 +08001207
jasonkmlu8d6bbfc2019-03-29 15:57:43 +08001208def set_attenuator_gnss_signal(ad, attenuator, atten_value):
jasonkmluff0d5b92019-03-21 11:24:45 +08001209 """Set attenuation value for different GNSS signal.
1210
1211 Args:
1212 ad: An AndroidDevice object.
jasonkmlu8d6bbfc2019-03-29 15:57:43 +08001213 attenuator: The attenuator object.
jasonkmluff0d5b92019-03-21 11:24:45 +08001214 atten_value: attenuation value
1215 """
jasonkmluff0d5b92019-03-21 11:24:45 +08001216 try:
jasonkmlu035eee12019-10-08 17:11:20 +08001217 ad.log.info(
1218 "Set attenuation value to \"%d\" for GNSS signal." % atten_value)
jasonkmlu8d6bbfc2019-03-29 15:57:43 +08001219 attenuator[0].set_atten(atten_value)
jasonkmlu81b8b032019-06-21 15:18:27 +08001220 except Exception as e:
jasonkmlu4fcdcad2019-07-10 14:35:12 +08001221 ad.log.error(e)
jasonkmluff0d5b92019-03-21 11:24:45 +08001222
jasonkmlu0f546de2019-12-13 20:58:41 +08001223
jasonkmluff0d5b92019-03-21 11:24:45 +08001224def set_battery_saver_mode(ad, state):
jasonkmlu6ea2a2b2020-11-02 13:29:41 +08001225 """Enable or disable battery saver mode via adb.
jasonkmluff0d5b92019-03-21 11:24:45 +08001226
1227 Args:
1228 ad: An AndroidDevice object.
1229 state: True is enable Battery Saver mode. False is disable.
1230 """
1231 ad.root_adb()
1232 if state:
1233 ad.log.info("Enable Battery Saver mode.")
1234 ad.adb.shell("cmd battery unplug")
1235 ad.adb.shell("settings put global low_power 1")
1236 else:
1237 ad.log.info("Disable Battery Saver mode.")
1238 ad.adb.shell("settings put global low_power 0")
1239 ad.adb.shell("cmd battery reset")
1240
jasonkmlu0f546de2019-12-13 20:58:41 +08001241
jasonkmluff0d5b92019-03-21 11:24:45 +08001242def set_gnss_qxdm_mask(ad, masks):
1243 """Find defined gnss qxdm mask and set as default logging mask.
1244
1245 Args:
1246 ad: An AndroidDevice object.
1247 masks: Defined gnss qxdm mask.
1248 """
1249 try:
1250 for mask in masks:
Markus Liue26ef8a2021-10-19 15:20:35 +08001251 if not tlutils.find_qxdm_log_mask(ad, mask):
jasonkmluff0d5b92019-03-21 11:24:45 +08001252 continue
Markus Liue26ef8a2021-10-19 15:20:35 +08001253 tlutils.set_qxdm_logger_command(ad, mask)
jasonkmluff0d5b92019-03-21 11:24:45 +08001254 break
1255 except Exception as e:
1256 ad.log.error(e)
jasonkmlu78540632019-11-15 18:04:20 +08001257 raise signals.TestError("Failed to set any QXDM masks.")
jasonkmlu903ece82019-05-16 14:56:19 +08001258
jasonkmlu0f546de2019-12-13 20:58:41 +08001259
jasonkmlu903ece82019-05-16 14:56:19 +08001260def start_youtube_video(ad, url=None, retries=0):
1261 """Start youtube video and verify if audio is in music state.
jasonkmlu81b8b032019-06-21 15:18:27 +08001262
jasonkmlu903ece82019-05-16 14:56:19 +08001263 Args:
1264 ad: An AndroidDevice object.
1265 url: Youtube video url.
1266 retries: Retry times if audio is not in music state.
jasonkmlu81b8b032019-06-21 15:18:27 +08001267
jasonkmlu903ece82019-05-16 14:56:19 +08001268 Returns:
1269 True if youtube video is playing normally.
1270 False if youtube video is not playing properly.
1271 """
1272 for i in range(retries):
1273 ad.log.info("Open an youtube video - attempt %d" % (i+1))
jasonkmluc0939182021-02-19 18:34:28 +08001274 cmd = ("am start -n com.google.android.youtube/"
1275 "com.google.android.youtube.UrlActivity -d \"%s\"" % url)
1276 ad.adb.shell(cmd)
jasonkmlu903ece82019-05-16 14:56:19 +08001277 time.sleep(2)
jasonkmlu035eee12019-10-08 17:11:20 +08001278 out = ad.adb.shell(
1279 "dumpsys activity | grep NewVersionAvailableActivity")
jasonkmlu903ece82019-05-16 14:56:19 +08001280 if out:
1281 ad.log.info("Skip Youtube New Version Update.")
1282 ad.send_keycode("BACK")
1283 if tutils.wait_for_state(ad.droid.audioIsMusicActive, True, 15, 1):
1284 ad.log.info("Started a video in youtube, audio is in MUSIC state")
1285 return True
1286 ad.log.info("Force-Stop youtube and reopen youtube again.")
1287 ad.force_stop_apk("com.google.android.youtube")
jasonkmlu6ea2a2b2020-11-02 13:29:41 +08001288 check_current_focus_app(ad)
jasonkmlu78540632019-11-15 18:04:20 +08001289 raise signals.TestError("Started a video in youtube, "
1290 "but audio is not in MUSIC state")
jasonkmlu81b8b032019-06-21 15:18:27 +08001291
jasonkmlu0f546de2019-12-13 20:58:41 +08001292
jasonkmlu81b8b032019-06-21 15:18:27 +08001293def get_baseband_and_gms_version(ad, extra_msg=""):
1294 """Get current radio baseband and GMSCore version of AndroidDevice object.
1295
1296 Args:
1297 ad: An AndroidDevice object.
jasonkmlu6ea2a2b2020-11-02 13:29:41 +08001298 extra_msg: Extra message before or after the change.
jasonkmlu81b8b032019-06-21 15:18:27 +08001299 """
1300 try:
jasonkmlud93060f2019-11-05 15:12:55 +08001301 build_version = ad.adb.getprop("ro.build.id")
jasonkmlu81b8b032019-06-21 15:18:27 +08001302 baseband_version = ad.adb.getprop("gsm.version.baseband")
jasonkmlu035eee12019-10-08 17:11:20 +08001303 gms_version = ad.adb.shell(
1304 "dumpsys package com.google.android.gms | grep versionName"
1305 ).split("\n")[0].split("=")[1]
1306 mpss_version = ad.adb.shell("cat /sys/devices/soc0/images | grep MPSS "
1307 "| cut -d ':' -f 3")
jasonkmlu81b8b032019-06-21 15:18:27 +08001308 if not extra_msg:
jasonkmlud93060f2019-11-05 15:12:55 +08001309 ad.log.info("TestResult Build_Version %s" % build_version)
jasonkmlu81b8b032019-06-21 15:18:27 +08001310 ad.log.info("TestResult Baseband_Version %s" % baseband_version)
jasonkmlu035eee12019-10-08 17:11:20 +08001311 ad.log.info(
1312 "TestResult GMS_Version %s" % gms_version.replace(" ", ""))
1313 ad.log.info("TestResult MPSS_Version %s" % mpss_version)
jasonkmlu81b8b032019-06-21 15:18:27 +08001314 else:
jasonkmlu035eee12019-10-08 17:11:20 +08001315 ad.log.info(
1316 "%s, Baseband_Version = %s" % (extra_msg, baseband_version))
jasonkmlu81b8b032019-06-21 15:18:27 +08001317 except Exception as e:
jasonkmlu035eee12019-10-08 17:11:20 +08001318 ad.log.error(e)
1319
jasonkmlu0f546de2019-12-13 20:58:41 +08001320
jasonkmlu035eee12019-10-08 17:11:20 +08001321def start_toggle_gnss_by_gtw_gpstool(ad, iteration):
1322 """Send toggle gnss off/on start_test_action
1323
1324 Args:
1325 ad: An AndroidDevice object.
1326 iteration: Iteration of toggle gnss off/on cycles.
1327 """
1328 msg_list = []
1329 begin_time = get_current_epoch_time()
1330 try:
1331 for i in range(1, 4):
1332 ad.adb.shell("am start -S -n com.android.gpstool/.GPSTool "
1333 "--es mode toggle --es cycle %d" % iteration)
1334 time.sleep(1)
1335 if ad.search_logcat("cmp=com.android.gpstool/.ToggleGPS",
1336 begin_time):
1337 ad.log.info("Send ToggleGPS start_test_action successfully.")
1338 break
1339 else:
jasonkmlu6ea2a2b2020-11-02 13:29:41 +08001340 check_current_focus_app(ad)
jasonkmlu78540632019-11-15 18:04:20 +08001341 raise signals.TestError("Fail to send ToggleGPS "
1342 "start_test_action within 3 attempts.")
jasonkmlu035eee12019-10-08 17:11:20 +08001343 time.sleep(2)
1344 test_start = ad.search_logcat("GPSTool_ToggleGPS: startService",
1345 begin_time)
1346 if test_start:
1347 ad.log.info(test_start[-1]["log_message"].split(":")[-1].strip())
1348 else:
jasonkmlu78540632019-11-15 18:04:20 +08001349 raise signals.TestError("Fail to start toggle GPS off/on test.")
jasonkmlu035eee12019-10-08 17:11:20 +08001350 # Every iteration is expected to finish within 4 minutes.
1351 while get_current_epoch_time() - begin_time <= iteration * 240000:
1352 crash_end = ad.search_logcat("Force finishing activity "
1353 "com.android.gpstool/.GPSTool",
1354 begin_time)
1355 if crash_end:
jasonkmlu78540632019-11-15 18:04:20 +08001356 raise signals.TestError("GPSTool crashed. Abort test.")
jasonkmlu035eee12019-10-08 17:11:20 +08001357 toggle_results = ad.search_logcat("GPSTool : msg", begin_time)
1358 if toggle_results:
1359 for toggle_result in toggle_results:
1360 msg = toggle_result["log_message"]
1361 if not msg in msg_list:
1362 ad.log.info(msg.split(":")[-1].strip())
1363 msg_list.append(msg)
1364 if "timeout" in msg:
1365 raise signals.TestFailure("Fail to get location fixed "
1366 "within 60 seconds.")
1367 if "Test end" in msg:
1368 raise signals.TestPass("Completed quick toggle GNSS "
1369 "off/on test.")
1370 raise signals.TestFailure("Fail to finish toggle GPS off/on test "
1371 "within %d minutes" % (iteration * 4))
1372 finally:
1373 ad.send_keycode("HOME")
jasonkmludc430ec2020-03-27 10:40:39 +08001374
jasonkmlu4ba30a02020-04-09 14:16:49 +08001375
jasonkmludc430ec2020-03-27 10:40:39 +08001376def grant_location_permission(ad, option):
1377 """Grant or revoke location related permission.
1378
1379 Args:
1380 ad: An AndroidDevice object.
1381 option: Boolean to grant or revoke location related permissions.
1382 """
jasonkmlu4ba30a02020-04-09 14:16:49 +08001383 action = "grant" if option else "revoke"
jasonkmludc430ec2020-03-27 10:40:39 +08001384 for permission in LOCATION_PERMISSIONS:
1385 ad.log.info(
jasonkmlu4ba30a02020-04-09 14:16:49 +08001386 "%s permission:%s on %s" % (action, permission, TEST_PACKAGE_NAME))
1387 ad.adb.shell("pm %s %s %s" % (action, TEST_PACKAGE_NAME, permission))
1388
1389
1390def check_location_runtime_permissions(ad, package, permissions):
1391 """Check if runtime permissions are granted on selected package.
1392
1393 Args:
1394 ad: An AndroidDevice object.
1395 package: Apk package name to check.
1396 permissions: A list of permissions to be granted.
1397 """
1398 for _ in range(3):
1399 location_runtime_permission = ad.adb.shell(
1400 "dumpsys package %s | grep ACCESS_FINE_LOCATION" % package)
1401 if "true" not in location_runtime_permission:
1402 ad.log.info("ACCESS_FINE_LOCATION is NOT granted on %s" % package)
1403 for permission in permissions:
1404 ad.log.debug("Grant %s on %s" % (permission, package))
1405 ad.adb.shell("pm grant %s %s" % (package, permission))
1406 else:
1407 ad.log.info("ACCESS_FINE_LOCATION is granted on %s" % package)
1408 break
1409 else:
1410 raise signals.TestError(
1411 "Fail to grant ACCESS_FINE_LOCATION on %s" % package)
jasonkmlucb654ac2020-07-01 11:08:33 +08001412
1413
1414def install_mdstest_app(ad, mdsapp):
1415 """
1416 Install MDS test app in DUT
1417
1418 Args:
1419 ad: An Android Device Object
1420 mdsapp: Installation path of MDSTest app
1421 """
1422 if not ad.is_apk_installed("com.google.mdstest"):
1423 ad.adb.install("-r %s" % mdsapp, timeout=300, ignore_status=True)
1424
1425
1426def write_modemconfig(ad, mdsapp, nvitem_dict, modemparfile):
1427 """
1428 Modify the NV items using modem_tool.par
1429 Note: modem_tool.par
1430
1431 Args:
1432 ad: An Android Device Object
1433 mdsapp: Installation path of MDSTest app
1434 nvitem_dict: dictionary of NV items and values.
1435 modemparfile: modem_tool.par path.
1436 """
1437 ad.log.info("Verify MDSTest app installed in DUT")
1438 install_mdstest_app(ad, mdsapp)
1439 os.system("chmod 777 %s" % modemparfile)
1440 for key, value in nvitem_dict.items():
1441 if key.isdigit():
1442 op_name = "WriteEFS"
1443 else:
1444 op_name = "WriteNV"
1445 ad.log.info("Modifying the NV{!r} using {}".format(key, op_name))
1446 job.run("{} --op {} --item {} --data '{}'".
1447 format(modemparfile, op_name, key, value))
1448 time.sleep(2)
1449
1450
1451def verify_modemconfig(ad, nvitem_dict, modemparfile):
1452 """
1453 Verify the NV items using modem_tool.par
1454 Note: modem_tool.par
1455
1456 Args:
1457 ad: An Android Device Object
1458 nvitem_dict: dictionary of NV items and values
1459 modemparfile: modem_tool.par path.
1460 """
1461 os.system("chmod 777 %s" % modemparfile)
1462 for key, value in nvitem_dict.items():
1463 if key.isdigit():
1464 op_name = "ReadEFS"
1465 else:
1466 op_name = "ReadNV"
1467 # Sleeptime to avoid Modem communication error
1468 time.sleep(5)
1469 result = job.run(
1470 "{} --op {} --item {}".format(modemparfile, op_name, key))
1471 output = str(result.stdout)
1472 ad.log.info("Actual Value for NV{!r} is {!r}".format(key, output))
1473 if not value.casefold() in output:
1474 ad.log.error("NV Value is wrong {!r} in {!r}".format(value, result))
1475 raise ValueError(
1476 "could not find {!r} in {!r}".format(value, result))
Jayakumar Munuswamy7efa25b2020-07-07 15:30:08 -07001477
1478
jasonkmlu6ea2a2b2020-11-02 13:29:41 +08001479def check_ttff_pe(ad, ttff_data, ttff_mode, pe_criteria):
Jayakumar Munuswamy7efa25b2020-07-07 15:30:08 -07001480 """Verify all TTFF results from ttff_data.
1481
1482 Args:
1483 ad: An AndroidDevice object.
1484 ttff_data: TTFF data of secs, position error and signal strength.
1485 ttff_mode: TTFF Test mode for current test item.
jasonkmlu6ea2a2b2020-11-02 13:29:41 +08001486 pe_criteria: Criteria for current test item.
Jayakumar Munuswamy7efa25b2020-07-07 15:30:08 -07001487
1488 """
1489 ad.log.info("%d iterations of TTFF %s tests finished.",
1490 (len(ttff_data.keys()), ttff_mode))
jasonkmlu6ea2a2b2020-11-02 13:29:41 +08001491 ad.log.info("%s PASS criteria is %f meters", (ttff_mode, pe_criteria))
Jayakumar Munuswamy7efa25b2020-07-07 15:30:08 -07001492 ad.log.debug("%s TTFF data: %s", (ttff_mode, ttff_data))
1493
1494 if len(ttff_data.keys()) == 0:
1495 ad.log.error("GTW_GPSTool didn't process TTFF properly.")
1496 raise signals.TestFailure("GTW_GPSTool didn't process TTFF properly.")
1497
jasonkmlu6ea2a2b2020-11-02 13:29:41 +08001498 elif any(float(ttff_data[key].ttff_pe) >= pe_criteria for key in
Jayakumar Munuswamy7efa25b2020-07-07 15:30:08 -07001499 ttff_data.keys()):
1500 ad.log.error("One or more TTFF %s are over test criteria %f meters",
jasonkmlu6ea2a2b2020-11-02 13:29:41 +08001501 (ttff_mode, pe_criteria))
Jayakumar Munuswamy7efa25b2020-07-07 15:30:08 -07001502 raise signals.TestFailure("GTW_GPSTool didn't process TTFF properly.")
1503 ad.log.info("All TTFF %s are within test criteria %f meters.",
jasonkmlu6ea2a2b2020-11-02 13:29:41 +08001504 (ttff_mode, pe_criteria))
jasonkmlud68fdf02020-07-23 16:18:11 +08001505
1506
1507def check_adblog_functionality(ad):
1508 """Restart adb logcat if system can't write logs into file after checking
1509 adblog file size.
1510
1511 Args:
1512 ad: An AndroidDevice object.
1513 """
1514 logcat_path = os.path.join(ad.device_log_path, "adblog_%s_debug.txt" %
1515 ad.serial)
1516 if not os.path.exists(logcat_path):
1517 raise signals.TestError("Logcat file %s does not exist." % logcat_path)
1518 original_log_size = os.path.getsize(logcat_path)
1519 ad.log.debug("Original adblog size is %d" % original_log_size)
1520 time.sleep(.5)
1521 current_log_size = os.path.getsize(logcat_path)
1522 ad.log.debug("Current adblog size is %d" % current_log_size)
1523 if current_log_size == original_log_size:
1524 ad.log.warn("System can't write logs into file. Restart adb "
1525 "logcat process now.")
1526 ad.stop_adb_logcat()
1527 ad.start_adb_logcat()
Scott Hong0f5dfc42020-08-22 00:47:53 +08001528
jasonkmluc0939182021-02-19 18:34:28 +08001529
Scott Hong0f5dfc42020-08-22 00:47:53 +08001530def build_instrumentation_call(package,
1531 runner,
1532 test_methods=None,
1533 options=None):
1534 """Build an instrumentation call for the tests
1535
1536 Args:
1537 package: A string to identify test package.
1538 runner: A string to identify test runner.
1539 test_methods: A dictionary contains {class_name, test_method}.
jasonkmlu6ea2a2b2020-11-02 13:29:41 +08001540 options: A dictionary constant {key, value} param for test.
Scott Hong0f5dfc42020-08-22 00:47:53 +08001541
1542 Returns:
1543 An instrumentation call command.
1544 """
1545 if test_methods is None:
1546 test_methods = {}
1547 cmd_builder = InstrumentationCommandBuilder()
1548 else:
1549 cmd_builder = InstrumentationTestCommandBuilder()
Scott Hong0f5dfc42020-08-22 00:47:53 +08001550 if options is None:
1551 options = {}
Scott Hong0f5dfc42020-08-22 00:47:53 +08001552 cmd_builder.set_manifest_package(package)
1553 cmd_builder.set_runner(runner)
Scott Honga2e430b2020-08-27 15:14:57 +08001554 cmd_builder.add_flag("-w")
Scott Hong0f5dfc42020-08-22 00:47:53 +08001555 for class_name, test_method in test_methods.items():
1556 cmd_builder.add_test_method(class_name, test_method)
Scott Hong0f5dfc42020-08-22 00:47:53 +08001557 for option_key, option_value in options.items():
1558 cmd_builder.add_key_value_param(option_key, option_value)
Scott Hong0f5dfc42020-08-22 00:47:53 +08001559 return cmd_builder.build()
jasonkmluc0939182021-02-19 18:34:28 +08001560
1561
1562def check_chipset_vendor_by_qualcomm(ad):
1563 """Check if cipset vendor is by Qualcomm.
1564
1565 Args:
1566 ad: An AndroidDevice object.
1567
1568 Returns:
1569 True if it's by Qualcomm. False irf not.
1570 """
1571 ad.root_adb()
1572 soc = str(ad.adb.shell("getprop gsm.version.ril-impl"))
1573 ad.log.debug("SOC = %s" % soc)
1574 return "Qualcomm" in soc
1575
1576
1577def delete_lto_file(ad):
1578 """Delete downloaded LTO files.
1579
1580 Args:
1581 ad: An AndroidDevice object.
1582 """
1583 remount_device(ad)
1584 status = ad.adb.shell("rm -rf /data/vendor/gps/lto*")
1585 ad.log.info("Delete downloaded LTO files.\n%s" % status)
1586
1587
1588def lto_mode(ad, state):
1589 """Enable or Disable LTO mode.
1590
1591 Args:
1592 ad: An AndroidDevice object.
1593 state: True to enable. False to disable.
1594 """
1595 server_list = ["LONGTERM_PSDS_SERVER_1",
1596 "LONGTERM_PSDS_SERVER_2",
1597 "LONGTERM_PSDS_SERVER_3",
1598 "NORMAL_PSDS_SERVER",
1599 "REALTIME_PSDS_SERVER"]
1600 delete_lto_file(ad)
1601 tmp_path = tempfile.mkdtemp()
1602 ad.pull_files("/etc/gps_debug.conf", tmp_path)
1603 gps_conf_path = os.path.join(tmp_path, "gps_debug.conf")
1604 gps_conf_file = open(gps_conf_path, "r")
1605 lines = gps_conf_file.readlines()
1606 gps_conf_file.close()
1607 fout = open(gps_conf_path, "w")
1608 if state:
1609 for line in lines:
1610 for server in server_list:
1611 if server in line:
1612 line = line.replace(line, "")
1613 fout.write(line)
1614 fout.close()
1615 ad.push_system_file(gps_conf_path, "/etc/gps_debug.conf")
1616 ad.log.info("Push back modified gps_debug.conf")
1617 ad.log.info("LTO/RTO/RTI enabled")
1618 else:
1619 ad.adb.shell("echo %r >> /etc/gps_debug.conf" %
1620 DISABLE_LTO_FILE_CONTENTS)
1621 ad.log.info("LTO/RTO/RTI disabled")
1622 reboot(ad)
1623
1624
jasonkmlu9b278f92021-04-20 01:06:50 +08001625def start_pixel_logger(ad, max_log_size_mb=100, max_number_of_files=500):
jasonkmluc0939182021-02-19 18:34:28 +08001626 """adb to start pixel logger for GNSS logging.
1627
1628 Args:
1629 ad: An AndroidDevice object.
jasonkmlu9b278f92021-04-20 01:06:50 +08001630 max_log_size_mb: Determines when to create a new log file if current
1631 one reaches the size limit.
1632 max_number_of_files: Determines how many log files can be saved on DUT.
jasonkmluc0939182021-02-19 18:34:28 +08001633 """
jasonkmlu9387b5a2021-04-23 03:28:40 +08001634 retries = 3
jasonkmluc0939182021-02-19 18:34:28 +08001635 start_timeout_sec = 60
jasonkmlu9b278f92021-04-20 01:06:50 +08001636 default_gnss_cfg = "/vendor/etc/mdlog/DEFAULT+SECURITY+FULLDPL+GPS.cfg"
1637 if check_chipset_vendor_by_qualcomm(ad):
1638 start_cmd = ("am start-foreground-service -a com.android.pixellogger"
1639 ".service.logging.LoggingService.ACTION_START_LOGGING "
1640 "-e intent_key_cfg_path '%s' "
1641 "--ei intent_key_max_log_size_mb %d "
1642 "--ei intent_key_max_number_of_files %d" % (
1643 default_gnss_cfg, max_log_size_mb, max_number_of_files))
1644 else:
1645 start_cmd = ("am startservice -a com.android.pixellogger."
1646 "service.logging.LoggingService.ACTION_START_LOGGING "
1647 "-e intent_logger brcm_gps")
jasonkmlu9387b5a2021-04-23 03:28:40 +08001648 for attempt in range(retries):
1649 begin_time = get_current_epoch_time()
1650 ad.log.info("Start Pixel Logger. - Attempt %d" % (attempt + 1))
1651 ad.adb.shell(start_cmd)
1652 while get_current_epoch_time() - begin_time <= start_timeout_sec * 1000:
1653 if not ad.is_adb_logcat_on:
1654 ad.start_adb_logcat()
1655 if check_chipset_vendor_by_qualcomm(ad):
1656 start_result = ad.search_logcat("Start logging", begin_time)
1657 else:
1658 start_result = ad.search_logcat("startRecording", begin_time)
1659 if start_result:
1660 ad.log.info("Pixel Logger starts recording successfully.")
1661 return True
1662 ad.force_stop_apk("com.android.pixellogger")
jasonkmluc0939182021-02-19 18:34:28 +08001663 else:
jasonkmlu9387b5a2021-04-23 03:28:40 +08001664 ad.log.warn("Pixel Logger fails to start recording in %d seconds "
1665 "within %d attempts." % (start_timeout_sec, retries))
jasonkmluc0939182021-02-19 18:34:28 +08001666
1667
1668def stop_pixel_logger(ad):
1669 """adb to stop pixel logger for GNSS logging.
1670
1671 Args:
1672 ad: An AndroidDevice object.
1673 """
jasonkmlu9387b5a2021-04-23 03:28:40 +08001674 retries = 3
jasonkmluc0939182021-02-19 18:34:28 +08001675 stop_timeout_sec = 300
jasonkmlu9b278f92021-04-20 01:06:50 +08001676 if check_chipset_vendor_by_qualcomm(ad):
1677 stop_cmd = ("am start-foreground-service -a com.android.pixellogger"
1678 ".service.logging.LoggingService.ACTION_STOP_LOGGING")
1679 else:
1680 stop_cmd = ("am startservice -a com.android.pixellogger."
1681 "service.logging.LoggingService.ACTION_STOP_LOGGING "
1682 "-e intent_logger brcm_gps")
jasonkmlu9387b5a2021-04-23 03:28:40 +08001683 for attempt in range(retries):
1684 begin_time = get_current_epoch_time()
1685 ad.log.info("Stop Pixel Logger. - Attempt %d" % (attempt + 1))
1686 ad.adb.shell(stop_cmd)
1687 while get_current_epoch_time() - begin_time <= stop_timeout_sec * 1000:
1688 if not ad.is_adb_logcat_on:
1689 ad.start_adb_logcat()
1690 stop_result = ad.search_logcat(
1691 "LoggingService: Stopping service", begin_time)
1692 if stop_result:
1693 ad.log.info("Pixel Logger stops successfully.")
1694 return True
1695 ad.force_stop_apk("com.android.pixellogger")
jasonkmluc0939182021-02-19 18:34:28 +08001696 else:
jasonkmlu9387b5a2021-04-23 03:28:40 +08001697 ad.log.warn("Pixel Logger fails to stop in %d seconds within %d "
1698 "attempts." % (stop_timeout_sec, retries))
1699
1700
1701def launch_eecoexer(ad):
1702 """adb to stop pixel logger for GNSS logging.
1703
1704 Args:
1705 ad: An AndroidDevice object.
1706 """
1707 launch_cmd = ("am start -a android.intent.action.MAIN -n"
1708 "com.google.eecoexer"
1709 "/.MainActivity")
1710 ad.adb.shell(launch_cmd)
1711 try:
1712 ad.log.info("Launch EEcoexer.")
1713 except Exception as e:
1714 ad.log.error(e)
1715 raise signals.TestError("Failed to launch EEcoexer.")
1716
1717
1718def excute_eecoexer_function(ad, eecoexer_args):
1719 """adb to stop pixel logger for GNSS logging.
1720
1721 Args:
1722 ad: An AndroidDevice object.
1723 eecoexer_args: EEcoexer function arguments
1724 """
1725 enqueue_cmd = ("am broadcast -a com.google.eecoexer.action.LISTENER"
1726 " --es sms_body ENQUEUE,{}".format(eecoexer_args))
1727 exe_cmd = ("am broadcast -a com.google.eecoexer.action.LISTENER"
1728 " --es sms_body EXECUTE")
1729 ad.log.info("EEcoexer Add Enqueue: {}".format(eecoexer_args))
1730 ad.adb.shell(enqueue_cmd)
1731 ad.log.info("EEcoexer Excute.")
1732 ad.adb.shell(exe_cmd)
1733
1734
1735def restart_gps_daemons(ad):
1736 """Restart GPS daemons by killing services of gpsd, lhd and scd.
1737
1738 Args:
1739 ad: An AndroidDevice object.
1740 """
1741 gps_daemons_list = ["gpsd", "lhd", "scd"]
1742 ad.root_adb()
1743 for service in gps_daemons_list:
1744 begin_time = get_current_epoch_time()
1745 time.sleep(3)
1746 ad.log.info("Kill GPS daemon \"%s\"" % service)
1747 ad.adb.shell("killall %s" % service)
1748 # Wait 3 seconds for daemons and services to start.
1749 time.sleep(3)
1750 restart_services = ad.search_logcat("starting service", begin_time)
1751 for restart_service in restart_services:
1752 if service in restart_service["log_message"]:
1753 ad.log.info(restart_service["log_message"])
1754 ad.log.info(
1755 "GPS daemon \"%s\" restarts successfully." % service)
1756 break
1757 else:
1758 raise signals.TestError("Unable to restart \"%s\"" % service)