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