1 /*
2  * Copyright (C) 2017 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 "VtsHalGnssV1_0TargetTest"
18 #include <android/hardware/gnss/1.0/IGnss.h>
19 #include <gtest/gtest.h>
20 #include <hidl/GtestPrinter.h>
21 #include <hidl/ServiceManagement.h>
22 #include <log/log.h>
23 
24 #include <chrono>
25 #include <cmath>
26 #include <condition_variable>
27 #include <mutex>
28 
29 #include <cutils/properties.h>
30 
31 using android::hardware::Return;
32 using android::hardware::Void;
33 
34 using android::hardware::gnss::V1_0::GnssLocation;
35 using android::hardware::gnss::V1_0::GnssLocationFlags;
36 using android::hardware::gnss::V1_0::IGnss;
37 using android::hardware::gnss::V1_0::IGnssCallback;
38 using android::hardware::gnss::V1_0::IGnssDebug;
39 using android::hardware::gnss::V1_0::IGnssMeasurement;
40 using android::sp;
41 
42 /*
43  * Since Utils.cpp depends on Gnss Hal 2.0, the tests for Gnss Hal 1.0 will use
44  * there own version of IsAutomotiveDevice() instead of the common version.
45  */
IsAutomotiveDevice()46 static bool IsAutomotiveDevice() {
47     char buffer[PROPERTY_VALUE_MAX] = {0};
48     property_get("ro.hardware.type", buffer, "");
49     return strncmp(buffer, "automotive", PROPERTY_VALUE_MAX) == 0;
50 }
51 
52 #define TIMEOUT_SEC 2  // for basic commands/responses
53 
54 // for command line argument on how strictly to run the test
55 bool sAgpsIsPresent = false;  // if SUPL or XTRA assistance available
56 bool sSignalIsWeak = false;   // if GNSS signals are weak (e.g. light indoor)
57 
58 // The main test class for GNSS HAL.
59 class GnssHalTest : public testing::TestWithParam<std::string> {
60  public:
SetUp()61   virtual void SetUp() override {
62     // Clean between tests
63     capabilities_called_count_ = 0;
64     location_called_count_ = 0;
65     info_called_count_ = 0;
66     notify_count_ = 0;
67 
68     gnss_hal_ = IGnss::getService(GetParam());
69     ASSERT_NE(gnss_hal_, nullptr);
70 
71     gnss_cb_ = new GnssCallback(*this);
72     ASSERT_NE(gnss_cb_, nullptr);
73 
74     auto result = gnss_hal_->setCallback(gnss_cb_);
75     if (!result.isOk()) {
76       ALOGE("result of failed setCallback %s", result.description().c_str());
77     }
78 
79     ASSERT_TRUE(result.isOk());
80     ASSERT_TRUE(result);
81 
82     /*
83      * At least one callback should trigger - it may be capabilites, or
84      * system info first, so wait again if capabilities not received.
85      */
86     EXPECT_EQ(std::cv_status::no_timeout, wait(TIMEOUT_SEC));
87     if (capabilities_called_count_ == 0) {
88       EXPECT_EQ(std::cv_status::no_timeout, wait(TIMEOUT_SEC));
89     }
90 
91     /*
92      * Generally should be 1 capabilites callback -
93      * or possibly 2 in some recovery cases (default cached & refreshed)
94      */
95     EXPECT_GE(capabilities_called_count_, 1);
96     EXPECT_LE(capabilities_called_count_, 2);
97 
98     /*
99      * Clear notify/waiting counter, allowing up till the timeout after
100      * the last reply for final startup messages to arrive (esp. system
101      * info.)
102      */
103     while (wait(TIMEOUT_SEC) == std::cv_status::no_timeout) {
104     }
105   }
106 
TearDown()107   virtual void TearDown() override {
108     if (gnss_hal_ != nullptr) {
109       gnss_hal_->cleanup();
110     }
111     if (notify_count_ > 0) {
112         ALOGW("%d unprocessed callbacks discarded", notify_count_);
113     }
114   }
115 
116   /* Used as a mechanism to inform the test that a callback has occurred */
notify()117   inline void notify() {
118     std::unique_lock<std::mutex> lock(mtx_);
119     notify_count_++;
120     cv_.notify_one();
121   }
122 
123   /* Test code calls this function to wait for a callback */
wait(int timeoutSeconds)124   inline std::cv_status wait(int timeoutSeconds) {
125     std::unique_lock<std::mutex> lock(mtx_);
126 
127     std::cv_status status = std::cv_status::no_timeout;
128     auto now = std::chrono::system_clock::now();
129     while (notify_count_ == 0) {
130         status = cv_.wait_until(lock, now + std::chrono::seconds(timeoutSeconds));
131         if (status == std::cv_status::timeout) return status;
132     }
133     notify_count_--;
134     return status;
135   }
136 
137   /*
138    * SetPositionMode:
139    * Helper function to set positioning mode and verify output
140    */
SetPositionMode(const int min_interval_msec)141   void SetPositionMode(const int min_interval_msec) {
142       const int kPreferredAccuracy = 0;  // Ideally perfect (matches GnssLocationProvider)
143       const int kPreferredTimeMsec = 0;  // Ideally immediate
144 
145       auto result = gnss_hal_->setPositionMode(
146               IGnss::GnssPositionMode::MS_BASED, IGnss::GnssPositionRecurrence::RECURRENCE_PERIODIC,
147               min_interval_msec, kPreferredAccuracy, kPreferredTimeMsec);
148 
149       ASSERT_TRUE(result.isOk());
150       EXPECT_TRUE(result);
151   }
152 
153   /*
154    * StartAndGetSingleLocation:
155    * Helper function to get one Location and check fields
156    *
157    * returns  true if a location was successfully generated
158    */
StartAndGetSingleLocation(const bool checkAccuracies,const int min_interval_msec)159   bool StartAndGetSingleLocation(const bool checkAccuracies, const int min_interval_msec) {
160       SetPositionMode(min_interval_msec);
161       auto result = gnss_hal_->start();
162 
163       EXPECT_TRUE(result.isOk());
164       EXPECT_TRUE(result);
165 
166       /*
167        * GPS signals initially optional for this test, so don't expect fast fix,
168        * or no timeout, unless signal is present
169        */
170       int firstGnssLocationTimeoutSeconds = sAgpsIsPresent ? 15 : 45;
171       if (sSignalIsWeak) {
172           // allow more time for weak signals
173           firstGnssLocationTimeoutSeconds += 30;
174       }
175 
176       wait(firstGnssLocationTimeoutSeconds);
177       if (sAgpsIsPresent) {
178           EXPECT_EQ(location_called_count_, 1);
179       }
180       if (location_called_count_ > 0) {
181           // don't require speed on first fix
182           CheckLocation(last_location_, checkAccuracies, false);
183           return true;
184       }
185       return false;
186   }
187 
188   /*
189    * StopAndClearLocations:
190    * Helper function to stop locations
191    *
192    * returns  true if a location was successfully generated
193    */
StopAndClearLocations()194   void StopAndClearLocations() {
195       auto result = gnss_hal_->stop();
196 
197       EXPECT_TRUE(result.isOk());
198       EXPECT_TRUE(result);
199 
200       /*
201        * Clear notify/waiting counter, allowing up till the timeout after
202        * the last reply for final startup messages to arrive (esp. system
203        * info.)
204        */
205       while (wait(TIMEOUT_SEC) == std::cv_status::no_timeout) {
206       }
207   }
208 
209   /*
210    * CheckLocation:
211    *   Helper function to vet Location fields
212    */
CheckLocation(GnssLocation & location,bool checkAccuracies,bool checkSpeed)213   void CheckLocation(GnssLocation& location, bool checkAccuracies, bool checkSpeed) {
214       EXPECT_TRUE(location.gnssLocationFlags & GnssLocationFlags::HAS_LAT_LONG);
215       EXPECT_TRUE(location.gnssLocationFlags & GnssLocationFlags::HAS_ALTITUDE);
216       if (checkSpeed) {
217           EXPECT_TRUE(location.gnssLocationFlags & GnssLocationFlags::HAS_SPEED);
218       }
219       EXPECT_TRUE(location.gnssLocationFlags & GnssLocationFlags::HAS_HORIZONTAL_ACCURACY);
220       // New uncertainties available in O must be provided,
221       // at least when paired with modern hardware (2017+)
222       if (checkAccuracies) {
223           EXPECT_TRUE(location.gnssLocationFlags & GnssLocationFlags::HAS_VERTICAL_ACCURACY);
224           if (checkSpeed) {
225               EXPECT_TRUE(location.gnssLocationFlags & GnssLocationFlags::HAS_SPEED_ACCURACY);
226               if (location.gnssLocationFlags & GnssLocationFlags::HAS_BEARING) {
227                   EXPECT_TRUE(location.gnssLocationFlags & GnssLocationFlags::HAS_BEARING_ACCURACY);
228               }
229           }
230       }
231       EXPECT_GE(location.latitudeDegrees, -90.0);
232       EXPECT_LE(location.latitudeDegrees, 90.0);
233       EXPECT_GE(location.longitudeDegrees, -180.0);
234       EXPECT_LE(location.longitudeDegrees, 180.0);
235       EXPECT_GE(location.altitudeMeters, -1000.0);
236       EXPECT_LE(location.altitudeMeters, 30000.0);
237       if (checkSpeed) {
238           EXPECT_GE(location.speedMetersPerSec, 0.0);
239           EXPECT_LE(location.speedMetersPerSec, 5.0);  // VTS tests are stationary.
240 
241           // Non-zero speeds must be reported with an associated bearing
242           if (location.speedMetersPerSec > 0.0) {
243               EXPECT_TRUE(location.gnssLocationFlags & GnssLocationFlags::HAS_BEARING);
244           }
245       }
246 
247       /*
248        * Tolerating some especially high values for accuracy estimate, in case of
249        * first fix with especially poor geometry (happens occasionally)
250        */
251       EXPECT_GT(location.horizontalAccuracyMeters, 0.0);
252       EXPECT_LE(location.horizontalAccuracyMeters, 250.0);
253 
254       /*
255        * Some devices may define bearing as -180 to +180, others as 0 to 360.
256        * Both are okay & understandable.
257        */
258       if (location.gnssLocationFlags & GnssLocationFlags::HAS_BEARING) {
259           EXPECT_GE(location.bearingDegrees, -180.0);
260           EXPECT_LE(location.bearingDegrees, 360.0);
261       }
262       if (location.gnssLocationFlags & GnssLocationFlags::HAS_VERTICAL_ACCURACY) {
263           EXPECT_GT(location.verticalAccuracyMeters, 0.0);
264           EXPECT_LE(location.verticalAccuracyMeters, 500.0);
265       }
266       if (location.gnssLocationFlags & GnssLocationFlags::HAS_SPEED_ACCURACY) {
267           EXPECT_GT(location.speedAccuracyMetersPerSecond, 0.0);
268           EXPECT_LE(location.speedAccuracyMetersPerSecond, 50.0);
269       }
270       if (location.gnssLocationFlags & GnssLocationFlags::HAS_BEARING_ACCURACY) {
271           EXPECT_GT(location.bearingAccuracyDegrees, 0.0);
272           EXPECT_LE(location.bearingAccuracyDegrees, 360.0);
273       }
274 
275       // Check timestamp > 1.48e12 (47 years in msec - 1970->2017+)
276       EXPECT_GT(location.timestamp, 1.48e12);
277   }
278 
279   /* Callback class for data & Event. */
280   class GnssCallback : public IGnssCallback {
281    public:
282     GnssHalTest& parent_;
283 
GnssCallback(GnssHalTest & parent)284     GnssCallback(GnssHalTest& parent) : parent_(parent){};
285 
286     virtual ~GnssCallback() = default;
287 
288     // Dummy callback handlers
gnssStatusCb(const IGnssCallback::GnssStatusValue)289     Return<void> gnssStatusCb(
290         const IGnssCallback::GnssStatusValue /* status */) override {
291       return Void();
292     }
gnssSvStatusCb(const IGnssCallback::GnssSvStatus &)293     Return<void> gnssSvStatusCb(
294         const IGnssCallback::GnssSvStatus& /* svStatus */) override {
295       return Void();
296     }
gnssNmeaCb(int64_t,const android::hardware::hidl_string &)297     Return<void> gnssNmeaCb(
298         int64_t /* timestamp */,
299         const android::hardware::hidl_string& /* nmea */) override {
300       return Void();
301     }
gnssAcquireWakelockCb()302     Return<void> gnssAcquireWakelockCb() override { return Void(); }
gnssReleaseWakelockCb()303     Return<void> gnssReleaseWakelockCb() override { return Void(); }
gnssRequestTimeCb()304     Return<void> gnssRequestTimeCb() override { return Void(); }
305 
306     // Actual (test) callback handlers
gnssLocationCb(const GnssLocation & location)307     Return<void> gnssLocationCb(const GnssLocation& location) override {
308       ALOGI("Location received");
309       parent_.location_called_count_++;
310       parent_.last_location_ = location;
311       parent_.notify();
312       return Void();
313     }
314 
gnssSetCapabilitesCb(uint32_t capabilities)315     Return<void> gnssSetCapabilitesCb(uint32_t capabilities) override {
316       ALOGI("Capabilities received %d", capabilities);
317       parent_.capabilities_called_count_++;
318       parent_.last_capabilities_ = capabilities;
319       parent_.notify();
320       return Void();
321     }
322 
gnssSetSystemInfoCb(const IGnssCallback::GnssSystemInfo & info)323     Return<void> gnssSetSystemInfoCb(
324         const IGnssCallback::GnssSystemInfo& info) override {
325       ALOGI("Info received, year %d", info.yearOfHw);
326       parent_.info_called_count_++;
327       parent_.last_info_ = info;
328       parent_.notify();
329       return Void();
330     }
331   };
332 
333   sp<IGnss> gnss_hal_;         // GNSS HAL to call into
334   sp<IGnssCallback> gnss_cb_;  // Primary callback interface
335 
336   /* Count of calls to set the following items, and the latest item (used by
337    * test.)
338    */
339   int capabilities_called_count_;
340   uint32_t last_capabilities_;
341 
342   int location_called_count_;
343   GnssLocation last_location_;
344 
345   int info_called_count_;
346   IGnssCallback::GnssSystemInfo last_info_;
347 
348  private:
349   std::mutex mtx_;
350   std::condition_variable cv_;
351   int notify_count_;
352 };
353 
354 /*
355  * SetCallbackCapabilitiesCleanup:
356  * Sets up the callback, awaits the capabilities, and calls cleanup
357  *
358  * Since this is just the basic operation of SetUp() and TearDown(),
359  * the function definition is intentionally empty
360  */
TEST_P(GnssHalTest,SetCallbackCapabilitiesCleanup)361 TEST_P(GnssHalTest, SetCallbackCapabilitiesCleanup) {}
362 
363 /*
364  * GetLocation:
365  * Turns on location, waits 45 second for at least 5 locations,
366  * and checks them for reasonable validity.
367  */
TEST_P(GnssHalTest,GetLocation)368 TEST_P(GnssHalTest, GetLocation) {
369     const int kMinIntervalMsec = 500;
370     const int kLocationTimeoutSubsequentSec = 3;
371     const int kLocationsToCheck = 5;
372 
373     bool checkMoreAccuracies = (info_called_count_ > 0 && last_info_.yearOfHw >= 2017);
374 
375     /*
376      * GPS signals initially optional for this test, so don't expect timeout yet.
377      */
378     bool gotLocation = StartAndGetSingleLocation(checkMoreAccuracies, kMinIntervalMsec);
379 
380     if (gotLocation) {
381         for (int i = 1; i < kLocationsToCheck; i++) {
382             EXPECT_EQ(std::cv_status::no_timeout, wait(kLocationTimeoutSubsequentSec));
383             EXPECT_EQ(location_called_count_, i + 1);
384             CheckLocation(last_location_, checkMoreAccuracies, true);
385         }
386     }
387 
388   StopAndClearLocations();
389 }
390 
391 /*
392  * InjectDelete:
393  * Ensures that calls to inject and/or delete information state are handled.
394  */
TEST_P(GnssHalTest,InjectDelete)395 TEST_P(GnssHalTest, InjectDelete) {
396   // confidently, well north of Alaska
397   auto result = gnss_hal_->injectLocation(80.0, -170.0, 1000.0);
398 
399   ASSERT_TRUE(result.isOk());
400   EXPECT_TRUE(result);
401 
402   // fake time, but generally reasonable values (time in Aug. 2018)
403   result = gnss_hal_->injectTime(1534567890123L, 123456L, 10000L);
404 
405   ASSERT_TRUE(result.isOk());
406   EXPECT_TRUE(result);
407 
408   auto resultVoid = gnss_hal_->deleteAidingData(IGnss::GnssAidingData::DELETE_POSITION);
409 
410   ASSERT_TRUE(resultVoid.isOk());
411 
412   resultVoid = gnss_hal_->deleteAidingData(IGnss::GnssAidingData::DELETE_TIME);
413 
414   ASSERT_TRUE(resultVoid.isOk());
415 
416   // Ensure we can get a good location after a bad injection has been deleted
417   StartAndGetSingleLocation(false, /* min_interval_sec= */ 1000);
418 
419   StopAndClearLocations();
420 }
421 
422 /*
423  * InjectSeedLocation:
424  * Injects a seed location and ensures the injected seed location is not fused in the resulting
425  * GNSS location.
426  */
TEST_P(GnssHalTest,InjectSeedLocation)427 TEST_P(GnssHalTest, InjectSeedLocation) {
428     // An arbitrary position in North Pacific Ocean (where no VTS labs will ever likely be located).
429     const double seedLatDegrees = 32.312894;
430     const double seedLngDegrees = -172.954117;
431     const float seedAccuracyMeters = 150.0;
432 
433     auto result = gnss_hal_->injectLocation(seedLatDegrees, seedLngDegrees, seedAccuracyMeters);
434     ASSERT_TRUE(result.isOk());
435     EXPECT_TRUE(result);
436 
437     StartAndGetSingleLocation(false, /* min_interval_msec= */ 1000);
438 
439     // Ensure we don't get a location anywhere within 111km (1 degree of lat or lng) of the seed
440     // location.
441     EXPECT_TRUE(std::abs(last_location_.latitudeDegrees - seedLatDegrees) > 1.0 ||
442                 std::abs(last_location_.longitudeDegrees - seedLngDegrees) > 1.0);
443 
444     StopAndClearLocations();
445 
446     auto resultVoid = gnss_hal_->deleteAidingData(IGnss::GnssAidingData::DELETE_POSITION);
447     ASSERT_TRUE(resultVoid.isOk());
448 }
449 
450 /*
451  * GetAllExtentions:
452  * Tries getting all optional extensions, and ensures a valid return
453  *   null or actual extension, no crash.
454  * Confirms year-based required extensions (Measurement & Debug) are present
455  */
TEST_P(GnssHalTest,GetAllExtensions)456 TEST_P(GnssHalTest, GetAllExtensions) {
457   // Basic call-is-handled checks
458   auto gnssXtra = gnss_hal_->getExtensionXtra();
459   ASSERT_TRUE(gnssXtra.isOk());
460 
461   auto gnssRil = gnss_hal_->getExtensionAGnssRil();
462   ASSERT_TRUE(gnssRil.isOk());
463 
464   auto gnssAgnss = gnss_hal_->getExtensionAGnss();
465   ASSERT_TRUE(gnssAgnss.isOk());
466 
467   auto gnssNi = gnss_hal_->getExtensionGnssNi();
468   ASSERT_TRUE(gnssNi.isOk());
469 
470   auto gnssNavigationMessage = gnss_hal_->getExtensionGnssNavigationMessage();
471   ASSERT_TRUE(gnssNavigationMessage.isOk());
472 
473   auto gnssConfiguration = gnss_hal_->getExtensionGnssConfiguration();
474   ASSERT_TRUE(gnssConfiguration.isOk());
475 
476   auto gnssGeofencing = gnss_hal_->getExtensionGnssGeofencing();
477   ASSERT_TRUE(gnssGeofencing.isOk());
478 
479   auto gnssBatching = gnss_hal_->getExtensionGnssBatching();
480   ASSERT_TRUE(gnssBatching.isOk());
481 
482   // Verifying, in some cases, that these return actual extensions
483   auto gnssMeasurement = gnss_hal_->getExtensionGnssMeasurement();
484   ASSERT_TRUE(gnssMeasurement.isOk());
485   if (last_capabilities_ & IGnssCallback::Capabilities::MEASUREMENTS) {
486     sp<IGnssMeasurement> iGnssMeas = gnssMeasurement;
487     EXPECT_NE(iGnssMeas, nullptr);
488   }
489 
490   auto gnssDebug = gnss_hal_->getExtensionGnssDebug();
491   ASSERT_TRUE(gnssDebug.isOk());
492   if (!IsAutomotiveDevice() && info_called_count_ > 0 && last_info_.yearOfHw >= 2017) {
493       sp<IGnssDebug> iGnssDebug = gnssDebug;
494       EXPECT_NE(iGnssDebug, nullptr);
495   }
496 }
497 
498 /*
499  * MeasurementCapabilities:
500  * Verifies that modern hardware supports measurement capabilities.
501  */
TEST_P(GnssHalTest,MeasurementCapabilites)502 TEST_P(GnssHalTest, MeasurementCapabilites) {
503     if (!IsAutomotiveDevice() && info_called_count_ > 0 && last_info_.yearOfHw >= 2016) {
504         EXPECT_TRUE(last_capabilities_ & IGnssCallback::Capabilities::MEASUREMENTS);
505     }
506 }
507 
508 /*
509  * SchedulingCapabilities:
510  * Verifies that 2018+ hardware supports Scheduling capabilities.
511  */
TEST_P(GnssHalTest,SchedulingCapabilities)512 TEST_P(GnssHalTest, SchedulingCapabilities) {
513     if (info_called_count_ > 0 && last_info_.yearOfHw >= 2018) {
514         EXPECT_TRUE(last_capabilities_ & IGnssCallback::Capabilities::SCHEDULING);
515     }
516 }
517 
518 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(GnssHalTest);
519 INSTANTIATE_TEST_SUITE_P(
520         PerInstance, GnssHalTest,
521         testing::ValuesIn(android::hardware::getAllHalInstanceNames(IGnss::descriptor)),
522         android::hardware::PrintInstanceNameToString);
523 
main(int argc,char ** argv)524 int main(int argc, char** argv) {
525   ::testing::InitGoogleTest(&argc, argv);
526   /*
527    * These arguments not used by automated VTS testing.
528    * Only for use in manual testing, when wanting to run
529    * stronger tests that require the presence of GPS signal.
530    */
531   for (int i = 1; i < argc; i++) {
532     if (strcmp(argv[i], "-agps") == 0) {
533         sAgpsIsPresent = true;
534     } else if (strcmp(argv[i], "-weak") == 0) {
535         sSignalIsWeak = true;
536     }
537   }
538 
539   return RUN_ALL_TESTS();
540 }
541