1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "GnssHalTest"
18 
19 #include "gnss_hal_test.h"
20 #include <hidl/ServiceManagement.h>
21 #include <algorithm>
22 #include <cmath>
23 #include "Utils.h"
24 
25 using android::hardware::gnss::GnssClock;
26 using android::hardware::gnss::GnssConstellationType;
27 using android::hardware::gnss::GnssData;
28 using android::hardware::gnss::GnssLocation;
29 using android::hardware::gnss::GnssMeasurement;
30 using android::hardware::gnss::IGnss;
31 using android::hardware::gnss::IGnssCallback;
32 using android::hardware::gnss::IGnssMeasurementInterface;
33 using android::hardware::gnss::common::Utils;
34 using GnssConstellationTypeV2_0 = android::hardware::gnss::V2_0::GnssConstellationType;
35 
36 namespace {
37 // The difference between the mean of the received intervals and the requested interval should not
38 // be larger mInterval * ALLOWED_MEAN_ERROR_RATIO
39 constexpr double ALLOWED_MEAN_ERROR_RATIO = 0.25;
40 
41 // The standard deviation computed for the deltas should not be bigger
42 // than mInterval * ALLOWED_STDEV_ERROR_RATIO or MIN_STDEV_MS, whichever is higher.
43 constexpr double ALLOWED_STDEV_ERROR_RATIO = 0.50;
44 constexpr double MIN_STDEV_MS = 1000;
45 
computeMean(std::vector<int> & deltas)46 double computeMean(std::vector<int>& deltas) {
47     long accumulator = 0;
48     for (auto& d : deltas) {
49         accumulator += d;
50     }
51     return accumulator / deltas.size();
52 }
53 
computeStdev(double mean,std::vector<int> & deltas)54 double computeStdev(double mean, std::vector<int>& deltas) {
55     double accumulator = 0;
56     for (auto& d : deltas) {
57         double diff = d - mean;
58         accumulator += diff * diff;
59     }
60     return std::sqrt(accumulator / (deltas.size() - 1));
61 }
62 
63 }  // anonymous namespace
64 
SetUp()65 void GnssHalTest::SetUp() {
66     // Get AIDL handle
67     aidl_gnss_hal_ = android::waitForDeclaredService<IGnssAidl>(String16(GetParam().c_str()));
68     ASSERT_NE(aidl_gnss_hal_, nullptr);
69     ALOGD("AIDL Interface Version = %d", aidl_gnss_hal_->getInterfaceVersion());
70 
71     if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
72         const auto& hidlInstanceNames = android::hardware::getAllHalInstanceNames(
73                 android::hardware::gnss::V2_1::IGnss::descriptor);
74         gnss_hal_ = IGnss_V2_1::getService(hidlInstanceNames[0]);
75         ASSERT_NE(gnss_hal_, nullptr);
76     }
77 
78     SetUpGnssCallback();
79 }
80 
SetUpGnssCallback()81 void GnssHalTest::SetUpGnssCallback() {
82     aidl_gnss_cb_ = new GnssCallbackAidl();
83     ASSERT_NE(aidl_gnss_cb_, nullptr);
84 
85     auto status = aidl_gnss_hal_->setCallback(aidl_gnss_cb_);
86     if (!status.isOk()) {
87         ALOGE("Failed to setCallback");
88     }
89     ASSERT_TRUE(status.isOk());
90 
91     /*
92      * Capabilities callback should trigger.
93      */
94     EXPECT_TRUE(aidl_gnss_cb_->capabilities_cbq_.retrieve(aidl_gnss_cb_->last_capabilities_,
95                                                           TIMEOUT_SEC));
96     EXPECT_EQ(aidl_gnss_cb_->capabilities_cbq_.calledCount(), 1);
97 
98     if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
99         // Invoke the super method.
100         GnssHalTestTemplate<IGnss_V2_1>::SetUpGnssCallback();
101     } else {
102         /*
103          * SystemInfo callback should trigger
104          */
105         EXPECT_TRUE(aidl_gnss_cb_->info_cbq_.retrieve(aidl_gnss_cb_->last_info_, TIMEOUT_SEC));
106         EXPECT_EQ(aidl_gnss_cb_->info_cbq_.calledCount(), 1);
107     }
108 
109     /*
110      * SignalTypeCapabilities callback should trigger.
111      */
112     if (aidl_gnss_hal_->getInterfaceVersion() >= 3) {
113         EXPECT_TRUE(aidl_gnss_cb_->signal_type_capabilities_cbq_.retrieve(
114                 aidl_gnss_cb_->last_signal_type_capabilities, TIMEOUT_SEC));
115         EXPECT_EQ(aidl_gnss_cb_->signal_type_capabilities_cbq_.calledCount(), 1);
116     }
117 }
118 
TearDown()119 void GnssHalTest::TearDown() {
120     GnssHalTestTemplate<IGnss_V2_1>::TearDown();
121     if (aidl_gnss_hal_ != nullptr) {
122         aidl_gnss_hal_->close();
123         aidl_gnss_hal_ = nullptr;
124     }
125 
126     // Set to nullptr to destruct the callback event queues and warn of any unprocessed events.
127     aidl_gnss_cb_ = nullptr;
128 }
129 
CheckLocation(const GnssLocation & location,bool check_speed)130 void GnssHalTest::CheckLocation(const GnssLocation& location, bool check_speed) {
131     Utils::checkLocation(location, check_speed, /* check_more_accuracies= */ true);
132 }
133 
SetPositionMode(const int min_interval_msec,const bool low_power_mode)134 void GnssHalTest::SetPositionMode(const int min_interval_msec, const bool low_power_mode) {
135     if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
136         // Invoke the super method.
137         return GnssHalTestTemplate<IGnss_V2_1>::SetPositionMode(min_interval_msec, low_power_mode);
138     }
139 
140     const int kPreferredAccuracy = 0;  // Ideally perfect (matches GnssLocationProvider)
141     const int kPreferredTimeMsec = 0;  // Ideally immediate
142 
143     IGnss::PositionModeOptions options;
144     options.mode = IGnss::GnssPositionMode::MS_BASED;
145     options.recurrence = IGnss::GnssPositionRecurrence::RECURRENCE_PERIODIC;
146     options.minIntervalMs = min_interval_msec;
147     options.preferredAccuracyMeters = kPreferredAccuracy;
148     options.preferredTimeMs = kPreferredTimeMsec;
149     options.lowPowerMode = low_power_mode;
150     auto status = aidl_gnss_hal_->setPositionMode(options);
151 
152     ASSERT_TRUE(status.isOk());
153 }
154 
StartAndCheckFirstLocation(const int min_interval_msec,const bool low_power_mode,const bool start_sv_status,const bool start_nmea)155 bool GnssHalTest::StartAndCheckFirstLocation(const int min_interval_msec, const bool low_power_mode,
156                                              const bool start_sv_status, const bool start_nmea) {
157     if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
158         // Invoke the super method.
159         return GnssHalTestTemplate<IGnss_V2_1>::StartAndCheckFirstLocation(min_interval_msec,
160                                                                            low_power_mode);
161     }
162     SetPositionMode(min_interval_msec, low_power_mode);
163 
164     if (start_sv_status) {
165         auto status = aidl_gnss_hal_->startSvStatus();
166         EXPECT_TRUE(status.isOk());
167     }
168     if (start_nmea) {
169         auto status = aidl_gnss_hal_->startNmea();
170         EXPECT_TRUE(status.isOk());
171     }
172 
173     auto status = aidl_gnss_hal_->start();
174     EXPECT_TRUE(status.isOk());
175 
176     /*
177      * GnssLocationProvider support of AGPS SUPL & XtraDownloader is not available in VTS,
178      * so allow time to demodulate ephemeris over the air.
179      */
180     const int kFirstGnssLocationTimeoutSeconds = 75;
181 
182     EXPECT_TRUE(aidl_gnss_cb_->location_cbq_.retrieve(aidl_gnss_cb_->last_location_,
183                                                       kFirstGnssLocationTimeoutSeconds));
184     int locationCalledCount = aidl_gnss_cb_->location_cbq_.calledCount();
185     EXPECT_EQ(locationCalledCount, 1);
186 
187     if (locationCalledCount > 0) {
188         // don't require speed on first fix
189         CheckLocation(aidl_gnss_cb_->last_location_, false);
190         return true;
191     }
192     return false;
193 }
194 
StartAndCheckFirstLocation(const int min_interval_msec,const bool low_power_mode)195 bool GnssHalTest::StartAndCheckFirstLocation(const int min_interval_msec,
196                                              const bool low_power_mode) {
197     return StartAndCheckFirstLocation(min_interval_msec, low_power_mode,
198                                       /* start_sv_status= */ true, /* start_nmea= */ true);
199 }
200 
StopAndClearLocations()201 void GnssHalTest::StopAndClearLocations() {
202     ALOGD("StopAndClearLocations");
203     if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
204         // Invoke the super method.
205         return GnssHalTestTemplate<IGnss_V2_1>::StopAndClearLocations();
206     }
207     auto status = aidl_gnss_hal_->stopSvStatus();
208     EXPECT_TRUE(status.isOk());
209     status = aidl_gnss_hal_->stopNmea();
210     EXPECT_TRUE(status.isOk());
211 
212     status = aidl_gnss_hal_->stop();
213     EXPECT_TRUE(status.isOk());
214 
215     /*
216      * Clear notify/waiting counter, allowing up till the timeout after
217      * the last reply for final startup messages to arrive (esp. system
218      * info.)
219      */
220     while (aidl_gnss_cb_->location_cbq_.retrieve(aidl_gnss_cb_->last_location_, TIMEOUT_SEC)) {
221     }
222     aidl_gnss_cb_->location_cbq_.reset();
223 }
224 
StartAndCheckLocations(const int count,const bool start_sv_status,const bool start_nmea)225 void GnssHalTest::StartAndCheckLocations(const int count, const bool start_sv_status,
226                                          const bool start_nmea) {
227     if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
228         // Invoke the super method.
229         return GnssHalTestTemplate<IGnss_V2_1>::StartAndCheckLocations(count);
230     }
231     const int kMinIntervalMsec = 500;
232     const int kLocationTimeoutSubsequentSec = 2;
233     const bool kLowPowerMode = false;
234 
235     EXPECT_TRUE(StartAndCheckFirstLocation(kMinIntervalMsec, kLowPowerMode, start_sv_status,
236                                            start_nmea));
237 
238     for (int i = 1; i < count; i++) {
239         EXPECT_TRUE(aidl_gnss_cb_->location_cbq_.retrieve(aidl_gnss_cb_->last_location_,
240                                                           kLocationTimeoutSubsequentSec));
241         int locationCalledCount = aidl_gnss_cb_->location_cbq_.calledCount();
242         EXPECT_EQ(locationCalledCount, i + 1);
243         // Don't cause confusion by checking details if no location yet
244         if (locationCalledCount > 0) {
245             // Should be more than 1 location by now, but if not, still don't check first fix speed
246             CheckLocation(aidl_gnss_cb_->last_location_, locationCalledCount > 1);
247         }
248     }
249 }
250 
StartAndCheckLocations(const int count)251 void GnssHalTest::StartAndCheckLocations(const int count) {
252     StartAndCheckLocations(count, /* start_sv_status= */ true, /* start_nmea= */ true);
253 }
254 
convertToAidl(const std::list<hidl_vec<IGnssCallback_2_1::GnssSvInfo>> & sv_info_list)255 std::list<std::vector<IGnssCallback::GnssSvInfo>> GnssHalTest::convertToAidl(
256         const std::list<hidl_vec<IGnssCallback_2_1::GnssSvInfo>>& sv_info_list) {
257     std::list<std::vector<IGnssCallback::GnssSvInfo>> aidl_sv_info_list;
258     for (const auto& sv_info_vec : sv_info_list) {
259         std::vector<IGnssCallback::GnssSvInfo> aidl_sv_info_vec;
260         for (const auto& sv_info : sv_info_vec) {
261             IGnssCallback::GnssSvInfo aidl_sv_info;
262             aidl_sv_info.svid = sv_info.v2_0.v1_0.svid;
263             aidl_sv_info.constellation =
264                     static_cast<GnssConstellationType>(sv_info.v2_0.constellation);
265             aidl_sv_info.cN0Dbhz = sv_info.v2_0.v1_0.cN0Dbhz;
266             aidl_sv_info.basebandCN0DbHz = sv_info.basebandCN0DbHz;
267             aidl_sv_info.elevationDegrees = sv_info.v2_0.v1_0.elevationDegrees;
268             aidl_sv_info.azimuthDegrees = sv_info.v2_0.v1_0.azimuthDegrees;
269             aidl_sv_info.carrierFrequencyHz = (int64_t)sv_info.v2_0.v1_0.carrierFrequencyHz;
270             aidl_sv_info.svFlag = (int)sv_info.v2_0.v1_0.svFlag;
271             aidl_sv_info_vec.push_back(aidl_sv_info);
272         }
273         aidl_sv_info_list.push_back(aidl_sv_info_vec);
274     }
275     return aidl_sv_info_list;
276 }
277 
278 /*
279  * FindStrongFrequentNonGpsSource:
280  *
281  * Search through a GnssSvStatus list for the strongest non-GPS satellite observed enough times
282  *
283  * returns the strongest source,
284  *         or a source with constellation == UNKNOWN if none are found sufficient times
285  */
FindStrongFrequentNonGpsSource(const std::list<hidl_vec<IGnssCallback_2_1::GnssSvInfo>> sv_info_list,const int min_observations)286 BlocklistedSource GnssHalTest::FindStrongFrequentNonGpsSource(
287         const std::list<hidl_vec<IGnssCallback_2_1::GnssSvInfo>> sv_info_list,
288         const int min_observations) {
289     return FindStrongFrequentNonGpsSource(convertToAidl(sv_info_list), min_observations);
290 }
291 
FindStrongFrequentNonGpsSource(const std::list<std::vector<IGnssCallback::GnssSvInfo>> sv_info_list,const int min_observations)292 BlocklistedSource GnssHalTest::FindStrongFrequentNonGpsSource(
293         const std::list<std::vector<IGnssCallback::GnssSvInfo>> sv_info_list,
294         const int min_observations) {
295     std::map<ComparableBlocklistedSource, SignalCounts> mapSignals;
296 
297     for (const auto& sv_info_vec : sv_info_list) {
298         for (uint32_t iSv = 0; iSv < sv_info_vec.size(); iSv++) {
299             const auto& gnss_sv = sv_info_vec[iSv];
300             if ((gnss_sv.svFlag & (int)IGnssCallback::GnssSvFlags::USED_IN_FIX) &&
301                 (gnss_sv.constellation != GnssConstellationType::GPS)) {
302                 ComparableBlocklistedSource source;
303                 source.id.svid = gnss_sv.svid;
304                 source.id.constellation = gnss_sv.constellation;
305 
306                 const auto& itSignal = mapSignals.find(source);
307                 if (itSignal == mapSignals.end()) {
308                     SignalCounts counts;
309                     counts.observations = 1;
310                     counts.max_cn0_dbhz = gnss_sv.cN0Dbhz;
311                     mapSignals.insert(
312                             std::pair<ComparableBlocklistedSource, SignalCounts>(source, counts));
313                 } else {
314                     itSignal->second.observations++;
315                     if (itSignal->second.max_cn0_dbhz < gnss_sv.cN0Dbhz) {
316                         itSignal->second.max_cn0_dbhz = gnss_sv.cN0Dbhz;
317                     }
318                 }
319             }
320         }
321     }
322 
323     float max_cn0_dbhz_with_sufficient_count = 0.;
324     int total_observation_count = 0;
325     int blocklisted_source_count_observation = 0;
326 
327     ComparableBlocklistedSource source_to_blocklist;  // initializes to zero = UNKNOWN constellation
328     for (auto const& pairSignal : mapSignals) {
329         total_observation_count += pairSignal.second.observations;
330         if ((pairSignal.second.observations >= min_observations) &&
331             (pairSignal.second.max_cn0_dbhz > max_cn0_dbhz_with_sufficient_count)) {
332             source_to_blocklist = pairSignal.first;
333             blocklisted_source_count_observation = pairSignal.second.observations;
334             max_cn0_dbhz_with_sufficient_count = pairSignal.second.max_cn0_dbhz;
335         }
336     }
337     ALOGD("Among %d observations, chose svid %d, constellation %d, "
338           "with %d observations at %.1f max CNo",
339           total_observation_count, source_to_blocklist.id.svid,
340           (int)source_to_blocklist.id.constellation, blocklisted_source_count_observation,
341           max_cn0_dbhz_with_sufficient_count);
342 
343     return source_to_blocklist.id;
344 }
345 
startLocationAndGetNonGpsConstellation(const int locations_to_await,const int gnss_sv_info_list_timeout)346 GnssConstellationType GnssHalTest::startLocationAndGetNonGpsConstellation(
347         const int locations_to_await, const int gnss_sv_info_list_timeout) {
348     if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
349         return static_cast<GnssConstellationType>(
350                 GnssHalTestTemplate<IGnss_V2_1>::startLocationAndGetNonGpsConstellation(
351                         locations_to_await, gnss_sv_info_list_timeout));
352     }
353     aidl_gnss_cb_->location_cbq_.reset();
354     StartAndCheckLocations(locations_to_await);
355     const int location_called_count = aidl_gnss_cb_->location_cbq_.calledCount();
356 
357     // Tolerate 1 less sv status to handle edge cases in reporting.
358     int sv_info_list_cbq_size = aidl_gnss_cb_->sv_info_list_cbq_.size();
359     EXPECT_GE(sv_info_list_cbq_size + 1, locations_to_await);
360     ALOGD("Observed %d GnssSvInfo, while awaiting %d Locations (%d received)",
361           sv_info_list_cbq_size, locations_to_await, location_called_count);
362 
363     // Find first non-GPS constellation to blocklist
364     GnssConstellationType constellation_to_blocklist = GnssConstellationType::UNKNOWN;
365     for (int i = 0; i < sv_info_list_cbq_size; ++i) {
366         std::vector<IGnssCallback::GnssSvInfo> sv_info_vec;
367         aidl_gnss_cb_->sv_info_list_cbq_.retrieve(sv_info_vec, gnss_sv_info_list_timeout);
368         for (uint32_t iSv = 0; iSv < sv_info_vec.size(); iSv++) {
369             auto& gnss_sv = sv_info_vec[iSv];
370             if ((gnss_sv.svFlag & (uint32_t)IGnssCallback::GnssSvFlags::USED_IN_FIX) &&
371                 (gnss_sv.constellation != GnssConstellationType::UNKNOWN) &&
372                 (gnss_sv.constellation != GnssConstellationType::GPS)) {
373                 // found a non-GPS constellation
374                 constellation_to_blocklist = gnss_sv.constellation;
375                 break;
376             }
377         }
378         if (constellation_to_blocklist != GnssConstellationType::UNKNOWN) {
379             break;
380         }
381     }
382 
383     if (constellation_to_blocklist == GnssConstellationType::UNKNOWN) {
384         ALOGI("No non-GPS constellations found, constellation blocklist test less effective.");
385         // Proceed functionally to blocklist something.
386         constellation_to_blocklist = GnssConstellationType::GLONASS;
387     }
388 
389     return constellation_to_blocklist;
390 }
391 
checkGnssMeasurementClockFields(const GnssData & measurement)392 void GnssHalTest::checkGnssMeasurementClockFields(const GnssData& measurement) {
393     Utils::checkElapsedRealtime(measurement.elapsedRealtime);
394     ASSERT_TRUE(measurement.clock.gnssClockFlags >= 0 &&
395                 measurement.clock.gnssClockFlags <=
396                         (GnssClock::HAS_LEAP_SECOND | GnssClock::HAS_TIME_UNCERTAINTY |
397                          GnssClock::HAS_FULL_BIAS | GnssClock::HAS_BIAS |
398                          GnssClock::HAS_BIAS_UNCERTAINTY | GnssClock::HAS_DRIFT |
399                          GnssClock::HAS_DRIFT_UNCERTAINTY));
400 }
401 
checkGnssMeasurementFlags(const GnssMeasurement & measurement)402 void GnssHalTest::checkGnssMeasurementFlags(const GnssMeasurement& measurement) {
403     ASSERT_TRUE(measurement.flags >= 0 &&
404                 measurement.flags <=
405                         (GnssMeasurement::HAS_SNR | GnssMeasurement::HAS_CARRIER_FREQUENCY |
406                          GnssMeasurement::HAS_CARRIER_CYCLES | GnssMeasurement::HAS_CARRIER_PHASE |
407                          GnssMeasurement::HAS_CARRIER_PHASE_UNCERTAINTY |
408                          GnssMeasurement::HAS_AUTOMATIC_GAIN_CONTROL |
409                          GnssMeasurement::HAS_FULL_ISB | GnssMeasurement::HAS_FULL_ISB_UNCERTAINTY |
410                          GnssMeasurement::HAS_SATELLITE_ISB |
411                          GnssMeasurement::HAS_SATELLITE_ISB_UNCERTAINTY |
412                          GnssMeasurement::HAS_SATELLITE_PVT |
413                          GnssMeasurement::HAS_CORRELATION_VECTOR));
414 }
415 
checkGnssMeasurementFields(const GnssMeasurement & measurement,const GnssData & data)416 void GnssHalTest::checkGnssMeasurementFields(const GnssMeasurement& measurement,
417                                              const GnssData& data) {
418     checkGnssMeasurementFlags(measurement);
419     // Verify CodeType is valid.
420     ASSERT_NE(measurement.signalType.codeType, "");
421     // Verify basebandCn0DbHz is valid.
422     ASSERT_TRUE(measurement.basebandCN0DbHz > 0.0 && measurement.basebandCN0DbHz <= 65.0);
423 
424     if (((measurement.flags & GnssMeasurement::HAS_FULL_ISB) > 0) &&
425         ((measurement.flags & GnssMeasurement::HAS_FULL_ISB_UNCERTAINTY) > 0) &&
426         ((measurement.flags & GnssMeasurement::HAS_SATELLITE_ISB) > 0) &&
427         ((measurement.flags & GnssMeasurement::HAS_SATELLITE_ISB_UNCERTAINTY) > 0)) {
428         GnssConstellationType referenceConstellation =
429                 data.clock.referenceSignalTypeForIsb.constellation;
430         double carrierFrequencyHz = data.clock.referenceSignalTypeForIsb.carrierFrequencyHz;
431         std::string codeType = data.clock.referenceSignalTypeForIsb.codeType;
432 
433         ASSERT_TRUE(referenceConstellation >= GnssConstellationType::UNKNOWN &&
434                     referenceConstellation <= GnssConstellationType::IRNSS);
435         ASSERT_TRUE(carrierFrequencyHz > 0);
436         ASSERT_NE(codeType, "");
437 
438         ASSERT_TRUE(std::abs(measurement.fullInterSignalBiasNs) < 1.0e6);
439         ASSERT_TRUE(measurement.fullInterSignalBiasUncertaintyNs >= 0);
440         ASSERT_TRUE(std::abs(measurement.satelliteInterSignalBiasNs) < 1.0e6);
441         ASSERT_TRUE(measurement.satelliteInterSignalBiasUncertaintyNs >= 0);
442     }
443 }
444 
startMeasurementWithInterval(int intervalMs,const sp<IGnssMeasurementInterface> & iGnssMeasurement,sp<GnssMeasurementCallbackAidl> & callback)445 void GnssHalTest::startMeasurementWithInterval(
446         int intervalMs, const sp<IGnssMeasurementInterface>& iGnssMeasurement,
447         sp<GnssMeasurementCallbackAidl>& callback) {
448     ALOGD("Start requesting measurement at interval of %d millis.", intervalMs);
449     IGnssMeasurementInterface::Options options;
450     options.intervalMs = intervalMs;
451     auto status = iGnssMeasurement->setCallbackWithOptions(callback, options);
452     ASSERT_TRUE(status.isOk());
453 }
454 
collectMeasurementIntervals(const sp<GnssMeasurementCallbackAidl> & callback,const int numMeasurementEvents,const int timeoutSeconds,std::vector<int> & deltasMs)455 void GnssHalTest::collectMeasurementIntervals(const sp<GnssMeasurementCallbackAidl>& callback,
456                                               const int numMeasurementEvents,
457                                               const int timeoutSeconds,
458                                               std::vector<int>& deltasMs) {
459     callback->gnss_data_cbq_.reset();  // throw away the initial measurements if any
460     int64_t lastElapsedRealtimeMillis = 0;
461     for (int i = 0; i < numMeasurementEvents; i++) {
462         GnssData lastGnssData;
463         ASSERT_TRUE(callback->gnss_data_cbq_.retrieve(lastGnssData, timeoutSeconds));
464         EXPECT_EQ(callback->gnss_data_cbq_.calledCount(), i + 1);
465         ASSERT_TRUE(lastGnssData.measurements.size() > 0);
466 
467         // Validity check GnssData fields
468         checkGnssMeasurementClockFields(lastGnssData);
469         for (const auto& measurement : lastGnssData.measurements) {
470             checkGnssMeasurementFields(measurement, lastGnssData);
471         }
472 
473         long currentElapsedRealtimeMillis = lastGnssData.elapsedRealtime.timestampNs * 1e-6;
474         if (lastElapsedRealtimeMillis != 0) {
475             deltasMs.push_back(currentElapsedRealtimeMillis - lastElapsedRealtimeMillis);
476         }
477         lastElapsedRealtimeMillis = currentElapsedRealtimeMillis;
478     }
479 }
480 
collectSvInfoListTimestamps(const int numMeasurementEvents,const int timeoutSeconds,std::vector<int> & deltasMs)481 void GnssHalTest::collectSvInfoListTimestamps(const int numMeasurementEvents,
482                                               const int timeoutSeconds,
483                                               std::vector<int>& deltasMs) {
484     aidl_gnss_cb_->sv_info_list_timestamps_millis_cbq_.reset();
485     aidl_gnss_cb_->sv_info_list_cbq_.reset();
486 
487     auto status = aidl_gnss_hal_->startSvStatus();
488     EXPECT_TRUE(status.isOk());
489     long lastElapsedRealtimeMillis = 0;
490     for (int i = 0; i < numMeasurementEvents; i++) {
491         long timeStamp;
492         ASSERT_TRUE(aidl_gnss_cb_->sv_info_list_timestamps_millis_cbq_.retrieve(timeStamp,
493                                                                                 timeoutSeconds));
494         if (lastElapsedRealtimeMillis != 0) {
495             deltasMs.push_back(timeStamp - lastElapsedRealtimeMillis);
496         }
497         lastElapsedRealtimeMillis = timeStamp;
498     }
499     status = aidl_gnss_hal_->stopSvStatus();
500     EXPECT_TRUE(status.isOk());
501 }
502 
checkGnssDataFields(const sp<GnssMeasurementCallbackAidl> & callback,const int numMeasurementEvents,const int timeoutSeconds,const bool isFullTracking)503 void GnssHalTest::checkGnssDataFields(const sp<GnssMeasurementCallbackAidl>& callback,
504                                       const int numMeasurementEvents, const int timeoutSeconds,
505                                       const bool isFullTracking) {
506     for (int i = 0; i < numMeasurementEvents; i++) {
507         GnssData lastGnssData;
508         ASSERT_TRUE(callback->gnss_data_cbq_.retrieve(lastGnssData, timeoutSeconds));
509         EXPECT_EQ(callback->gnss_data_cbq_.calledCount(), i + 1);
510         ASSERT_TRUE(lastGnssData.measurements.size() > 0);
511 
512         // Validity check GnssData fields
513         checkGnssMeasurementClockFields(lastGnssData);
514         if (aidl_gnss_hal_->getInterfaceVersion() >= 3) {
515             if (isFullTracking) {
516                 EXPECT_EQ(lastGnssData.isFullTracking, isFullTracking);
517             }
518         }
519         for (const auto& measurement : lastGnssData.measurements) {
520             checkGnssMeasurementFields(measurement, lastGnssData);
521         }
522     }
523 }
524 
assertMeanAndStdev(int intervalMs,std::vector<int> & deltasMs)525 void GnssHalTest::assertMeanAndStdev(int intervalMs, std::vector<int>& deltasMs) {
526     double mean = computeMean(deltasMs);
527     double stdev = computeStdev(mean, deltasMs);
528     EXPECT_TRUE(std::abs(mean - intervalMs) <= intervalMs * ALLOWED_MEAN_ERROR_RATIO)
529             << "Test failed, because the mean of intervals is " << mean
530             << " millis. The test requires that abs(" << mean << " - " << intervalMs
531             << ") <= " << intervalMs * ALLOWED_MEAN_ERROR_RATIO
532             << " millis, when the requested interval is " << intervalMs << " millis.";
533 
534     double maxStdev = std::max(MIN_STDEV_MS, intervalMs * ALLOWED_STDEV_ERROR_RATIO);
535     EXPECT_TRUE(stdev <= maxStdev)
536             << "Test failed, because the stdev of intervals is " << stdev
537             << " millis, which must be <= " << maxStdev
538             << " millis, when the requested interval is " << intervalMs << " millis.";
539     ALOGD("Mean of interval deltas in millis: %.1lf", mean);
540     ALOGD("Stdev of interval deltas in millis: %.1lf", stdev);
541 }
542