1 /*
2  * Copyright (C) 2008 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 "GnssLocationProvider"
18 
19 #define LOG_NDEBUG 0
20 
21 #include <android/hardware/gnss/1.0/IGnss.h>
22 #include <android/hardware/gnss/1.1/IGnss.h>
23 #include <android/hardware/gnss/2.0/IGnss.h>
24 #include <android/hardware/gnss/2.1/IGnss.h>
25 
26 #include <android/hardware/gnss/1.0/IGnssMeasurement.h>
27 #include <android/hardware/gnss/1.1/IGnssMeasurement.h>
28 #include <android/hardware/gnss/2.0/IGnssMeasurement.h>
29 #include <android/hardware/gnss/2.1/IGnssAntennaInfo.h>
30 #include <android/hardware/gnss/2.1/IGnssMeasurement.h>
31 #include <android/hardware/gnss/measurement_corrections/1.0/IMeasurementCorrections.h>
32 #include <android/hardware/gnss/measurement_corrections/1.1/IMeasurementCorrections.h>
33 #include <android/hardware/gnss/visibility_control/1.0/IGnssVisibilityControl.h>
34 #include <nativehelper/JNIHelp.h>
35 #include "android_runtime/AndroidRuntime.h"
36 #include "android_runtime/Log.h"
37 #include "hardware_legacy/power.h"
38 #include "jni.h"
39 #include "utils/Log.h"
40 #include "utils/misc.h"
41 
42 #include <arpa/inet.h>
43 #include <cinttypes>
44 #include <iomanip>
45 #include <limits>
46 #include <linux/in.h>
47 #include <linux/in6.h>
48 #include <pthread.h>
49 #include <string.h>
50 #include <utils/SystemClock.h>
51 
52 static jclass class_gnssMeasurementsEvent;
53 static jclass class_gnssMeasurement;
54 static jclass class_location;
55 static jclass class_gnssNavigationMessage;
56 static jclass class_gnssClock;
57 static jclass class_gnssConfiguration_halInterfaceVersion;
58 static jclass class_gnssAntennaInfoBuilder;
59 static jclass class_phaseCenterOffset;
60 static jclass class_sphericalCorrections;
61 static jclass class_arrayList;
62 static jclass class_doubleArray;
63 
64 static jobject mCallbacksObj = nullptr;
65 
66 static jmethodID method_reportLocation;
67 static jmethodID method_reportStatus;
68 static jmethodID method_reportSvStatus;
69 static jmethodID method_reportAGpsStatus;
70 static jmethodID method_reportNmea;
71 static jmethodID method_setTopHalCapabilities;
72 static jmethodID method_setGnssYearOfHardware;
73 static jmethodID method_setGnssHardwareModelName;
74 static jmethodID method_psdsDownloadRequest;
75 static jmethodID method_reportNiNotification;
76 static jmethodID method_requestLocation;
77 static jmethodID method_requestRefLocation;
78 static jmethodID method_requestSetID;
79 static jmethodID method_requestUtcTime;
80 static jmethodID method_reportGeofenceTransition;
81 static jmethodID method_reportGeofenceStatus;
82 static jmethodID method_reportGeofenceAddStatus;
83 static jmethodID method_reportGeofenceRemoveStatus;
84 static jmethodID method_reportGeofencePauseStatus;
85 static jmethodID method_reportGeofenceResumeStatus;
86 static jmethodID method_reportMeasurementData;
87 static jmethodID method_reportAntennaInfo;
88 static jmethodID method_reportNavigationMessages;
89 static jmethodID method_reportLocationBatch;
90 static jmethodID method_reportGnssServiceDied;
91 static jmethodID method_setSubHalMeasurementCorrectionsCapabilities;
92 static jmethodID method_correctionsGetLatitudeDegrees;
93 static jmethodID method_correctionsGetLongitudeDegrees;
94 static jmethodID method_correctionsGetAltitudeMeters;
95 static jmethodID method_correctionsGetHorPosUncMeters;
96 static jmethodID method_correctionsGetVerPosUncMeters;
97 static jmethodID method_correctionsGetToaGpsNanosecondsOfWeek;
98 static jmethodID method_correctionsGetSingleSatCorrectionList;
99 static jmethodID method_correctionsHasEnvironmentBearing;
100 static jmethodID method_correctionsGetEnvironmentBearingDegrees;
101 static jmethodID method_correctionsGetEnvironmentBearingUncertaintyDegrees;
102 static jmethodID method_listSize;
103 static jmethodID method_correctionListGet;
104 static jmethodID method_correctionSatFlags;
105 static jmethodID method_correctionSatConstType;
106 static jmethodID method_correctionSatId;
107 static jmethodID method_correctionSatCarrierFreq;
108 static jmethodID method_correctionSatIsLosProb;
109 static jmethodID method_correctionSatEpl;
110 static jmethodID method_correctionSatEplUnc;
111 static jmethodID method_correctionSatRefPlane;
112 static jmethodID method_correctionPlaneLatDeg;
113 static jmethodID method_correctionPlaneLngDeg;
114 static jmethodID method_correctionPlaneAltDeg;
115 static jmethodID method_correctionPlaneAzimDeg;
116 static jmethodID method_reportNfwNotification;
117 static jmethodID method_isInEmergencySession;
118 static jmethodID method_gnssMeasurementsEventCtor;
119 static jmethodID method_locationCtor;
120 static jmethodID method_gnssNavigationMessageCtor;
121 static jmethodID method_gnssClockCtor;
122 static jmethodID method_gnssMeasurementCtor;
123 static jmethodID method_halInterfaceVersionCtor;
124 static jmethodID method_gnssAntennaInfoBuilderCtor;
125 static jmethodID method_phaseCenterOffsetCtor;
126 static jmethodID method_sphericalCorrectionsCtor;
127 static jmethodID method_arrayListCtor;
128 static jmethodID method_arrayListAdd;
129 static jmethodID method_gnssAntennaInfoBuilderSetCarrierFrequencyMHz;
130 static jmethodID method_gnssAntennaInfoBuilderSetPhaseCenterOffset;
131 static jmethodID method_gnssAntennaInfoBuilderSetPhaseCenterVariationCorrections;
132 static jmethodID method_gnssAntennaInfoBuilderSetSignalGainCorrections;
133 static jmethodID method_gnssAntennaInfoBuilderBuild;
134 
135 /*
136  * Save a pointer to JavaVm to attach/detach threads executing
137  * callback methods that need to make JNI calls.
138  */
139 static JavaVM* sJvm;
140 
141 using android::OK;
142 using android::sp;
143 using android::wp;
144 using android::status_t;
145 using android::String16;
146 
147 using android::hardware::Return;
148 using android::hardware::Void;
149 using android::hardware::hidl_vec;
150 using android::hardware::hidl_string;
151 using android::hardware::hidl_death_recipient;
152 
153 using android::hardware::gnss::V1_0::GnssLocationFlags;
154 using android::hardware::gnss::V1_0::IAGnssRilCallback;
155 using android::hardware::gnss::V1_0::IGnssGeofenceCallback;
156 using android::hardware::gnss::V1_0::IGnssGeofencing;
157 using android::hardware::gnss::V1_0::IGnssNavigationMessage;
158 using android::hardware::gnss::V1_0::IGnssNavigationMessageCallback;
159 using android::hardware::gnss::V1_0::IGnssNi;
160 using android::hardware::gnss::V1_0::IGnssNiCallback;
161 using android::hardware::gnss::V1_0::IGnssXtra;
162 using android::hardware::gnss::V1_0::IGnssXtraCallback;
163 
164 using android::hardware::gnss::V2_0::ElapsedRealtimeFlags;
165 
166 using MeasurementCorrections_V1_0 = android::hardware::gnss::measurement_corrections::V1_0::MeasurementCorrections;
167 using MeasurementCorrections_V1_1 = android::hardware::gnss::measurement_corrections::V1_1::MeasurementCorrections;
168 
169 using SingleSatCorrection_V1_0 =
170         android::hardware::gnss::measurement_corrections::V1_0::SingleSatCorrection;
171 using SingleSatCorrection_V1_1 =
172         android::hardware::gnss::measurement_corrections::V1_1::SingleSatCorrection;
173 using android::hardware::gnss::measurement_corrections::V1_0::ReflectingPlane;
174 
175 using android::hidl::base::V1_0::IBase;
176 
177 using GnssConstellationType_V1_0 = android::hardware::gnss::V1_0::GnssConstellationType;
178 using GnssConstellationType_V2_0 = android::hardware::gnss::V2_0::GnssConstellationType;
179 using GnssLocation_V1_0 = android::hardware::gnss::V1_0::GnssLocation;
180 using GnssLocation_V2_0 = android::hardware::gnss::V2_0::GnssLocation;
181 using IGnss_V1_0 = android::hardware::gnss::V1_0::IGnss;
182 using IGnss_V1_1 = android::hardware::gnss::V1_1::IGnss;
183 using IGnss_V2_0 = android::hardware::gnss::V2_0::IGnss;
184 using IGnss_V2_1 = android::hardware::gnss::V2_1::IGnss;
185 using IGnssCallback_V1_0 = android::hardware::gnss::V1_0::IGnssCallback;
186 using IGnssCallback_V2_0 = android::hardware::gnss::V2_0::IGnssCallback;
187 using IGnssCallback_V2_1 = android::hardware::gnss::V2_1::IGnssCallback;
188 using IGnssConfiguration_V1_0 = android::hardware::gnss::V1_0::IGnssConfiguration;
189 using IGnssConfiguration_V1_1 = android::hardware::gnss::V1_1::IGnssConfiguration;
190 using IGnssConfiguration_V2_0 = android::hardware::gnss::V2_0::IGnssConfiguration;
191 using IGnssConfiguration_V2_1 = android::hardware::gnss::V2_1::IGnssConfiguration;
192 using IGnssDebug_V1_0 = android::hardware::gnss::V1_0::IGnssDebug;
193 using IGnssDebug_V2_0 = android::hardware::gnss::V2_0::IGnssDebug;
194 using IGnssAntennaInfo = android::hardware::gnss::V2_1::IGnssAntennaInfo;
195 using IGnssAntennaInfoCallback = android::hardware::gnss::V2_1::IGnssAntennaInfoCallback;
196 using IGnssMeasurement_V1_0 = android::hardware::gnss::V1_0::IGnssMeasurement;
197 using IGnssMeasurement_V1_1 = android::hardware::gnss::V1_1::IGnssMeasurement;
198 using IGnssMeasurement_V2_0 = android::hardware::gnss::V2_0::IGnssMeasurement;
199 using IGnssMeasurement_V2_1 = android::hardware::gnss::V2_1::IGnssMeasurement;
200 using IGnssMeasurementCallback_V1_0 = android::hardware::gnss::V1_0::IGnssMeasurementCallback;
201 using IGnssMeasurementCallback_V1_1 = android::hardware::gnss::V1_1::IGnssMeasurementCallback;
202 using IGnssMeasurementCallback_V2_0 = android::hardware::gnss::V2_0::IGnssMeasurementCallback;
203 using IGnssMeasurementCallback_V2_1 = android::hardware::gnss::V2_1::IGnssMeasurementCallback;
204 using IAGnssRil_V1_0 = android::hardware::gnss::V1_0::IAGnssRil;
205 using IAGnssRil_V2_0 = android::hardware::gnss::V2_0::IAGnssRil;
206 using IAGnss_V1_0 = android::hardware::gnss::V1_0::IAGnss;
207 using IAGnss_V2_0 = android::hardware::gnss::V2_0::IAGnss;
208 using IAGnssCallback_V1_0 = android::hardware::gnss::V1_0::IAGnssCallback;
209 using IAGnssCallback_V2_0 = android::hardware::gnss::V2_0::IAGnssCallback;
210 using IGnssBatching_V1_0 = android::hardware::gnss::V1_0::IGnssBatching;
211 using IGnssBatching_V2_0 = android::hardware::gnss::V2_0::IGnssBatching;
212 using IGnssBatchingCallback_V1_0 = android::hardware::gnss::V1_0::IGnssBatchingCallback;
213 using IGnssBatchingCallback_V2_0 = android::hardware::gnss::V2_0::IGnssBatchingCallback;
214 
215 using IMeasurementCorrections_V1_0 = android::hardware::gnss::measurement_corrections::V1_0::IMeasurementCorrections;
216 using IMeasurementCorrections_V1_1 = android::hardware::gnss::measurement_corrections::V1_1::IMeasurementCorrections;
217 using android::hardware::gnss::measurement_corrections::V1_0::IMeasurementCorrectionsCallback;
218 using android::hardware::gnss::measurement_corrections::V1_0::GnssSingleSatCorrectionFlags;
219 
220 using android::hardware::gnss::visibility_control::V1_0::IGnssVisibilityControl;
221 using android::hardware::gnss::visibility_control::V1_0::IGnssVisibilityControlCallback;
222 
223 struct GnssDeathRecipient : virtual public hidl_death_recipient
224 {
225     // hidl_death_recipient interface
serviceDiedGnssDeathRecipient226     virtual void serviceDied(uint64_t cookie, const wp<IBase>& who) override {
227         ALOGE("IGNSS hidl service failed, trying to recover...");
228 
229         JNIEnv* env = android::AndroidRuntime::getJNIEnv();
230         env->CallVoidMethod(mCallbacksObj, method_reportGnssServiceDied);
231     }
232 };
233 
234 // Must match the value from GnssMeasurement.java
235 static const uint32_t ADR_STATE_HALF_CYCLE_REPORTED = (1<<4);
236 static const uint32_t SVID_FLAGS_HAS_BASEBAND_CN0 = (1<<4);
237 
238 sp<GnssDeathRecipient> gnssHalDeathRecipient = nullptr;
239 sp<IGnss_V1_0> gnssHal = nullptr;
240 sp<IGnss_V1_1> gnssHal_V1_1 = nullptr;
241 sp<IGnss_V2_0> gnssHal_V2_0 = nullptr;
242 sp<IGnss_V2_1> gnssHal_V2_1 = nullptr;
243 sp<IGnssXtra> gnssXtraIface = nullptr;
244 sp<IAGnssRil_V1_0> agnssRilIface = nullptr;
245 sp<IAGnssRil_V2_0> agnssRilIface_V2_0 = nullptr;
246 sp<IGnssGeofencing> gnssGeofencingIface = nullptr;
247 sp<IAGnss_V1_0> agnssIface = nullptr;
248 sp<IAGnss_V2_0> agnssIface_V2_0 = nullptr;
249 sp<IGnssBatching_V1_0> gnssBatchingIface = nullptr;
250 sp<IGnssBatching_V2_0> gnssBatchingIface_V2_0 = nullptr;
251 sp<IGnssDebug_V1_0> gnssDebugIface = nullptr;
252 sp<IGnssDebug_V2_0> gnssDebugIface_V2_0 = nullptr;
253 sp<IGnssConfiguration_V1_0> gnssConfigurationIface = nullptr;
254 sp<IGnssConfiguration_V1_1> gnssConfigurationIface_V1_1 = nullptr;
255 sp<IGnssConfiguration_V2_0> gnssConfigurationIface_V2_0 = nullptr;
256 sp<IGnssConfiguration_V2_1> gnssConfigurationIface_V2_1 = nullptr;
257 sp<IGnssNi> gnssNiIface = nullptr;
258 sp<IGnssMeasurement_V1_0> gnssMeasurementIface = nullptr;
259 sp<IGnssMeasurement_V1_1> gnssMeasurementIface_V1_1 = nullptr;
260 sp<IGnssMeasurement_V2_0> gnssMeasurementIface_V2_0 = nullptr;
261 sp<IGnssMeasurement_V2_1> gnssMeasurementIface_V2_1 = nullptr;
262 sp<IGnssNavigationMessage> gnssNavigationMessageIface = nullptr;
263 sp<IMeasurementCorrections_V1_0> gnssCorrectionsIface_V1_0 = nullptr;
264 sp<IMeasurementCorrections_V1_1> gnssCorrectionsIface_V1_1 = nullptr;
265 sp<IGnssVisibilityControl> gnssVisibilityControlIface = nullptr;
266 sp<IGnssAntennaInfo> gnssAntennaInfoIface = nullptr;
267 
268 #define WAKE_LOCK_NAME  "GPS"
269 
270 namespace android {
271 
272 namespace {
273 
274 // Returns true if location has lat/long information.
hasLatLong(const GnssLocation_V1_0 & location)275 bool hasLatLong(const GnssLocation_V1_0& location) {
276     return (static_cast<uint32_t>(location.gnssLocationFlags) &
277             GnssLocationFlags::HAS_LAT_LONG) != 0;
278 }
279 
280 // Returns true if location has lat/long information.
hasLatLong(const GnssLocation_V2_0 & location)281 bool hasLatLong(const GnssLocation_V2_0& location) {
282     return hasLatLong(location.v1_0);
283 }
284 
285 }  // namespace
286 template<class T>
287 class JavaMethodHelper {
288  public:
289     // Helper function to call setter on a Java object.
290     static void callJavaMethod(
291            JNIEnv* env,
292            jclass clazz,
293            jobject object,
294            const char* method_name,
295            T value);
296 
297  private:
298     static const char* const signature_;
299 };
300 
301 template<class T>
callJavaMethod(JNIEnv * env,jclass clazz,jobject object,const char * method_name,T value)302 void JavaMethodHelper<T>::callJavaMethod(
303         JNIEnv* env,
304         jclass clazz,
305         jobject object,
306         const char* method_name,
307         T value) {
308     jmethodID method = env->GetMethodID(clazz, method_name, signature_);
309     env->CallVoidMethod(object, method, value);
310 }
311 
312 class JavaObject {
313  public:
314     JavaObject(JNIEnv* env, jclass clazz, jmethodID defaultCtor);
315     JavaObject(JNIEnv* env, jclass clazz, jmethodID stringCtor, const char * sz_arg_1);
316     JavaObject(JNIEnv* env, jclass clazz, jobject object);
317 
318     virtual ~JavaObject() = default;
319 
320     template<class T>
321     void callSetter(const char* method_name, T value);
322     template<class T>
323     void callSetter(const char* method_name, T* value, size_t size);
324     jobject get();
325 
326  private:
327     JNIEnv* env_;
328     jclass clazz_;
329     jobject object_;
330 };
331 
JavaObject(JNIEnv * env,jclass clazz,jmethodID defaultCtor)332 JavaObject::JavaObject(JNIEnv* env, jclass clazz, jmethodID defaultCtor) : env_(env),
333         clazz_(clazz) {
334     object_ = env_->NewObject(clazz_, defaultCtor);
335 }
336 
337 
JavaObject(JNIEnv * env,jclass clazz,jmethodID stringCtor,const char * sz_arg_1)338 JavaObject::JavaObject(JNIEnv* env, jclass clazz, jmethodID stringCtor, const char * sz_arg_1)
339         : env_(env), clazz_(clazz) {
340     jstring szArg = env->NewStringUTF(sz_arg_1);
341     object_ = env_->NewObject(clazz_, stringCtor, szArg);
342     if (szArg) {
343         env_->DeleteLocalRef(szArg);
344     }
345 }
346 
347 
JavaObject(JNIEnv * env,jclass clazz,jobject object)348 JavaObject::JavaObject(JNIEnv* env, jclass clazz, jobject object)
349     : env_(env), clazz_(clazz), object_(object) {
350 }
351 
352 template<class T>
callSetter(const char * method_name,T value)353 void JavaObject::callSetter(const char* method_name, T value) {
354     JavaMethodHelper<T>::callJavaMethod(
355             env_, clazz_, object_, method_name, value);
356 }
357 
358 template<>
callSetter(const char * method_name,uint8_t * value,size_t size)359 void JavaObject::callSetter(
360         const char* method_name, uint8_t* value, size_t size) {
361     jbyteArray array = env_->NewByteArray(size);
362     env_->SetByteArrayRegion(array, 0, size, reinterpret_cast<jbyte*>(value));
363     jmethodID method = env_->GetMethodID(
364             clazz_,
365             method_name,
366             "([B)V");
367     env_->CallVoidMethod(object_, method, array);
368     env_->DeleteLocalRef(array);
369 }
370 
get()371 jobject JavaObject::get() {
372     return object_;
373 }
374 
375 // Define Java method signatures for all known types.
376 template<>
377 const char *const JavaMethodHelper<uint8_t>::signature_ = "(B)V";
378 template<>
379 const char *const JavaMethodHelper<int8_t>::signature_ = "(B)V";
380 template<>
381 const char *const JavaMethodHelper<int16_t>::signature_ = "(S)V";
382 template<>
383 const char *const JavaMethodHelper<uint16_t>::signature_ = "(S)V";
384 template<>
385 const char *const JavaMethodHelper<int32_t>::signature_ = "(I)V";
386 template<>
387 const char *const JavaMethodHelper<uint32_t>::signature_ = "(I)V";
388 template<>
389 const char *const JavaMethodHelper<int64_t>::signature_ = "(J)V";
390 template<>
391 const char *const JavaMethodHelper<uint64_t>::signature_ = "(J)V";
392 template<>
393 const char *const JavaMethodHelper<float>::signature_ = "(F)V";
394 template<>
395 const char *const JavaMethodHelper<double>::signature_ = "(D)V";
396 template<>
397 const char *const JavaMethodHelper<bool>::signature_ = "(Z)V";
398 template<>
399 const char *const JavaMethodHelper<jstring>::signature_ = "(Ljava/lang/String;)V";
400 
401 #define SET(setter, value) object.callSetter("set" # setter, (value))
402 
boolToJbool(bool value)403 static inline jboolean boolToJbool(bool value) {
404     return value ? JNI_TRUE : JNI_FALSE;
405 }
406 
407 template<class T>
logHidlError(Return<T> & result,const char * errorMessage)408 static inline void logHidlError(Return<T>& result, const char* errorMessage) {
409     ALOGE("%s HIDL transport error: %s", errorMessage, result.description().c_str());
410 }
411 
412 template<class T>
checkHidlReturn(Return<T> & result,const char * errorMessage)413 static jboolean checkHidlReturn(Return<T>& result, const char* errorMessage) {
414     if (!result.isOk()) {
415         logHidlError(result, errorMessage);
416         return JNI_FALSE;
417     } else {
418         return JNI_TRUE;
419     }
420 }
421 
checkHidlReturn(Return<bool> & result,const char * errorMessage)422 static jboolean checkHidlReturn(Return<bool>& result, const char* errorMessage) {
423     if (!result.isOk()) {
424         logHidlError(result, errorMessage);
425         return JNI_FALSE;
426     } else if (!result) {
427         ALOGE("%s", errorMessage);
428         return JNI_FALSE;
429     } else {
430         return JNI_TRUE;
431     }
432 }
433 
checkAndClearExceptionFromCallback(JNIEnv * env,const char * methodName)434 static void checkAndClearExceptionFromCallback(JNIEnv* env, const char* methodName) {
435     if (env->ExceptionCheck()) {
436         ALOGE("An exception was thrown by callback '%s'.", methodName);
437         LOGE_EX(env);
438         env->ExceptionClear();
439     }
440 }
441 
createHalInterfaceVersionJavaObject(JNIEnv * env,jint major,jint minor)442 static jobject createHalInterfaceVersionJavaObject(JNIEnv* env, jint major, jint minor) {
443     jobject version = env->NewObject(class_gnssConfiguration_halInterfaceVersion,
444             method_halInterfaceVersionCtor, major, minor);
445     return version;
446 }
447 
448 struct ScopedJniString {
ScopedJniStringandroid::ScopedJniString449     ScopedJniString(JNIEnv* env, jstring javaString) : mEnv(env), mJavaString(javaString) {
450         mNativeString = mEnv->GetStringUTFChars(mJavaString, nullptr);
451     }
452 
~ScopedJniStringandroid::ScopedJniString453     ~ScopedJniString() {
454         if (mNativeString != nullptr) {
455             mEnv->ReleaseStringUTFChars(mJavaString, mNativeString);
456         }
457     }
458 
c_strandroid::ScopedJniString459     const char* c_str() const {
460         return mNativeString;
461     }
462 
operator hidl_stringandroid::ScopedJniString463     operator hidl_string() const {
464         return hidl_string(mNativeString);
465     }
466 
467 private:
468     ScopedJniString(const ScopedJniString&) = delete;
469     ScopedJniString& operator=(const ScopedJniString&) = delete;
470 
471     JNIEnv* mEnv;
472     jstring mJavaString;
473     const char* mNativeString;
474 };
475 
476 class ScopedJniThreadAttach {
477 public:
ScopedJniThreadAttach()478     ScopedJniThreadAttach() {
479         /*
480          * attachResult will also be JNI_OK if the thead was already attached to
481          * JNI before the call to AttachCurrentThread().
482          */
483         jint attachResult = sJvm->AttachCurrentThread(&mEnv, nullptr);
484         LOG_ALWAYS_FATAL_IF(attachResult != JNI_OK, "Unable to attach thread. Error %d",
485                             attachResult);
486     }
487 
~ScopedJniThreadAttach()488     ~ScopedJniThreadAttach() {
489         jint detachResult = sJvm->DetachCurrentThread();
490         /*
491          * Return if the thread was already detached. Log error for any other
492          * failure.
493          */
494         if (detachResult == JNI_EDETACHED) {
495             return;
496         }
497 
498         LOG_ALWAYS_FATAL_IF(detachResult != JNI_OK, "Unable to detach thread. Error %d",
499                             detachResult);
500     }
501 
getEnv()502     JNIEnv* getEnv() {
503         /*
504          * Checking validity of mEnv in case the thread was detached elsewhere.
505          */
506         LOG_ALWAYS_FATAL_IF(AndroidRuntime::getJNIEnv() != mEnv);
507         return mEnv;
508     }
509 
510 private:
511     JNIEnv* mEnv = nullptr;
512 };
513 
514 thread_local std::unique_ptr<ScopedJniThreadAttach> tJniThreadAttacher;
515 
getJniEnv()516 static JNIEnv* getJniEnv() {
517     JNIEnv* env = AndroidRuntime::getJNIEnv();
518 
519     /*
520      * If env is nullptr, the thread is not already attached to
521      * JNI. It is attached below and the destructor for ScopedJniThreadAttach
522      * will detach it on thread exit.
523      */
524     if (env == nullptr) {
525         tJniThreadAttacher.reset(new ScopedJniThreadAttach());
526         env = tJniThreadAttacher->getEnv();
527     }
528 
529     return env;
530 }
531 
translateGnssLocation(JNIEnv * env,const GnssLocation_V1_0 & location)532 static jobject translateGnssLocation(JNIEnv* env,
533                                      const GnssLocation_V1_0& location) {
534     JavaObject object(env, class_location, method_locationCtor, "gps");
535 
536     uint16_t flags = static_cast<uint32_t>(location.gnssLocationFlags);
537     if (flags & GnssLocationFlags::HAS_LAT_LONG) {
538         SET(Latitude, location.latitudeDegrees);
539         SET(Longitude, location.longitudeDegrees);
540     }
541     if (flags & GnssLocationFlags::HAS_ALTITUDE) {
542         SET(Altitude, location.altitudeMeters);
543     }
544     if (flags & GnssLocationFlags::HAS_SPEED) {
545         SET(Speed, location.speedMetersPerSec);
546     }
547     if (flags & GnssLocationFlags::HAS_BEARING) {
548         SET(Bearing, location.bearingDegrees);
549     }
550     if (flags & GnssLocationFlags::HAS_HORIZONTAL_ACCURACY) {
551         SET(Accuracy, location.horizontalAccuracyMeters);
552     }
553     if (flags & GnssLocationFlags::HAS_VERTICAL_ACCURACY) {
554         SET(VerticalAccuracyMeters, location.verticalAccuracyMeters);
555     }
556     if (flags & GnssLocationFlags::HAS_SPEED_ACCURACY) {
557         SET(SpeedAccuracyMetersPerSecond, location.speedAccuracyMetersPerSecond);
558     }
559     if (flags & GnssLocationFlags::HAS_BEARING_ACCURACY) {
560         SET(BearingAccuracyDegrees, location.bearingAccuracyDegrees);
561     }
562     SET(Time, location.timestamp);
563     SET(ElapsedRealtimeNanos, android::elapsedRealtimeNano());
564 
565     return object.get();
566 }
567 
translateGnssLocation(JNIEnv * env,const GnssLocation_V2_0 & location)568 static jobject translateGnssLocation(JNIEnv* env,
569                                      const GnssLocation_V2_0& location) {
570     JavaObject object(env, class_location, translateGnssLocation(env, location.v1_0));
571 
572     const uint16_t flags = static_cast<uint16_t>(location.elapsedRealtime.flags);
573 
574     // Overwrite ElapsedRealtimeNanos when available from HAL.
575     if (flags & ElapsedRealtimeFlags::HAS_TIMESTAMP_NS) {
576         SET(ElapsedRealtimeNanos, location.elapsedRealtime.timestampNs);
577     }
578 
579     if (flags & ElapsedRealtimeFlags::HAS_TIME_UNCERTAINTY_NS) {
580         SET(ElapsedRealtimeUncertaintyNanos, static_cast<double>(location.elapsedRealtime.timeUncertaintyNs));
581     }
582 
583     return object.get();
584 }
585 
createGnssLocation_V1_0(jint gnssLocationFlags,jdouble latitudeDegrees,jdouble longitudeDegrees,jdouble altitudeMeters,jfloat speedMetersPerSec,jfloat bearingDegrees,jfloat horizontalAccuracyMeters,jfloat verticalAccuracyMeters,jfloat speedAccuracyMetersPerSecond,jfloat bearingAccuracyDegrees,jlong timestamp)586 static GnssLocation_V1_0 createGnssLocation_V1_0(
587         jint gnssLocationFlags, jdouble latitudeDegrees, jdouble longitudeDegrees,
588         jdouble altitudeMeters, jfloat speedMetersPerSec, jfloat bearingDegrees,
589         jfloat horizontalAccuracyMeters, jfloat verticalAccuracyMeters,
590         jfloat speedAccuracyMetersPerSecond, jfloat bearingAccuracyDegrees,
591         jlong timestamp) {
592     GnssLocation_V1_0 location;
593     location.gnssLocationFlags = static_cast<uint16_t>(gnssLocationFlags);
594     location.latitudeDegrees = static_cast<double>(latitudeDegrees);
595     location.longitudeDegrees = static_cast<double>(longitudeDegrees);
596     location.altitudeMeters = static_cast<double>(altitudeMeters);
597     location.speedMetersPerSec = static_cast<float>(speedMetersPerSec);
598     location.bearingDegrees = static_cast<float>(bearingDegrees);
599     location.horizontalAccuracyMeters = static_cast<float>(horizontalAccuracyMeters);
600     location.verticalAccuracyMeters = static_cast<float>(verticalAccuracyMeters);
601     location.speedAccuracyMetersPerSecond = static_cast<float>(speedAccuracyMetersPerSecond);
602     location.bearingAccuracyDegrees = static_cast<float>(bearingAccuracyDegrees);
603     location.timestamp = static_cast<uint64_t>(timestamp);
604 
605     return location;
606 }
607 
createGnssLocation_V2_0(jint gnssLocationFlags,jdouble latitudeDegrees,jdouble longitudeDegrees,jdouble altitudeMeters,jfloat speedMetersPerSec,jfloat bearingDegrees,jfloat horizontalAccuracyMeters,jfloat verticalAccuracyMeters,jfloat speedAccuracyMetersPerSecond,jfloat bearingAccuracyDegrees,jlong timestamp,jint elapsedRealtimeFlags,jlong elapsedRealtimeNanos,jdouble elapsedRealtimeUncertaintyNanos)608 static GnssLocation_V2_0 createGnssLocation_V2_0(
609         jint gnssLocationFlags, jdouble latitudeDegrees, jdouble longitudeDegrees,
610         jdouble altitudeMeters, jfloat speedMetersPerSec, jfloat bearingDegrees,
611         jfloat horizontalAccuracyMeters, jfloat verticalAccuracyMeters,
612         jfloat speedAccuracyMetersPerSecond, jfloat bearingAccuracyDegrees,
613         jlong timestamp, jint elapsedRealtimeFlags, jlong elapsedRealtimeNanos,
614         jdouble elapsedRealtimeUncertaintyNanos) {
615     GnssLocation_V2_0 location;
616     location.v1_0 = createGnssLocation_V1_0(
617             gnssLocationFlags, latitudeDegrees, longitudeDegrees, altitudeMeters,
618             speedMetersPerSec, bearingDegrees, horizontalAccuracyMeters,
619             verticalAccuracyMeters, speedAccuracyMetersPerSecond,
620             bearingAccuracyDegrees, timestamp);
621 
622     location.elapsedRealtime.flags = static_cast<uint16_t>(elapsedRealtimeFlags);
623     location.elapsedRealtime.timestampNs = static_cast<uint64_t>(elapsedRealtimeNanos);
624     location.elapsedRealtime.timeUncertaintyNs = static_cast<uint64_t>(elapsedRealtimeUncertaintyNanos);
625 
626     return location;
627 }
628 
629 /*
630  * GnssCallback class implements the callback methods for IGnss interface.
631  */
632 struct GnssCallback : public IGnssCallback_V2_1 {
633     Return<void> gnssLocationCb(const GnssLocation_V1_0& location) override;
634     Return<void> gnssStatusCb(const IGnssCallback_V1_0::GnssStatusValue status) override;
gnssSvStatusCbandroid::GnssCallback635     Return<void> gnssSvStatusCb(const IGnssCallback_V1_0::GnssSvStatus& svStatus) override {
636         return gnssSvStatusCbImpl(svStatus);
637     }
638     Return<void> gnssNmeaCb(int64_t timestamp, const android::hardware::hidl_string& nmea) override;
639     Return<void> gnssSetCapabilitesCb(uint32_t capabilities) override;
640     Return<void> gnssAcquireWakelockCb() override;
641     Return<void> gnssReleaseWakelockCb() override;
642     Return<void> gnssRequestTimeCb() override;
643     Return<void> gnssRequestLocationCb(const bool independentFromGnss) override;
644 
645     Return<void> gnssSetSystemInfoCb(const IGnssCallback_V1_0::GnssSystemInfo& info) override;
646 
647     // New in 1.1
648     Return<void> gnssNameCb(const android::hardware::hidl_string& name) override;
649 
650     // New in 2.0
651     Return<void> gnssRequestLocationCb_2_0(const bool independentFromGnss, const bool isUserEmergency)
652             override;
653     Return<void> gnssSetCapabilitiesCb_2_0(uint32_t capabilities) override;
654     Return<void> gnssLocationCb_2_0(const GnssLocation_V2_0& location) override;
gnssSvStatusCb_2_0android::GnssCallback655     Return<void> gnssSvStatusCb_2_0(const hidl_vec<IGnssCallback_V2_0::GnssSvInfo>& svInfoList) override {
656         return gnssSvStatusCbImpl(svInfoList);
657     }
658 
659     // New in 2.1
gnssSvStatusCb_2_1android::GnssCallback660     Return<void> gnssSvStatusCb_2_1(const hidl_vec<IGnssCallback_V2_1::GnssSvInfo>& svInfoList) override {
661         return gnssSvStatusCbImpl(svInfoList);
662     }
663     Return<void> gnssSetCapabilitiesCb_2_1(uint32_t capabilities) override;
664 
665     // TODO: Reconsider allocation cost vs threadsafety on these statics
666     static const char* sNmeaString;
667     static size_t sNmeaStringLength;
668 private:
669     template<class T>
670     Return<void> gnssLocationCbImpl(const T& location);
671 
672     template<class T>
673     Return<void> gnssSvStatusCbImpl(const T& svStatus);
674 
675     template<class T>
getHasBasebandCn0DbHzFlagandroid::GnssCallback676     uint32_t getHasBasebandCn0DbHzFlag(const T& svStatus) {
677         return 0;
678     }
679 
680     template<class T>
getBasebandCn0DbHzandroid::GnssCallback681     double getBasebandCn0DbHz(const T& svStatus, size_t i) {
682         return 0.0;
683     }
684 
getGnssSvInfoListSizeandroid::GnssCallback685     uint32_t getGnssSvInfoListSize(const IGnssCallback_V1_0::GnssSvStatus& svStatus) {
686         return svStatus.numSvs;
687     }
688 
getGnssSvInfoListSizeandroid::GnssCallback689     uint32_t getGnssSvInfoListSize(const hidl_vec<IGnssCallback_V2_0::GnssSvInfo>& svInfoList) {
690         return svInfoList.size();
691     }
692 
getGnssSvInfoListSizeandroid::GnssCallback693     uint32_t getGnssSvInfoListSize(const hidl_vec<IGnssCallback_V2_1::GnssSvInfo>& svInfoList) {
694         return svInfoList.size();
695     }
696 
getGnssSvInfoOfIndexandroid::GnssCallback697     const IGnssCallback_V1_0::GnssSvInfo& getGnssSvInfoOfIndex(
698             const IGnssCallback_V1_0::GnssSvStatus& svStatus, size_t i) {
699         return svStatus.gnssSvList.data()[i];
700     }
701 
getGnssSvInfoOfIndexandroid::GnssCallback702     const IGnssCallback_V1_0::GnssSvInfo& getGnssSvInfoOfIndex(
703             const hidl_vec<IGnssCallback_V2_0::GnssSvInfo>& svInfoList, size_t i) {
704         return svInfoList[i].v1_0;
705     }
706 
getGnssSvInfoOfIndexandroid::GnssCallback707     const IGnssCallback_V1_0::GnssSvInfo& getGnssSvInfoOfIndex(
708             const hidl_vec<IGnssCallback_V2_1::GnssSvInfo>& svInfoList, size_t i) {
709         return svInfoList[i].v2_0.v1_0;
710     }
711 
getConstellationTypeandroid::GnssCallback712     uint32_t getConstellationType(const IGnssCallback_V1_0::GnssSvStatus& svStatus, size_t i) {
713         return static_cast<uint32_t>(svStatus.gnssSvList.data()[i].constellation);
714     }
715 
getConstellationTypeandroid::GnssCallback716     uint32_t getConstellationType(const hidl_vec<IGnssCallback_V2_0::GnssSvInfo>& svInfoList, size_t i) {
717         return static_cast<uint32_t>(svInfoList[i].constellation);
718     }
719 
getConstellationTypeandroid::GnssCallback720     uint32_t getConstellationType(const hidl_vec<IGnssCallback_V2_1::GnssSvInfo>& svInfoList, size_t i) {
721         return static_cast<uint32_t>(svInfoList[i].v2_0.constellation);
722     }
723 };
724 
gnssNameCb(const android::hardware::hidl_string & name)725 Return<void> GnssCallback::gnssNameCb(const android::hardware::hidl_string& name) {
726     ALOGD("%s: name=%s\n", __func__, name.c_str());
727 
728     JNIEnv* env = getJniEnv();
729     jstring jstringName = env->NewStringUTF(name.c_str());
730     env->CallVoidMethod(mCallbacksObj, method_setGnssHardwareModelName, jstringName);
731     if (jstringName) {
732         env->DeleteLocalRef(jstringName);
733     }
734     checkAndClearExceptionFromCallback(env, __FUNCTION__);
735 
736     return Void();
737 }
738 
739 const char* GnssCallback::sNmeaString = nullptr;
740 size_t GnssCallback::sNmeaStringLength = 0;
741 
742 template<class T>
gnssLocationCbImpl(const T & location)743 Return<void> GnssCallback::gnssLocationCbImpl(const T& location) {
744     JNIEnv* env = getJniEnv();
745 
746     jobject jLocation = translateGnssLocation(env, location);
747 
748     env->CallVoidMethod(mCallbacksObj,
749                         method_reportLocation,
750                         boolToJbool(hasLatLong(location)),
751                         jLocation);
752     checkAndClearExceptionFromCallback(env, __FUNCTION__);
753     env->DeleteLocalRef(jLocation);
754     return Void();
755 }
756 
gnssLocationCb(const GnssLocation_V1_0 & location)757 Return<void> GnssCallback::gnssLocationCb(const GnssLocation_V1_0& location) {
758     return gnssLocationCbImpl<GnssLocation_V1_0>(location);
759 }
760 
761 Return<void>
gnssLocationCb_2_0(const GnssLocation_V2_0 & location)762 GnssCallback::gnssLocationCb_2_0(const GnssLocation_V2_0& location) {
763     return gnssLocationCbImpl<GnssLocation_V2_0>(location);
764 }
765 
gnssStatusCb(const IGnssCallback_V2_0::GnssStatusValue status)766 Return<void> GnssCallback::gnssStatusCb(const IGnssCallback_V2_0::GnssStatusValue status) {
767     JNIEnv* env = getJniEnv();
768     env->CallVoidMethod(mCallbacksObj, method_reportStatus, status);
769     checkAndClearExceptionFromCallback(env, __FUNCTION__);
770     return Void();
771 }
772 
773 template<>
getHasBasebandCn0DbHzFlag(const hidl_vec<IGnssCallback_V2_1::GnssSvInfo> & svStatus)774 uint32_t GnssCallback::getHasBasebandCn0DbHzFlag(const hidl_vec<IGnssCallback_V2_1::GnssSvInfo>&
775         svStatus) {
776     return SVID_FLAGS_HAS_BASEBAND_CN0;
777 }
778 
779 template<>
getBasebandCn0DbHz(const hidl_vec<IGnssCallback_V2_1::GnssSvInfo> & svInfoList,size_t i)780 double GnssCallback::getBasebandCn0DbHz(const hidl_vec<IGnssCallback_V2_1::GnssSvInfo>& svInfoList,
781         size_t i) {
782     return svInfoList[i].basebandCN0DbHz;
783 }
784 
785 template<class T>
gnssSvStatusCbImpl(const T & svStatus)786 Return<void> GnssCallback::gnssSvStatusCbImpl(const T& svStatus) {
787     JNIEnv* env = getJniEnv();
788 
789     uint32_t listSize = getGnssSvInfoListSize(svStatus);
790 
791     jintArray svidWithFlagArray = env->NewIntArray(listSize);
792     jfloatArray cn0Array = env->NewFloatArray(listSize);
793     jfloatArray elevArray = env->NewFloatArray(listSize);
794     jfloatArray azimArray = env->NewFloatArray(listSize);
795     jfloatArray carrierFreqArray = env->NewFloatArray(listSize);
796     jfloatArray basebandCn0Array = env->NewFloatArray(listSize);
797 
798     jint* svidWithFlags = env->GetIntArrayElements(svidWithFlagArray, 0);
799     jfloat* cn0s = env->GetFloatArrayElements(cn0Array, 0);
800     jfloat* elev = env->GetFloatArrayElements(elevArray, 0);
801     jfloat* azim = env->GetFloatArrayElements(azimArray, 0);
802     jfloat* carrierFreq = env->GetFloatArrayElements(carrierFreqArray, 0);
803     jfloat* basebandCn0s = env->GetFloatArrayElements(basebandCn0Array, 0);
804 
805     /*
806      * Read GNSS SV info.
807      */
808     for (size_t i = 0; i < listSize; ++i) {
809         enum ShiftWidth: uint8_t {
810             SVID_SHIFT_WIDTH = 12,
811             CONSTELLATION_TYPE_SHIFT_WIDTH = 8
812         };
813 
814         const IGnssCallback_V1_0::GnssSvInfo& info = getGnssSvInfoOfIndex(svStatus, i);
815         svidWithFlags[i] = (info.svid << SVID_SHIFT_WIDTH) |
816             (getConstellationType(svStatus, i) << CONSTELLATION_TYPE_SHIFT_WIDTH) |
817             static_cast<uint32_t>(info.svFlag);
818         cn0s[i] = info.cN0Dbhz;
819         elev[i] = info.elevationDegrees;
820         azim[i] = info.azimuthDegrees;
821         carrierFreq[i] = info.carrierFrequencyHz;
822         svidWithFlags[i] |= getHasBasebandCn0DbHzFlag(svStatus);
823         basebandCn0s[i] = getBasebandCn0DbHz(svStatus, i);
824     }
825 
826     env->ReleaseIntArrayElements(svidWithFlagArray, svidWithFlags, 0);
827     env->ReleaseFloatArrayElements(cn0Array, cn0s, 0);
828     env->ReleaseFloatArrayElements(elevArray, elev, 0);
829     env->ReleaseFloatArrayElements(azimArray, azim, 0);
830     env->ReleaseFloatArrayElements(carrierFreqArray, carrierFreq, 0);
831     env->ReleaseFloatArrayElements(basebandCn0Array, basebandCn0s, 0);
832 
833     env->CallVoidMethod(mCallbacksObj, method_reportSvStatus,
834             static_cast<jint>(listSize), svidWithFlagArray, cn0Array, elevArray, azimArray,
835             carrierFreqArray, basebandCn0Array);
836 
837     env->DeleteLocalRef(svidWithFlagArray);
838     env->DeleteLocalRef(cn0Array);
839     env->DeleteLocalRef(elevArray);
840     env->DeleteLocalRef(azimArray);
841     env->DeleteLocalRef(carrierFreqArray);
842     env->DeleteLocalRef(basebandCn0Array);
843 
844     checkAndClearExceptionFromCallback(env, __FUNCTION__);
845     return Void();
846 }
847 
gnssNmeaCb(int64_t timestamp,const::android::hardware::hidl_string & nmea)848 Return<void> GnssCallback::gnssNmeaCb(
849     int64_t timestamp, const ::android::hardware::hidl_string& nmea) {
850     JNIEnv* env = getJniEnv();
851     /*
852      * The Java code will call back to read these values.
853      * We do this to avoid creating unnecessary String objects.
854      */
855     sNmeaString = nmea.c_str();
856     sNmeaStringLength = nmea.size();
857 
858     env->CallVoidMethod(mCallbacksObj, method_reportNmea, timestamp);
859     checkAndClearExceptionFromCallback(env, __FUNCTION__);
860     return Void();
861 }
862 
gnssSetCapabilitesCb(uint32_t capabilities)863 Return<void> GnssCallback::gnssSetCapabilitesCb(uint32_t capabilities) {
864     ALOGD("%s: %du\n", __func__, capabilities);
865 
866     JNIEnv* env = getJniEnv();
867     env->CallVoidMethod(mCallbacksObj, method_setTopHalCapabilities, capabilities);
868     checkAndClearExceptionFromCallback(env, __FUNCTION__);
869     return Void();
870 }
871 
gnssSetCapabilitiesCb_2_0(uint32_t capabilities)872 Return<void> GnssCallback::gnssSetCapabilitiesCb_2_0(uint32_t capabilities) {
873     return GnssCallback::gnssSetCapabilitesCb(capabilities);
874 }
875 
gnssSetCapabilitiesCb_2_1(uint32_t capabilities)876 Return<void> GnssCallback::gnssSetCapabilitiesCb_2_1(uint32_t capabilities) {
877     return GnssCallback::gnssSetCapabilitesCb(capabilities);
878 }
879 
gnssAcquireWakelockCb()880 Return<void> GnssCallback::gnssAcquireWakelockCb() {
881     acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
882     return Void();
883 }
884 
gnssReleaseWakelockCb()885 Return<void> GnssCallback::gnssReleaseWakelockCb() {
886     release_wake_lock(WAKE_LOCK_NAME);
887     return Void();
888 }
889 
gnssRequestTimeCb()890 Return<void> GnssCallback::gnssRequestTimeCb() {
891     JNIEnv* env = getJniEnv();
892     env->CallVoidMethod(mCallbacksObj, method_requestUtcTime);
893     checkAndClearExceptionFromCallback(env, __FUNCTION__);
894     return Void();
895 }
896 
gnssRequestLocationCb(const bool independentFromGnss)897 Return<void> GnssCallback::gnssRequestLocationCb(const bool independentFromGnss) {
898     return GnssCallback::gnssRequestLocationCb_2_0(independentFromGnss, /* isUserEmergency= */
899             false);
900 }
901 
gnssRequestLocationCb_2_0(const bool independentFromGnss,const bool isUserEmergency)902 Return<void> GnssCallback::gnssRequestLocationCb_2_0(const bool independentFromGnss, const bool
903         isUserEmergency) {
904     JNIEnv* env = getJniEnv();
905     env->CallVoidMethod(mCallbacksObj, method_requestLocation, boolToJbool(independentFromGnss),
906             boolToJbool(isUserEmergency));
907     checkAndClearExceptionFromCallback(env, __FUNCTION__);
908     return Void();
909 }
910 
gnssSetSystemInfoCb(const IGnssCallback_V2_0::GnssSystemInfo & info)911 Return<void> GnssCallback::gnssSetSystemInfoCb(const IGnssCallback_V2_0::GnssSystemInfo& info) {
912     ALOGD("%s: yearOfHw=%d\n", __func__, info.yearOfHw);
913 
914     JNIEnv* env = getJniEnv();
915     env->CallVoidMethod(mCallbacksObj, method_setGnssYearOfHardware,
916                         info.yearOfHw);
917     checkAndClearExceptionFromCallback(env, __FUNCTION__);
918     return Void();
919 }
920 
921 class GnssXtraCallback : public IGnssXtraCallback {
922     Return<void> downloadRequestCb() override;
923 };
924 
925 /*
926  * GnssXtraCallback class implements the callback methods for the IGnssXtra
927  * interface.
928  */
downloadRequestCb()929 Return<void> GnssXtraCallback::downloadRequestCb() {
930     JNIEnv* env = getJniEnv();
931     env->CallVoidMethod(mCallbacksObj, method_psdsDownloadRequest);
932     checkAndClearExceptionFromCallback(env, __FUNCTION__);
933     return Void();
934 }
935 
936 /*
937  * GnssGeofenceCallback class implements the callback methods for the
938  * IGnssGeofence interface.
939  */
940 struct GnssGeofenceCallback : public IGnssGeofenceCallback {
941     // Methods from ::android::hardware::gps::V1_0::IGnssGeofenceCallback follow.
942     Return<void> gnssGeofenceTransitionCb(
943             int32_t geofenceId,
944             const GnssLocation_V1_0& location,
945             GeofenceTransition transition,
946             hardware::gnss::V1_0::GnssUtcTime timestamp) override;
947     Return<void>
948     gnssGeofenceStatusCb(
949             GeofenceAvailability status,
950             const GnssLocation_V1_0& location) override;
951     Return<void> gnssGeofenceAddCb(int32_t geofenceId,
952                                    GeofenceStatus status) override;
953     Return<void> gnssGeofenceRemoveCb(int32_t geofenceId,
954                                       GeofenceStatus status) override;
955     Return<void> gnssGeofencePauseCb(int32_t geofenceId,
956                                      GeofenceStatus status) override;
957     Return<void> gnssGeofenceResumeCb(int32_t geofenceId,
958                                       GeofenceStatus status) override;
959 };
960 
gnssGeofenceTransitionCb(int32_t geofenceId,const GnssLocation_V1_0 & location,GeofenceTransition transition,hardware::gnss::V1_0::GnssUtcTime timestamp)961 Return<void> GnssGeofenceCallback::gnssGeofenceTransitionCb(
962         int32_t geofenceId, const GnssLocation_V1_0& location,
963         GeofenceTransition transition,
964         hardware::gnss::V1_0::GnssUtcTime timestamp) {
965     JNIEnv* env = getJniEnv();
966 
967     jobject jLocation = translateGnssLocation(env, location);
968 
969     env->CallVoidMethod(mCallbacksObj,
970                         method_reportGeofenceTransition,
971                         geofenceId,
972                         jLocation,
973                         transition,
974                         timestamp);
975 
976     checkAndClearExceptionFromCallback(env, __FUNCTION__);
977     env->DeleteLocalRef(jLocation);
978     return Void();
979 }
980 
981 Return<void>
gnssGeofenceStatusCb(GeofenceAvailability status,const GnssLocation_V1_0 & location)982 GnssGeofenceCallback::gnssGeofenceStatusCb(GeofenceAvailability status,
983                                            const GnssLocation_V1_0& location) {
984     JNIEnv* env = getJniEnv();
985 
986     jobject jLocation = translateGnssLocation(env, location);
987 
988     env->CallVoidMethod(mCallbacksObj, method_reportGeofenceStatus, status,
989                         jLocation);
990     checkAndClearExceptionFromCallback(env, __FUNCTION__);
991     env->DeleteLocalRef(jLocation);
992     return Void();
993 }
994 
gnssGeofenceAddCb(int32_t geofenceId,GeofenceStatus status)995 Return<void> GnssGeofenceCallback::gnssGeofenceAddCb(int32_t geofenceId,
996                                                     GeofenceStatus status) {
997     JNIEnv* env = getJniEnv();
998     if (status != IGnssGeofenceCallback::GeofenceStatus::OPERATION_SUCCESS) {
999         ALOGE("%s: Error in adding a Geofence: %d\n", __func__, status);
1000     }
1001 
1002     env->CallVoidMethod(mCallbacksObj,
1003                         method_reportGeofenceAddStatus,
1004                         geofenceId,
1005                         status);
1006     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1007     return Void();
1008 }
1009 
gnssGeofenceRemoveCb(int32_t geofenceId,GeofenceStatus status)1010 Return<void> GnssGeofenceCallback::gnssGeofenceRemoveCb(int32_t geofenceId,
1011                                                        GeofenceStatus status) {
1012     JNIEnv* env = getJniEnv();
1013     if (status != IGnssGeofenceCallback::GeofenceStatus::OPERATION_SUCCESS) {
1014         ALOGE("%s: Error in removing a Geofence: %d\n", __func__, status);
1015     }
1016 
1017     env->CallVoidMethod(mCallbacksObj,
1018                         method_reportGeofenceRemoveStatus,
1019                         geofenceId, status);
1020     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1021     return Void();
1022 }
1023 
gnssGeofencePauseCb(int32_t geofenceId,GeofenceStatus status)1024 Return<void> GnssGeofenceCallback::gnssGeofencePauseCb(int32_t geofenceId,
1025                                                       GeofenceStatus status) {
1026     JNIEnv* env = getJniEnv();
1027     if (status != IGnssGeofenceCallback::GeofenceStatus::OPERATION_SUCCESS) {
1028         ALOGE("%s: Error in pausing Geofence: %d\n", __func__, status);
1029     }
1030 
1031     env->CallVoidMethod(mCallbacksObj,
1032                         method_reportGeofencePauseStatus,
1033                         geofenceId, status);
1034     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1035     return Void();
1036 }
1037 
gnssGeofenceResumeCb(int32_t geofenceId,GeofenceStatus status)1038 Return<void> GnssGeofenceCallback::gnssGeofenceResumeCb(int32_t geofenceId,
1039                                                        GeofenceStatus status) {
1040     JNIEnv* env = getJniEnv();
1041     if (status != IGnssGeofenceCallback::GeofenceStatus::OPERATION_SUCCESS) {
1042         ALOGE("%s: Error in resuming Geofence: %d\n", __func__, status);
1043     }
1044 
1045     env->CallVoidMethod(mCallbacksObj,
1046                         method_reportGeofenceResumeStatus,
1047                         geofenceId, status);
1048     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1049     return Void();
1050 }
1051 
1052 /*
1053  * GnssNavigationMessageCallback interface implements the callback methods
1054  * required by the IGnssNavigationMessage interface.
1055  */
1056 struct GnssNavigationMessageCallback : public IGnssNavigationMessageCallback {
1057   /*
1058    * Methods from ::android::hardware::gps::V1_0::IGnssNavigationMessageCallback
1059    * follow.
1060    */
1061   Return<void> gnssNavigationMessageCb(
1062           const IGnssNavigationMessageCallback::GnssNavigationMessage& message) override;
1063 };
1064 
gnssNavigationMessageCb(const IGnssNavigationMessageCallback::GnssNavigationMessage & message)1065 Return<void> GnssNavigationMessageCallback::gnssNavigationMessageCb(
1066         const IGnssNavigationMessageCallback::GnssNavigationMessage& message) {
1067     JNIEnv* env = getJniEnv();
1068 
1069     size_t dataLength = message.data.size();
1070 
1071     std::vector<uint8_t> navigationData = message.data;
1072     uint8_t* data = &(navigationData[0]);
1073     if (dataLength == 0 || data == nullptr) {
1074       ALOGE("Invalid Navigation Message found: data=%p, length=%zd", data,
1075             dataLength);
1076       return Void();
1077     }
1078 
1079     JavaObject object(env, class_gnssNavigationMessage, method_gnssNavigationMessageCtor);
1080     SET(Type, static_cast<int32_t>(message.type));
1081     SET(Svid, static_cast<int32_t>(message.svid));
1082     SET(MessageId, static_cast<int32_t>(message.messageId));
1083     SET(SubmessageId, static_cast<int32_t>(message.submessageId));
1084     object.callSetter("setData", data, dataLength);
1085     SET(Status, static_cast<int32_t>(message.status));
1086 
1087     jobject navigationMessage = object.get();
1088     env->CallVoidMethod(mCallbacksObj,
1089                         method_reportNavigationMessages,
1090                         navigationMessage);
1091     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1092     env->DeleteLocalRef(navigationMessage);
1093     return Void();
1094 }
1095 
1096 /*
1097  * GnssAntennaInfoCallback implements the callback methods required for the
1098  * GnssAntennaInfo interface.
1099  */
1100 struct GnssAntennaInfoCallback : public IGnssAntennaInfoCallback {
1101     // Methods from V2_1::GnssAntennaInfoCallback follow.
1102     Return<void> gnssAntennaInfoCb(
1103             const hidl_vec<IGnssAntennaInfoCallback::GnssAntennaInfo>& gnssAntennaInfos);
1104 
1105 private:
1106     jobject translateAllGnssAntennaInfos(
1107             JNIEnv* env,
1108             const hidl_vec<IGnssAntennaInfoCallback::GnssAntennaInfo>& gnssAntennaInfos);
1109     jobject translateSingleGnssAntennaInfo(
1110             JNIEnv* env, const IGnssAntennaInfoCallback::GnssAntennaInfo& gnssAntennaInfo);
1111     jobject translatePhaseCenterOffset(
1112             JNIEnv* env, const IGnssAntennaInfoCallback::GnssAntennaInfo& gnssAntennaInfo);
1113     jobject translatePhaseCenterVariationCorrections(
1114             JNIEnv* env, const IGnssAntennaInfoCallback::GnssAntennaInfo& gnssAntennaInfo);
1115     jobject translateSignalGainCorrections(
1116             JNIEnv* env, const IGnssAntennaInfoCallback::GnssAntennaInfo& gnssAntennaInfo);
1117     jobjectArray translate2dDoubleArray(JNIEnv* env,
1118                                         const hidl_vec<IGnssAntennaInfoCallback::Row>& array);
1119     void translateAndReportGnssAntennaInfo(
1120             const hidl_vec<IGnssAntennaInfoCallback::GnssAntennaInfo>& gnssAntennaInfos);
1121     void reportAntennaInfo(JNIEnv* env, const jobject antennaInfosArray);
1122 };
1123 
gnssAntennaInfoCb(const hidl_vec<IGnssAntennaInfoCallback::GnssAntennaInfo> & gnssAntennaInfos)1124 Return<void> GnssAntennaInfoCallback::gnssAntennaInfoCb(
1125         const hidl_vec<IGnssAntennaInfoCallback::GnssAntennaInfo>& gnssAntennaInfos) {
1126     translateAndReportGnssAntennaInfo(gnssAntennaInfos);
1127     return Void();
1128 }
1129 
translate2dDoubleArray(JNIEnv * env,const hidl_vec<IGnssAntennaInfoCallback::Row> & array)1130 jobjectArray GnssAntennaInfoCallback::translate2dDoubleArray(
1131         JNIEnv* env, const hidl_vec<IGnssAntennaInfoCallback::Row>& array) {
1132     jsize numRows = array.size();
1133     if (numRows == 0) {
1134         // Empty array
1135         return NULL;
1136     }
1137     jsize numCols = array[0].row.size();
1138     if (numCols <= 1) {
1139         // phi angle separation is computed as 180.0 / (numColumns - 1), so can't be < 2.
1140         return NULL;
1141     }
1142 
1143     // Allocate array of double arrays
1144     jobjectArray returnArray = env->NewObjectArray(numRows, class_doubleArray, NULL);
1145 
1146     // Create each double array
1147     for (uint8_t i = 0; i < numRows; i++) {
1148         jdoubleArray doubleArray = env->NewDoubleArray(numCols);
1149         env->SetDoubleArrayRegion(doubleArray, (jsize)0, numCols, array[i].row.data());
1150         env->SetObjectArrayElement(returnArray, (jsize)i, doubleArray);
1151         env->DeleteLocalRef(doubleArray);
1152     }
1153     return returnArray;
1154 }
1155 
translateAllGnssAntennaInfos(JNIEnv * env,const hidl_vec<IGnssAntennaInfoCallback::GnssAntennaInfo> & gnssAntennaInfos)1156 jobject GnssAntennaInfoCallback::translateAllGnssAntennaInfos(
1157         JNIEnv* env, const hidl_vec<IGnssAntennaInfoCallback::GnssAntennaInfo>& gnssAntennaInfos) {
1158     jobject arrayList = env->NewObject(class_arrayList,
1159                                        method_arrayListCtor); // Create new ArrayList instance
1160 
1161     for (auto gnssAntennaInfo : gnssAntennaInfos) {
1162         jobject gnssAntennaInfoObject = translateSingleGnssAntennaInfo(env, gnssAntennaInfo);
1163 
1164         env->CallBooleanMethod(arrayList, method_arrayListAdd,
1165                                gnssAntennaInfoObject); // Add the antennaInfo to the ArrayList
1166 
1167         // Delete Local Refs
1168         env->DeleteLocalRef(gnssAntennaInfoObject);
1169     }
1170     return arrayList;
1171 }
1172 
translatePhaseCenterOffset(JNIEnv * env,const IGnssAntennaInfoCallback::GnssAntennaInfo & gnssAntennaInfo)1173 jobject GnssAntennaInfoCallback::translatePhaseCenterOffset(
1174         JNIEnv* env, const IGnssAntennaInfoCallback::GnssAntennaInfo& gnssAntennaInfo) {
1175     jobject phaseCenterOffset =
1176             env->NewObject(class_phaseCenterOffset, method_phaseCenterOffsetCtor,
1177                            gnssAntennaInfo.phaseCenterOffsetCoordinateMillimeters.x,
1178                            gnssAntennaInfo.phaseCenterOffsetCoordinateMillimeters.xUncertainty,
1179                            gnssAntennaInfo.phaseCenterOffsetCoordinateMillimeters.y,
1180                            gnssAntennaInfo.phaseCenterOffsetCoordinateMillimeters.yUncertainty,
1181                            gnssAntennaInfo.phaseCenterOffsetCoordinateMillimeters.z,
1182                            gnssAntennaInfo.phaseCenterOffsetCoordinateMillimeters.zUncertainty);
1183 
1184     return phaseCenterOffset;
1185 }
1186 
translatePhaseCenterVariationCorrections(JNIEnv * env,const IGnssAntennaInfoCallback::GnssAntennaInfo & gnssAntennaInfo)1187 jobject GnssAntennaInfoCallback::translatePhaseCenterVariationCorrections(
1188         JNIEnv* env, const IGnssAntennaInfoCallback::GnssAntennaInfo& gnssAntennaInfo) {
1189     if (gnssAntennaInfo.phaseCenterVariationCorrectionMillimeters == NULL ||
1190         gnssAntennaInfo.phaseCenterVariationCorrectionUncertaintyMillimeters == NULL) {
1191         return NULL;
1192     }
1193 
1194     jobjectArray phaseCenterVariationCorrectionsArray =
1195             translate2dDoubleArray(env, gnssAntennaInfo.phaseCenterVariationCorrectionMillimeters);
1196     jobjectArray phaseCenterVariationCorrectionsUncertaintiesArray =
1197             translate2dDoubleArray(env,
1198                                    gnssAntennaInfo
1199                                            .phaseCenterVariationCorrectionUncertaintyMillimeters);
1200 
1201     if (phaseCenterVariationCorrectionsArray == NULL ||
1202         phaseCenterVariationCorrectionsUncertaintiesArray == NULL) {
1203         return NULL;
1204     }
1205 
1206     jobject phaseCenterVariationCorrections =
1207             env->NewObject(class_sphericalCorrections, method_sphericalCorrectionsCtor,
1208                            phaseCenterVariationCorrectionsArray,
1209                            phaseCenterVariationCorrectionsUncertaintiesArray);
1210 
1211     env->DeleteLocalRef(phaseCenterVariationCorrectionsArray);
1212     env->DeleteLocalRef(phaseCenterVariationCorrectionsUncertaintiesArray);
1213 
1214     return phaseCenterVariationCorrections;
1215 }
1216 
translateSignalGainCorrections(JNIEnv * env,const IGnssAntennaInfoCallback::GnssAntennaInfo & gnssAntennaInfo)1217 jobject GnssAntennaInfoCallback::translateSignalGainCorrections(
1218         JNIEnv* env, const IGnssAntennaInfoCallback::GnssAntennaInfo& gnssAntennaInfo) {
1219     if (gnssAntennaInfo.signalGainCorrectionDbi == NULL ||
1220         gnssAntennaInfo.signalGainCorrectionUncertaintyDbi == NULL) {
1221         return NULL;
1222     }
1223     jobjectArray signalGainCorrectionsArray =
1224             translate2dDoubleArray(env, gnssAntennaInfo.signalGainCorrectionDbi);
1225     jobjectArray signalGainCorrectionsUncertaintiesArray =
1226             translate2dDoubleArray(env, gnssAntennaInfo.signalGainCorrectionUncertaintyDbi);
1227 
1228     if (signalGainCorrectionsArray == NULL || signalGainCorrectionsUncertaintiesArray == NULL) {
1229         return NULL;
1230     }
1231 
1232     jobject signalGainCorrections =
1233             env->NewObject(class_sphericalCorrections, method_sphericalCorrectionsCtor,
1234                            signalGainCorrectionsArray, signalGainCorrectionsUncertaintiesArray);
1235 
1236     env->DeleteLocalRef(signalGainCorrectionsArray);
1237     env->DeleteLocalRef(signalGainCorrectionsUncertaintiesArray);
1238 
1239     return signalGainCorrections;
1240 }
1241 
translateSingleGnssAntennaInfo(JNIEnv * env,const IGnssAntennaInfoCallback::GnssAntennaInfo & gnssAntennaInfo)1242 jobject GnssAntennaInfoCallback::translateSingleGnssAntennaInfo(
1243         JNIEnv* env, const IGnssAntennaInfoCallback::GnssAntennaInfo& gnssAntennaInfo) {
1244     jobject phaseCenterOffset = translatePhaseCenterOffset(env, gnssAntennaInfo);
1245 
1246     // Nullable
1247     jobject phaseCenterVariationCorrections =
1248             translatePhaseCenterVariationCorrections(env, gnssAntennaInfo);
1249 
1250     // Nullable
1251     jobject signalGainCorrections = translateSignalGainCorrections(env, gnssAntennaInfo);
1252 
1253     // Get builder
1254     jobject gnssAntennaInfoBuilderObject =
1255             env->NewObject(class_gnssAntennaInfoBuilder, method_gnssAntennaInfoBuilderCtor);
1256 
1257     // Set fields
1258     env->CallObjectMethod(gnssAntennaInfoBuilderObject,
1259                           method_gnssAntennaInfoBuilderSetCarrierFrequencyMHz,
1260                           gnssAntennaInfo.carrierFrequencyMHz);
1261     env->CallObjectMethod(gnssAntennaInfoBuilderObject,
1262                           method_gnssAntennaInfoBuilderSetPhaseCenterOffset, phaseCenterOffset);
1263     env->CallObjectMethod(gnssAntennaInfoBuilderObject,
1264                           method_gnssAntennaInfoBuilderSetPhaseCenterVariationCorrections,
1265                           phaseCenterVariationCorrections);
1266     env->CallObjectMethod(gnssAntennaInfoBuilderObject,
1267                           method_gnssAntennaInfoBuilderSetSignalGainCorrections,
1268                           signalGainCorrections);
1269 
1270     // build
1271     jobject gnssAntennaInfoObject =
1272             env->CallObjectMethod(gnssAntennaInfoBuilderObject, method_gnssAntennaInfoBuilderBuild);
1273 
1274     // Delete Local Refs
1275     env->DeleteLocalRef(phaseCenterOffset);
1276     env->DeleteLocalRef(phaseCenterVariationCorrections);
1277     env->DeleteLocalRef(signalGainCorrections);
1278 
1279     return gnssAntennaInfoObject;
1280 }
1281 
translateAndReportGnssAntennaInfo(const hidl_vec<IGnssAntennaInfoCallback::GnssAntennaInfo> & gnssAntennaInfos)1282 void GnssAntennaInfoCallback::translateAndReportGnssAntennaInfo(
1283         const hidl_vec<IGnssAntennaInfoCallback::GnssAntennaInfo>& gnssAntennaInfos) {
1284     JNIEnv* env = getJniEnv();
1285 
1286     jobject arrayList = translateAllGnssAntennaInfos(env, gnssAntennaInfos);
1287 
1288     reportAntennaInfo(env, arrayList);
1289 
1290     env->DeleteLocalRef(arrayList);
1291 }
1292 
reportAntennaInfo(JNIEnv * env,const jobject antennaInfosArray)1293 void GnssAntennaInfoCallback::reportAntennaInfo(JNIEnv* env, const jobject antennaInfosArray) {
1294     env->CallVoidMethod(mCallbacksObj, method_reportAntennaInfo, antennaInfosArray);
1295     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1296 }
1297 
1298 /*
1299  * GnssMeasurementCallback implements the callback methods required for the
1300  * GnssMeasurement interface.
1301  */
1302 struct GnssMeasurementCallback : public IGnssMeasurementCallback_V2_1 {
1303     Return<void> gnssMeasurementCb_2_1(const IGnssMeasurementCallback_V2_1::GnssData& data)
1304             override;
1305     Return<void> gnssMeasurementCb_2_0(const IGnssMeasurementCallback_V2_0::GnssData& data)
1306             override;
1307     Return<void> gnssMeasurementCb(const IGnssMeasurementCallback_V1_1::GnssData& data) override;
1308     Return<void> GnssMeasurementCb(const IGnssMeasurementCallback_V1_0::GnssData& data) override;
1309  private:
1310     template<class T>
1311     void translateSingleGnssMeasurement(const T* measurement, JavaObject& object);
1312 
1313     template<class T>
1314     jobjectArray translateAllGnssMeasurements(JNIEnv* env, const T* measurements, size_t count);
1315 
1316     template<class T>
1317     void translateAndSetGnssData(const T& data);
1318 
1319     template<class T>
1320     size_t getMeasurementCount(const T& data);
1321 
1322     template<class T>
1323     void translateGnssClock(JavaObject& object, const T& data);
1324 
1325     void setMeasurementData(JNIEnv* env, jobject clock, jobjectArray measurementArray);
1326 };
1327 
gnssMeasurementCb_2_1(const IGnssMeasurementCallback_V2_1::GnssData & data)1328 Return<void> GnssMeasurementCallback::gnssMeasurementCb_2_1(
1329         const IGnssMeasurementCallback_V2_1::GnssData& data) {
1330     translateAndSetGnssData(data);
1331     return Void();
1332 }
1333 
gnssMeasurementCb_2_0(const IGnssMeasurementCallback_V2_0::GnssData & data)1334 Return<void> GnssMeasurementCallback::gnssMeasurementCb_2_0(
1335         const IGnssMeasurementCallback_V2_0::GnssData& data) {
1336     translateAndSetGnssData(data);
1337     return Void();
1338 }
1339 
gnssMeasurementCb(const IGnssMeasurementCallback_V1_1::GnssData & data)1340 Return<void> GnssMeasurementCallback::gnssMeasurementCb(
1341         const IGnssMeasurementCallback_V1_1::GnssData& data) {
1342     translateAndSetGnssData(data);
1343     return Void();
1344 }
1345 
GnssMeasurementCb(const IGnssMeasurementCallback_V1_0::GnssData & data)1346 Return<void> GnssMeasurementCallback::GnssMeasurementCb(
1347         const IGnssMeasurementCallback_V1_0::GnssData& data) {
1348     translateAndSetGnssData(data);
1349     return Void();
1350 }
1351 
1352 template<class T>
translateAndSetGnssData(const T & data)1353 void GnssMeasurementCallback::translateAndSetGnssData(const T& data) {
1354     JNIEnv* env = getJniEnv();
1355 
1356     JavaObject gnssClockJavaObject(env, class_gnssClock, method_gnssClockCtor);
1357     translateGnssClock(gnssClockJavaObject, data);
1358     jobject clock = gnssClockJavaObject.get();
1359 
1360     size_t count = getMeasurementCount(data);
1361     jobjectArray measurementArray = translateAllGnssMeasurements(env, data.measurements.data(), count);
1362     setMeasurementData(env, clock, measurementArray);
1363 
1364     env->DeleteLocalRef(clock);
1365     env->DeleteLocalRef(measurementArray);
1366 }
1367 
1368 template<>
getMeasurementCount(const IGnssMeasurementCallback_V1_0::GnssData & data)1369 size_t GnssMeasurementCallback::getMeasurementCount<IGnssMeasurementCallback_V1_0::GnssData>
1370         (const IGnssMeasurementCallback_V1_0::GnssData& data) {
1371     return data.measurementCount;
1372 }
1373 
1374 template<class T>
getMeasurementCount(const T & data)1375 size_t GnssMeasurementCallback::getMeasurementCount(const T& data) {
1376     return data.measurements.size();
1377 }
1378 
1379 // Preallocate object as: JavaObject object(env, "android/location/GnssMeasurement");
1380 template<>
translateSingleGnssMeasurement(const IGnssMeasurementCallback_V1_0::GnssMeasurement * measurement,JavaObject & object)1381 void GnssMeasurementCallback::translateSingleGnssMeasurement
1382         <IGnssMeasurementCallback_V1_0::GnssMeasurement>(
1383         const IGnssMeasurementCallback_V1_0::GnssMeasurement* measurement,
1384         JavaObject& object) {
1385     uint32_t flags = static_cast<uint32_t>(measurement->flags);
1386 
1387     SET(Svid, static_cast<int32_t>(measurement->svid));
1388     SET(ConstellationType, static_cast<int32_t>(measurement->constellation));
1389     SET(TimeOffsetNanos, measurement->timeOffsetNs);
1390     SET(State, static_cast<int32_t>(measurement->state));
1391     SET(ReceivedSvTimeNanos, measurement->receivedSvTimeInNs);
1392     SET(ReceivedSvTimeUncertaintyNanos,
1393         measurement->receivedSvTimeUncertaintyInNs);
1394     SET(Cn0DbHz, measurement->cN0DbHz);
1395     SET(PseudorangeRateMetersPerSecond, measurement->pseudorangeRateMps);
1396     SET(PseudorangeRateUncertaintyMetersPerSecond,
1397         measurement->pseudorangeRateUncertaintyMps);
1398     SET(AccumulatedDeltaRangeState,
1399         (static_cast<int32_t>(measurement->accumulatedDeltaRangeState) &
1400         ~ADR_STATE_HALF_CYCLE_REPORTED)); // Half Cycle state not reported from Hardware in V1_0
1401     SET(AccumulatedDeltaRangeMeters, measurement->accumulatedDeltaRangeM);
1402     SET(AccumulatedDeltaRangeUncertaintyMeters,
1403         measurement->accumulatedDeltaRangeUncertaintyM);
1404 
1405     if (flags & static_cast<uint32_t>(GnssMeasurementFlags::HAS_CARRIER_FREQUENCY)) {
1406         SET(CarrierFrequencyHz, measurement->carrierFrequencyHz);
1407     }
1408 
1409     // Intentionally not copying deprecated fields of carrierCycles,
1410     // carrierPhase, carrierPhaseUncertainty
1411 
1412     SET(MultipathIndicator, static_cast<int32_t>(measurement->multipathIndicator));
1413 
1414     if (flags & static_cast<uint32_t>(GnssMeasurementFlags::HAS_SNR)) {
1415         SET(SnrInDb, measurement->snrDb);
1416     }
1417 
1418     if (flags & static_cast<uint32_t>(GnssMeasurementFlags::HAS_AUTOMATIC_GAIN_CONTROL)) {
1419         SET(AutomaticGainControlLevelInDb, measurement->agcLevelDb);
1420     }
1421 }
1422 
1423 // Preallocate object as: JavaObject object(env, "android/location/GnssMeasurement");
1424 template<>
translateSingleGnssMeasurement(const IGnssMeasurementCallback_V1_1::GnssMeasurement * measurement_V1_1,JavaObject & object)1425 void GnssMeasurementCallback::translateSingleGnssMeasurement
1426         <IGnssMeasurementCallback_V1_1::GnssMeasurement>(
1427         const IGnssMeasurementCallback_V1_1::GnssMeasurement* measurement_V1_1,
1428         JavaObject& object) {
1429     translateSingleGnssMeasurement(&(measurement_V1_1->v1_0), object);
1430 
1431     // Set the V1_1 flag, and mark that new field has valid information for Java Layer
1432     SET(AccumulatedDeltaRangeState,
1433             (static_cast<int32_t>(measurement_V1_1->accumulatedDeltaRangeState) |
1434             ADR_STATE_HALF_CYCLE_REPORTED));
1435 }
1436 
1437 // Preallocate object as: JavaObject object(env, "android/location/GnssMeasurement");
1438 template<>
translateSingleGnssMeasurement(const IGnssMeasurementCallback_V2_0::GnssMeasurement * measurement_V2_0,JavaObject & object)1439 void GnssMeasurementCallback::translateSingleGnssMeasurement
1440         <IGnssMeasurementCallback_V2_0::GnssMeasurement>(
1441         const IGnssMeasurementCallback_V2_0::GnssMeasurement* measurement_V2_0,
1442         JavaObject& object) {
1443     JNIEnv* env = getJniEnv();
1444     translateSingleGnssMeasurement(&(measurement_V2_0->v1_1), object);
1445 
1446     jstring codeType = env->NewStringUTF(measurement_V2_0->codeType.c_str());
1447     SET(CodeType, codeType);
1448 
1449     // Overwrite with v2_0.state since v2_0->v1_1->v1_0.state is deprecated.
1450     SET(State, static_cast<int32_t>(measurement_V2_0->state));
1451 
1452     // Overwrite with v2_0.constellation since v2_0->v1_1->v1_0.constellation is deprecated.
1453     SET(ConstellationType, static_cast<int32_t>(measurement_V2_0->constellation));
1454 
1455     if (codeType) {
1456         env->DeleteLocalRef(codeType);
1457     }
1458 }
1459 
1460 // Preallocate object as: JavaObject object(env, "android/location/GnssMeasurement");
1461 template<>
translateSingleGnssMeasurement(const IGnssMeasurementCallback_V2_1::GnssMeasurement * measurement_V2_1,JavaObject & object)1462 void GnssMeasurementCallback::translateSingleGnssMeasurement
1463         <IGnssMeasurementCallback_V2_1::GnssMeasurement>(
1464         const IGnssMeasurementCallback_V2_1::GnssMeasurement* measurement_V2_1,
1465         JavaObject& object) {
1466     translateSingleGnssMeasurement(&(measurement_V2_1->v2_0), object);
1467 
1468     SET(BasebandCn0DbHz, measurement_V2_1->basebandCN0DbHz);
1469 
1470     if (measurement_V2_1->flags & GnssMeasurementFlags::HAS_FULL_ISB) {
1471         SET(FullInterSignalBiasNanos, measurement_V2_1->fullInterSignalBiasNs);
1472     }
1473 
1474     if (measurement_V2_1->flags & GnssMeasurementFlags::HAS_FULL_ISB_UNCERTAINTY) {
1475         SET(FullInterSignalBiasUncertaintyNanos,
1476             measurement_V2_1->fullInterSignalBiasUncertaintyNs);
1477     }
1478 
1479     if (measurement_V2_1->flags & GnssMeasurementFlags::HAS_SATELLITE_ISB) {
1480         SET(SatelliteInterSignalBiasNanos, measurement_V2_1->satelliteInterSignalBiasNs);
1481     }
1482 
1483     if (measurement_V2_1->flags & GnssMeasurementFlags::HAS_SATELLITE_ISB_UNCERTAINTY) {
1484         SET(SatelliteInterSignalBiasUncertaintyNanos,
1485             measurement_V2_1->satelliteInterSignalBiasUncertaintyNs);
1486     }
1487 }
1488 
1489 template<class T>
translateGnssClock(JavaObject & object,const T & data)1490 void GnssMeasurementCallback::translateGnssClock(JavaObject& object, const T& data) {
1491     translateGnssClock(object, data.clock);
1492 }
1493 
1494 template<>
translateGnssClock(JavaObject & object,const IGnssMeasurementCallback_V1_0::GnssClock & clock)1495 void GnssMeasurementCallback::translateGnssClock(
1496        JavaObject& object, const IGnssMeasurementCallback_V1_0::GnssClock& clock) {
1497     uint32_t flags = static_cast<uint32_t>(clock.gnssClockFlags);
1498     if (flags & static_cast<uint32_t>(GnssClockFlags::HAS_LEAP_SECOND)) {
1499         SET(LeapSecond, static_cast<int32_t>(clock.leapSecond));
1500     }
1501 
1502     if (flags & static_cast<uint32_t>(GnssClockFlags::HAS_TIME_UNCERTAINTY)) {
1503         SET(TimeUncertaintyNanos, clock.timeUncertaintyNs);
1504     }
1505 
1506     if (flags & static_cast<uint32_t>(GnssClockFlags::HAS_FULL_BIAS)) {
1507         SET(FullBiasNanos, clock.fullBiasNs);
1508     }
1509 
1510     if (flags & static_cast<uint32_t>(GnssClockFlags::HAS_BIAS)) {
1511         SET(BiasNanos, clock.biasNs);
1512     }
1513 
1514     if (flags & static_cast<uint32_t>(GnssClockFlags::HAS_BIAS_UNCERTAINTY)) {
1515         SET(BiasUncertaintyNanos, clock.biasUncertaintyNs);
1516     }
1517 
1518     if (flags & static_cast<uint32_t>(GnssClockFlags::HAS_DRIFT)) {
1519         SET(DriftNanosPerSecond, clock.driftNsps);
1520     }
1521 
1522     if (flags & static_cast<uint32_t>(GnssClockFlags::HAS_DRIFT_UNCERTAINTY)) {
1523         SET(DriftUncertaintyNanosPerSecond, clock.driftUncertaintyNsps);
1524     }
1525 
1526     SET(TimeNanos, clock.timeNs);
1527     SET(HardwareClockDiscontinuityCount, clock.hwClockDiscontinuityCount);
1528 }
1529 
1530 template<>
translateGnssClock(JavaObject & object,const IGnssMeasurementCallback_V2_1::GnssClock & clock)1531 void GnssMeasurementCallback::translateGnssClock(
1532        JavaObject& object, const IGnssMeasurementCallback_V2_1::GnssClock& clock) {
1533     JNIEnv* env = getJniEnv();
1534     SET(ReferenceConstellationTypeForIsb,
1535             static_cast<int32_t>(clock.referenceSignalTypeForIsb.constellation));
1536     SET(ReferenceCarrierFrequencyHzForIsb, clock.referenceSignalTypeForIsb.carrierFrequencyHz);
1537 
1538     jstring referenceCodeTypeForIsb =
1539             env->NewStringUTF(clock.referenceSignalTypeForIsb.codeType.c_str());
1540     SET(ReferenceCodeTypeForIsb, referenceCodeTypeForIsb);
1541 
1542     translateGnssClock(object, clock.v1_0);
1543 
1544     if (referenceCodeTypeForIsb) {
1545         env->DeleteLocalRef(referenceCodeTypeForIsb);
1546     }
1547 }
1548 
1549 template<>
translateGnssClock(JavaObject & object,const IGnssMeasurementCallback_V2_0::GnssData & data)1550 void GnssMeasurementCallback::translateGnssClock(
1551        JavaObject& object, const IGnssMeasurementCallback_V2_0::GnssData& data) {
1552     auto elapsedRealtime = data.elapsedRealtime;
1553     uint16_t flags = static_cast<uint16_t>(elapsedRealtime.flags);
1554     if (flags & ElapsedRealtimeFlags::HAS_TIMESTAMP_NS) {
1555         SET(ElapsedRealtimeNanos, static_cast<uint64_t>(elapsedRealtime.timestampNs));
1556     }
1557     if (flags & ElapsedRealtimeFlags::HAS_TIME_UNCERTAINTY_NS) {
1558         SET(ElapsedRealtimeUncertaintyNanos, static_cast<double>(elapsedRealtime.timeUncertaintyNs));
1559     }
1560     translateGnssClock(object, data.clock);
1561 }
1562 
1563 template<>
translateGnssClock(JavaObject & object,const IGnssMeasurementCallback_V2_1::GnssData & data)1564 void GnssMeasurementCallback::translateGnssClock(
1565        JavaObject& object, const IGnssMeasurementCallback_V2_1::GnssData& data) {
1566     auto elapsedRealtime = data.elapsedRealtime;
1567     uint16_t flags = static_cast<uint16_t>(elapsedRealtime.flags);
1568     if (flags & ElapsedRealtimeFlags::HAS_TIMESTAMP_NS) {
1569         SET(ElapsedRealtimeNanos, static_cast<uint64_t>(elapsedRealtime.timestampNs));
1570     }
1571     if (flags & ElapsedRealtimeFlags::HAS_TIME_UNCERTAINTY_NS) {
1572         SET(ElapsedRealtimeUncertaintyNanos, static_cast<double>(elapsedRealtime.timeUncertaintyNs));
1573     }
1574     translateGnssClock(object, data.clock);
1575 }
1576 
1577 template<class T>
translateAllGnssMeasurements(JNIEnv * env,const T * measurements,size_t count)1578 jobjectArray GnssMeasurementCallback::translateAllGnssMeasurements(JNIEnv* env,
1579         const T* measurements,
1580         size_t count) {
1581     if (count == 0) {
1582         return nullptr;
1583     }
1584 
1585     jobjectArray gnssMeasurementArray = env->NewObjectArray(
1586             count,
1587             class_gnssMeasurement,
1588             nullptr /* initialElement */);
1589 
1590     for (uint16_t i = 0; i < count; ++i) {
1591         JavaObject object(env, class_gnssMeasurement, method_gnssMeasurementCtor);
1592         translateSingleGnssMeasurement(&(measurements[i]), object);
1593         jobject gnssMeasurement = object.get();
1594         env->SetObjectArrayElement(gnssMeasurementArray, i, gnssMeasurement);
1595         env->DeleteLocalRef(gnssMeasurement);
1596     }
1597 
1598     return gnssMeasurementArray;
1599 }
1600 
setMeasurementData(JNIEnv * env,jobject clock,jobjectArray measurementArray)1601 void GnssMeasurementCallback::setMeasurementData(JNIEnv* env, jobject clock,
1602                              jobjectArray measurementArray) {
1603     jobject gnssMeasurementsEvent = env->NewObject(class_gnssMeasurementsEvent,
1604                                                    method_gnssMeasurementsEventCtor,
1605                                                    clock,
1606                                                    measurementArray);
1607 
1608     env->CallVoidMethod(mCallbacksObj, method_reportMeasurementData,
1609                       gnssMeasurementsEvent);
1610     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1611     env->DeleteLocalRef(gnssMeasurementsEvent);
1612 }
1613 
1614 /*
1615  * MeasurementCorrectionsCallback implements callback methods of interface
1616  * IMeasurementCorrectionsCallback.hal.
1617  */
1618 struct MeasurementCorrectionsCallback : public IMeasurementCorrectionsCallback {
1619     Return<void> setCapabilitiesCb(uint32_t capabilities) override;
1620 };
1621 
setCapabilitiesCb(uint32_t capabilities)1622 Return<void> MeasurementCorrectionsCallback::setCapabilitiesCb(uint32_t capabilities) {
1623     ALOGD("%s: %du\n", __func__, capabilities);
1624     JNIEnv* env = getJniEnv();
1625     env->CallVoidMethod(mCallbacksObj, method_setSubHalMeasurementCorrectionsCapabilities,
1626                         capabilities);
1627     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1628     return Void();
1629 }
1630 
1631 /*
1632  * GnssNiCallback implements callback methods required by the IGnssNi interface.
1633  */
1634 struct GnssNiCallback : public IGnssNiCallback {
1635     Return<void> niNotifyCb(const IGnssNiCallback::GnssNiNotification& notification)
1636             override;
1637 };
1638 
niNotifyCb(const IGnssNiCallback::GnssNiNotification & notification)1639 Return<void> GnssNiCallback::niNotifyCb(
1640         const IGnssNiCallback::GnssNiNotification& notification) {
1641     JNIEnv* env = getJniEnv();
1642     jstring requestorId = env->NewStringUTF(notification.requestorId.c_str());
1643     jstring text = env->NewStringUTF(notification.notificationMessage.c_str());
1644 
1645     if (requestorId && text) {
1646         env->CallVoidMethod(mCallbacksObj, method_reportNiNotification,
1647                             notification.notificationId, notification.niType,
1648                             notification.notifyFlags, notification.timeoutSec,
1649                             notification.defaultResponse, requestorId, text,
1650                             notification.requestorIdEncoding,
1651                             notification.notificationIdEncoding);
1652     } else {
1653         ALOGE("%s: OOM Error\n", __func__);
1654     }
1655 
1656     if (requestorId) {
1657         env->DeleteLocalRef(requestorId);
1658     }
1659 
1660     if (text) {
1661         env->DeleteLocalRef(text);
1662     }
1663     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1664     return Void();
1665 }
1666 
1667 /*
1668  * GnssVisibilityControlCallback implements callback methods of IGnssVisibilityControlCallback.hal.
1669  */
1670 struct GnssVisibilityControlCallback : public IGnssVisibilityControlCallback {
1671     Return<void> nfwNotifyCb(const IGnssVisibilityControlCallback::NfwNotification& notification)
1672             override;
1673     Return<bool> isInEmergencySession() override;
1674 };
1675 
nfwNotifyCb(const IGnssVisibilityControlCallback::NfwNotification & notification)1676 Return<void> GnssVisibilityControlCallback::nfwNotifyCb(
1677         const IGnssVisibilityControlCallback::NfwNotification& notification) {
1678     JNIEnv* env = getJniEnv();
1679     jstring proxyAppPackageName = env->NewStringUTF(notification.proxyAppPackageName.c_str());
1680     jstring otherProtocolStackName = env->NewStringUTF(notification.otherProtocolStackName.c_str());
1681     jstring requestorId = env->NewStringUTF(notification.requestorId.c_str());
1682 
1683     if (proxyAppPackageName && otherProtocolStackName && requestorId) {
1684         env->CallVoidMethod(mCallbacksObj, method_reportNfwNotification, proxyAppPackageName,
1685                             notification.protocolStack, otherProtocolStackName,
1686                             notification.requestor, requestorId, notification.responseType,
1687                             notification.inEmergencyMode, notification.isCachedLocation);
1688     } else {
1689         ALOGE("%s: OOM Error\n", __func__);
1690     }
1691 
1692     if (requestorId) {
1693         env->DeleteLocalRef(requestorId);
1694     }
1695 
1696     if (otherProtocolStackName) {
1697         env->DeleteLocalRef(otherProtocolStackName);
1698     }
1699 
1700     if (proxyAppPackageName) {
1701         env->DeleteLocalRef(proxyAppPackageName);
1702     }
1703 
1704     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1705     return Void();
1706 }
1707 
isInEmergencySession()1708 Return<bool> GnssVisibilityControlCallback::isInEmergencySession() {
1709     JNIEnv* env = getJniEnv();
1710     auto result = env->CallBooleanMethod(mCallbacksObj, method_isInEmergencySession);
1711     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1712     return result;
1713 }
1714 
1715 /*
1716  * AGnssCallback_V1_0 implements callback methods required by the IAGnssCallback 1.0 interface.
1717  */
1718 struct AGnssCallback_V1_0 : public IAGnssCallback_V1_0 {
1719     // Methods from ::android::hardware::gps::V1_0::IAGnssCallback follow.
1720     Return<void> agnssStatusIpV6Cb(
1721       const IAGnssCallback_V1_0::AGnssStatusIpV6& agps_status) override;
1722 
1723     Return<void> agnssStatusIpV4Cb(
1724       const IAGnssCallback_V1_0::AGnssStatusIpV4& agps_status) override;
1725  private:
1726     jbyteArray convertToIpV4(uint32_t ip);
1727 };
1728 
agnssStatusIpV6Cb(const IAGnssCallback_V1_0::AGnssStatusIpV6 & agps_status)1729 Return<void> AGnssCallback_V1_0::agnssStatusIpV6Cb(
1730         const IAGnssCallback_V1_0::AGnssStatusIpV6& agps_status) {
1731     JNIEnv* env = getJniEnv();
1732     jbyteArray byteArray = nullptr;
1733 
1734     byteArray = env->NewByteArray(16);
1735     if (byteArray != nullptr) {
1736         env->SetByteArrayRegion(byteArray, 0, 16,
1737                                 (const jbyte*)(agps_status.ipV6Addr.data()));
1738     } else {
1739         ALOGE("Unable to allocate byte array for IPv6 address.");
1740     }
1741 
1742     IF_ALOGD() {
1743         // log the IP for reference in case there is a bogus value pushed by HAL
1744         char str[INET6_ADDRSTRLEN];
1745         inet_ntop(AF_INET6, agps_status.ipV6Addr.data(), str, INET6_ADDRSTRLEN);
1746         ALOGD("AGPS IP is v6: %s", str);
1747     }
1748 
1749     jsize byteArrayLength = byteArray != nullptr ? env->GetArrayLength(byteArray) : 0;
1750     ALOGV("Passing AGPS IP addr: size %d", byteArrayLength);
1751     env->CallVoidMethod(mCallbacksObj, method_reportAGpsStatus,
1752                         agps_status.type, agps_status.status, byteArray);
1753 
1754     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1755 
1756     if (byteArray) {
1757         env->DeleteLocalRef(byteArray);
1758     }
1759 
1760     return Void();
1761 }
1762 
agnssStatusIpV4Cb(const IAGnssCallback_V1_0::AGnssStatusIpV4 & agps_status)1763 Return<void> AGnssCallback_V1_0::agnssStatusIpV4Cb(
1764         const IAGnssCallback_V1_0::AGnssStatusIpV4& agps_status) {
1765     JNIEnv* env = getJniEnv();
1766     jbyteArray byteArray = nullptr;
1767 
1768     uint32_t ipAddr = agps_status.ipV4Addr;
1769     byteArray = convertToIpV4(ipAddr);
1770 
1771     IF_ALOGD() {
1772         /*
1773          * log the IP for reference in case there is a bogus value pushed by
1774          * HAL.
1775          */
1776         char str[INET_ADDRSTRLEN];
1777         inet_ntop(AF_INET, &ipAddr, str, INET_ADDRSTRLEN);
1778         ALOGD("AGPS IP is v4: %s", str);
1779     }
1780 
1781     jsize byteArrayLength =
1782       byteArray != nullptr ? env->GetArrayLength(byteArray) : 0;
1783     ALOGV("Passing AGPS IP addr: size %d", byteArrayLength);
1784     env->CallVoidMethod(mCallbacksObj, method_reportAGpsStatus,
1785                       agps_status.type, agps_status.status, byteArray);
1786 
1787     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1788 
1789     if (byteArray) {
1790         env->DeleteLocalRef(byteArray);
1791     }
1792     return Void();
1793 }
1794 
convertToIpV4(uint32_t ip)1795 jbyteArray AGnssCallback_V1_0::convertToIpV4(uint32_t ip) {
1796     if (INADDR_NONE == ip) {
1797         return nullptr;
1798     }
1799 
1800     JNIEnv* env = getJniEnv();
1801     jbyteArray byteArray = env->NewByteArray(4);
1802     if (byteArray == nullptr) {
1803         ALOGE("Unable to allocate byte array for IPv4 address");
1804         return nullptr;
1805     }
1806 
1807     jbyte ipv4[4];
1808     ALOGV("Converting IPv4 address byte array (net_order) %x", ip);
1809     memcpy(ipv4, &ip, sizeof(ipv4));
1810     env->SetByteArrayRegion(byteArray, 0, 4, (const jbyte*)ipv4);
1811     return byteArray;
1812 }
1813 
1814 /*
1815  * AGnssCallback_V2_0 implements callback methods required by the IAGnssCallback 2.0 interface.
1816  */
1817 struct AGnssCallback_V2_0 : public IAGnssCallback_V2_0 {
1818     // Methods from ::android::hardware::gps::V2_0::IAGnssCallback follow.
1819     Return<void> agnssStatusCb(IAGnssCallback_V2_0::AGnssType type,
1820         IAGnssCallback_V2_0::AGnssStatusValue status) override;
1821 };
1822 
agnssStatusCb(IAGnssCallback_V2_0::AGnssType type,IAGnssCallback_V2_0::AGnssStatusValue status)1823 Return<void> AGnssCallback_V2_0::agnssStatusCb(IAGnssCallback_V2_0::AGnssType type,
1824         IAGnssCallback_V2_0::AGnssStatusValue status) {
1825     JNIEnv* env = getJniEnv();
1826     env->CallVoidMethod(mCallbacksObj, method_reportAGpsStatus, type, status, nullptr);
1827     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1828     return Void();
1829 }
1830 
1831 /*
1832  * AGnssRilCallback implements the callback methods required by the AGnssRil
1833  * interface.
1834  */
1835 struct AGnssRilCallback : IAGnssRilCallback {
1836     Return<void> requestSetIdCb(uint32_t setIdFlag) override;
1837     Return<void> requestRefLocCb() override;
1838 };
1839 
requestSetIdCb(uint32_t setIdFlag)1840 Return<void> AGnssRilCallback::requestSetIdCb(uint32_t setIdFlag) {
1841     JNIEnv* env = getJniEnv();
1842     env->CallVoidMethod(mCallbacksObj, method_requestSetID, setIdFlag);
1843     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1844     return Void();
1845 }
1846 
requestRefLocCb()1847 Return<void> AGnssRilCallback::requestRefLocCb() {
1848     JNIEnv* env = getJniEnv();
1849     env->CallVoidMethod(mCallbacksObj, method_requestRefLocation);
1850     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1851     return Void();
1852 }
1853 
1854 struct GnssBatchingCallbackUtil {
1855     template<class T>
1856     static Return<void> gnssLocationBatchCbImpl(const hidl_vec<T>& locations);
1857 private:
1858     GnssBatchingCallbackUtil() = delete;
1859 };
1860 
1861 template<class T>
gnssLocationBatchCbImpl(const hidl_vec<T> & locations)1862 Return<void> GnssBatchingCallbackUtil::gnssLocationBatchCbImpl(const hidl_vec<T>& locations) {
1863     JNIEnv* env = getJniEnv();
1864 
1865     jobjectArray jLocations = env->NewObjectArray(locations.size(), class_location, nullptr);
1866 
1867     for (uint16_t i = 0; i < locations.size(); ++i) {
1868         jobject jLocation = translateGnssLocation(env, locations[i]);
1869         env->SetObjectArrayElement(jLocations, i, jLocation);
1870         env->DeleteLocalRef(jLocation);
1871     }
1872 
1873     env->CallVoidMethod(mCallbacksObj, method_reportLocationBatch, jLocations);
1874     checkAndClearExceptionFromCallback(env, __FUNCTION__);
1875 
1876     env->DeleteLocalRef(jLocations);
1877 
1878     return Void();
1879 }
1880 
1881 /*
1882  * GnssBatchingCallback_V1_0 class implements the callback methods required by the
1883  * IGnssBatching 1.0 interface.
1884  */
1885 struct GnssBatchingCallback_V1_0 : public IGnssBatchingCallback_V1_0 {
1886     /** Methods from ::android::hardware::gps::V1_0::IGnssBatchingCallback follow. */
gnssLocationBatchCbandroid::GnssBatchingCallback_V1_01887     Return<void> gnssLocationBatchCb(const hidl_vec<GnssLocation_V1_0>& locations) override {
1888         return GnssBatchingCallbackUtil::gnssLocationBatchCbImpl(locations);
1889     }
1890 };
1891 
1892 /*
1893  * GnssBatchingCallback_V2_0 class implements the callback methods required by the
1894  * IGnssBatching 2.0 interface.
1895  */
1896 struct GnssBatchingCallback_V2_0 : public IGnssBatchingCallback_V2_0 {
1897     /** Methods from ::android::hardware::gps::V2_0::IGnssBatchingCallback follow. */
gnssLocationBatchCbandroid::GnssBatchingCallback_V2_01898     Return<void> gnssLocationBatchCb(const hidl_vec<GnssLocation_V2_0>& locations) override {
1899         return GnssBatchingCallbackUtil::gnssLocationBatchCbImpl(locations);
1900     }
1901 };
1902 
1903 /* Initializes the GNSS service handle. */
android_location_GnssLocationProvider_set_gps_service_handle()1904 static void android_location_GnssLocationProvider_set_gps_service_handle() {
1905     ALOGD("Trying IGnss_V2_1::getService()");
1906     gnssHal_V2_1 = IGnss_V2_1::getService();
1907     if (gnssHal_V2_1 != nullptr) {
1908         gnssHal = gnssHal_V2_1;
1909         gnssHal_V2_0 = gnssHal_V2_1;
1910         gnssHal_V1_1 = gnssHal_V2_1;
1911         gnssHal = gnssHal_V2_1;
1912         return;
1913     }
1914 
1915     ALOGD("gnssHal 2.1 was null, trying 2.0");
1916     gnssHal_V2_0 = IGnss_V2_0::getService();
1917     if (gnssHal_V2_0 != nullptr) {
1918         gnssHal = gnssHal_V2_0;
1919         gnssHal_V1_1 = gnssHal_V2_0;
1920         return;
1921     }
1922 
1923     ALOGD("gnssHal 2.0 was null, trying 1.1");
1924     gnssHal_V1_1 = IGnss_V1_1::getService();
1925     if (gnssHal_V1_1 != nullptr) {
1926         gnssHal = gnssHal_V1_1;
1927         return;
1928     }
1929 
1930     ALOGD("gnssHal 1.1 was null, trying 1.0");
1931     gnssHal = IGnss_V1_0::getService();
1932 }
1933 
1934 /* One time initialization at system boot */
android_location_GnssLocationProvider_class_init_native(JNIEnv * env,jclass clazz)1935 static void android_location_GnssLocationProvider_class_init_native(JNIEnv* env, jclass clazz) {
1936     // Initialize the top level gnss HAL handle.
1937     android_location_GnssLocationProvider_set_gps_service_handle();
1938 
1939     // Cache methodIDs and class IDs.
1940     method_reportLocation = env->GetMethodID(clazz, "reportLocation",
1941             "(ZLandroid/location/Location;)V");
1942     method_reportStatus = env->GetMethodID(clazz, "reportStatus", "(I)V");
1943     method_reportSvStatus = env->GetMethodID(clazz, "reportSvStatus", "(I[I[F[F[F[F[F)V");
1944     method_reportAGpsStatus = env->GetMethodID(clazz, "reportAGpsStatus", "(II[B)V");
1945     method_reportNmea = env->GetMethodID(clazz, "reportNmea", "(J)V");
1946     method_setTopHalCapabilities = env->GetMethodID(clazz, "setTopHalCapabilities", "(I)V");
1947     method_setGnssYearOfHardware = env->GetMethodID(clazz, "setGnssYearOfHardware", "(I)V");
1948     method_setGnssHardwareModelName = env->GetMethodID(clazz, "setGnssHardwareModelName",
1949             "(Ljava/lang/String;)V");
1950     method_psdsDownloadRequest = env->GetMethodID(clazz, "psdsDownloadRequest", "()V");
1951     method_reportNiNotification = env->GetMethodID(clazz, "reportNiNotification",
1952             "(IIIIILjava/lang/String;Ljava/lang/String;II)V");
1953     method_requestLocation = env->GetMethodID(clazz, "requestLocation", "(ZZ)V");
1954     method_requestRefLocation = env->GetMethodID(clazz, "requestRefLocation", "()V");
1955     method_requestSetID = env->GetMethodID(clazz, "requestSetID", "(I)V");
1956     method_requestUtcTime = env->GetMethodID(clazz, "requestUtcTime", "()V");
1957     method_reportGeofenceTransition = env->GetMethodID(clazz, "reportGeofenceTransition",
1958             "(ILandroid/location/Location;IJ)V");
1959     method_reportGeofenceStatus = env->GetMethodID(clazz, "reportGeofenceStatus",
1960             "(ILandroid/location/Location;)V");
1961     method_reportGeofenceAddStatus = env->GetMethodID(clazz, "reportGeofenceAddStatus",
1962             "(II)V");
1963     method_reportGeofenceRemoveStatus = env->GetMethodID(clazz, "reportGeofenceRemoveStatus",
1964             "(II)V");
1965     method_reportGeofenceResumeStatus = env->GetMethodID(clazz, "reportGeofenceResumeStatus",
1966             "(II)V");
1967     method_reportGeofencePauseStatus = env->GetMethodID(clazz, "reportGeofencePauseStatus",
1968             "(II)V");
1969     method_reportAntennaInfo = env->GetMethodID(clazz, "reportAntennaInfo", "(Ljava/util/List;)V");
1970     method_reportMeasurementData = env->GetMethodID(
1971             clazz,
1972             "reportMeasurementData",
1973             "(Landroid/location/GnssMeasurementsEvent;)V");
1974     method_reportNavigationMessages = env->GetMethodID(
1975             clazz,
1976             "reportNavigationMessage",
1977             "(Landroid/location/GnssNavigationMessage;)V");
1978     method_reportLocationBatch = env->GetMethodID(
1979             clazz,
1980             "reportLocationBatch",
1981             "([Landroid/location/Location;)V");
1982     method_reportGnssServiceDied = env->GetMethodID(clazz, "reportGnssServiceDied", "()V");
1983     method_reportNfwNotification = env->GetMethodID(clazz, "reportNfwNotification",
1984             "(Ljava/lang/String;BLjava/lang/String;BLjava/lang/String;BZZ)V");
1985     method_isInEmergencySession = env->GetMethodID(clazz, "isInEmergencySession", "()Z");
1986 
1987     method_setSubHalMeasurementCorrectionsCapabilities = env->GetMethodID(clazz,
1988             "setSubHalMeasurementCorrectionsCapabilities", "(I)V");
1989 
1990     jclass measCorrClass = env->FindClass("android/location/GnssMeasurementCorrections");
1991     method_correctionsGetLatitudeDegrees = env->GetMethodID(
1992             measCorrClass,"getLatitudeDegrees", "()D");
1993     method_correctionsGetLongitudeDegrees = env->GetMethodID(
1994             measCorrClass, "getLongitudeDegrees", "()D");
1995     method_correctionsGetAltitudeMeters = env->GetMethodID(
1996             measCorrClass, "getAltitudeMeters", "()D");
1997     method_correctionsGetHorPosUncMeters = env->GetMethodID(
1998             measCorrClass, "getHorizontalPositionUncertaintyMeters", "()D");
1999     method_correctionsGetVerPosUncMeters = env->GetMethodID(
2000             measCorrClass, "getVerticalPositionUncertaintyMeters", "()D");
2001     method_correctionsGetToaGpsNanosecondsOfWeek = env->GetMethodID(
2002             measCorrClass, "getToaGpsNanosecondsOfWeek", "()J");
2003 
2004     method_correctionsGetSingleSatCorrectionList = env->GetMethodID(
2005             measCorrClass, "getSingleSatelliteCorrectionList", "()Ljava/util/List;");
2006 
2007     method_correctionsHasEnvironmentBearing = env->GetMethodID(
2008             measCorrClass, "hasEnvironmentBearing", "()Z");
2009     method_correctionsGetEnvironmentBearingDegrees = env->GetMethodID(
2010             measCorrClass, "getEnvironmentBearingDegrees", "()F");
2011     method_correctionsGetEnvironmentBearingUncertaintyDegrees = env->GetMethodID(
2012             measCorrClass, "getEnvironmentBearingUncertaintyDegrees", "()F");
2013 
2014     jclass corrListClass = env->FindClass("java/util/List");
2015     method_listSize = env->GetMethodID(corrListClass, "size", "()I");
2016     method_correctionListGet = env->GetMethodID(corrListClass, "get", "(I)Ljava/lang/Object;");
2017 
2018     jclass singleSatCorrClass = env->FindClass("android/location/GnssSingleSatCorrection");
2019     method_correctionSatFlags = env->GetMethodID(
2020             singleSatCorrClass, "getSingleSatelliteCorrectionFlags", "()I");
2021     method_correctionSatConstType = env->GetMethodID(
2022             singleSatCorrClass, "getConstellationType", "()I");
2023     method_correctionSatId= env->GetMethodID(
2024             singleSatCorrClass, "getSatelliteId", "()I");
2025     method_correctionSatCarrierFreq = env->GetMethodID(
2026             singleSatCorrClass, "getCarrierFrequencyHz", "()F");
2027     method_correctionSatIsLosProb = env->GetMethodID(
2028             singleSatCorrClass,"getProbabilityLineOfSight", "()F");
2029     method_correctionSatEpl = env->GetMethodID(
2030             singleSatCorrClass, "getExcessPathLengthMeters", "()F");
2031     method_correctionSatEplUnc = env->GetMethodID(
2032             singleSatCorrClass, "getExcessPathLengthUncertaintyMeters", "()F");
2033     method_correctionSatRefPlane = env->GetMethodID(
2034             singleSatCorrClass, "getReflectingPlane", "()Landroid/location/GnssReflectingPlane;");
2035 
2036     jclass refPlaneClass = env->FindClass("android/location/GnssReflectingPlane");
2037     method_correctionPlaneLatDeg = env->GetMethodID(refPlaneClass, "getLatitudeDegrees", "()D");
2038     method_correctionPlaneLngDeg = env->GetMethodID(refPlaneClass, "getLongitudeDegrees", "()D");
2039     method_correctionPlaneAltDeg = env->GetMethodID(refPlaneClass, "getAltitudeMeters", "()D");
2040     method_correctionPlaneAzimDeg = env->GetMethodID(refPlaneClass, "getAzimuthDegrees", "()D");
2041 
2042     jclass gnssMeasurementsEventClass = env->FindClass("android/location/GnssMeasurementsEvent");
2043     class_gnssMeasurementsEvent= (jclass) env->NewGlobalRef(gnssMeasurementsEventClass);
2044     method_gnssMeasurementsEventCtor = env->GetMethodID(
2045                     class_gnssMeasurementsEvent,
2046                     "<init>",
2047                     "(Landroid/location/GnssClock;[Landroid/location/GnssMeasurement;)V");
2048 
2049     jclass gnssMeasurementClass = env->FindClass("android/location/GnssMeasurement");
2050     class_gnssMeasurement = (jclass) env->NewGlobalRef(gnssMeasurementClass);
2051     method_gnssMeasurementCtor = env->GetMethodID(class_gnssMeasurement, "<init>", "()V");
2052 
2053     jclass gnssAntennaInfoBuilder = env->FindClass("android/location/GnssAntennaInfo$Builder");
2054     class_gnssAntennaInfoBuilder = (jclass)env->NewGlobalRef(gnssAntennaInfoBuilder);
2055     method_gnssAntennaInfoBuilderCtor =
2056             env->GetMethodID(class_gnssAntennaInfoBuilder, "<init>", "()V");
2057     method_gnssAntennaInfoBuilderSetCarrierFrequencyMHz =
2058             env->GetMethodID(class_gnssAntennaInfoBuilder, "setCarrierFrequencyMHz",
2059                              "(D)Landroid/location/GnssAntennaInfo$Builder;");
2060     method_gnssAntennaInfoBuilderSetPhaseCenterOffset =
2061             env->GetMethodID(class_gnssAntennaInfoBuilder, "setPhaseCenterOffset",
2062                              "(Landroid/location/GnssAntennaInfo$PhaseCenterOffset;)"
2063                              "Landroid/location/GnssAntennaInfo$Builder;");
2064     method_gnssAntennaInfoBuilderSetPhaseCenterVariationCorrections =
2065             env->GetMethodID(class_gnssAntennaInfoBuilder, "setPhaseCenterVariationCorrections",
2066                              "(Landroid/location/GnssAntennaInfo$SphericalCorrections;)"
2067                              "Landroid/location/GnssAntennaInfo$Builder;");
2068     method_gnssAntennaInfoBuilderSetSignalGainCorrections =
2069             env->GetMethodID(class_gnssAntennaInfoBuilder, "setSignalGainCorrections",
2070                              "(Landroid/location/GnssAntennaInfo$SphericalCorrections;)"
2071                              "Landroid/location/GnssAntennaInfo$Builder;");
2072     method_gnssAntennaInfoBuilderBuild = env->GetMethodID(class_gnssAntennaInfoBuilder, "build",
2073                                                           "()Landroid/location/GnssAntennaInfo;");
2074 
2075     jclass phaseCenterOffsetClass =
2076             env->FindClass("android/location/GnssAntennaInfo$PhaseCenterOffset");
2077     class_phaseCenterOffset = (jclass)env->NewGlobalRef(phaseCenterOffsetClass);
2078     method_phaseCenterOffsetCtor = env->GetMethodID(class_phaseCenterOffset, "<init>", "(DDDDDD)V");
2079 
2080     jclass sphericalCorrectionsClass =
2081             env->FindClass("android/location/GnssAntennaInfo$SphericalCorrections");
2082     class_sphericalCorrections = (jclass)env->NewGlobalRef(sphericalCorrectionsClass);
2083     method_sphericalCorrectionsCtor =
2084             env->GetMethodID(class_sphericalCorrections, "<init>", "([[D[[D)V");
2085 
2086     jclass locationClass = env->FindClass("android/location/Location");
2087     class_location = (jclass) env->NewGlobalRef(locationClass);
2088     method_locationCtor = env->GetMethodID(class_location, "<init>", "(Ljava/lang/String;)V");
2089 
2090     jclass gnssNavigationMessageClass = env->FindClass("android/location/GnssNavigationMessage");
2091     class_gnssNavigationMessage = (jclass) env->NewGlobalRef(gnssNavigationMessageClass);
2092     method_gnssNavigationMessageCtor = env->GetMethodID(class_gnssNavigationMessage, "<init>", "()V");
2093 
2094     jclass gnssClockClass = env->FindClass("android/location/GnssClock");
2095     class_gnssClock = (jclass) env->NewGlobalRef(gnssClockClass);
2096     method_gnssClockCtor = env->GetMethodID(class_gnssClock, "<init>", "()V");
2097 
2098     jclass gnssConfiguration_halInterfaceVersionClass = env->FindClass(
2099             "com/android/server/location/gnss/GnssConfiguration$HalInterfaceVersion");
2100     class_gnssConfiguration_halInterfaceVersion =
2101             (jclass) env->NewGlobalRef(gnssConfiguration_halInterfaceVersionClass);
2102     method_halInterfaceVersionCtor =
2103             env->GetMethodID(class_gnssConfiguration_halInterfaceVersion, "<init>", "(II)V");
2104 
2105     jclass arrayListClass = env->FindClass("java/util/ArrayList");
2106     class_arrayList = (jclass)env->NewGlobalRef(arrayListClass);
2107     method_arrayListCtor = env->GetMethodID(class_arrayList, "<init>", "()V");
2108     method_arrayListAdd = env->GetMethodID(class_arrayList, "add", "(Ljava/lang/Object;)Z");
2109 
2110     jclass doubleArrayClass = env->FindClass("[D");
2111     class_doubleArray = (jclass)env->NewGlobalRef(doubleArrayClass);
2112 }
2113 
2114 /* Initialization needed at system boot and whenever GNSS service dies. */
android_location_GnssLocationProvider_init_once(JNIEnv * env,jclass clazz,jboolean reinitializeGnssServiceHandle)2115 static void android_location_GnssLocationProvider_init_once(JNIEnv* env, jclass clazz,
2116         jboolean reinitializeGnssServiceHandle) {
2117     /*
2118      * Save a pointer to JVM.
2119      */
2120     jint jvmStatus = env->GetJavaVM(&sJvm);
2121     if (jvmStatus != JNI_OK) {
2122         LOG_ALWAYS_FATAL("Unable to get Java VM. Error: %d", jvmStatus);
2123     }
2124 
2125     if (reinitializeGnssServiceHandle) {
2126         android_location_GnssLocationProvider_set_gps_service_handle();
2127     }
2128 
2129     if (gnssHal == nullptr) {
2130         ALOGE("Unable to get GPS service\n");
2131         return;
2132     }
2133 
2134     gnssHalDeathRecipient = new GnssDeathRecipient();
2135     hardware::Return<bool> linked = gnssHal->linkToDeath(gnssHalDeathRecipient, /*cookie*/ 0);
2136     if (!linked.isOk()) {
2137         ALOGE("Transaction error in linking to GnssHAL death: %s",
2138                 linked.description().c_str());
2139     } else if (!linked) {
2140         ALOGW("Unable to link to GnssHal death notifications");
2141     } else {
2142         ALOGD("Link to death notification successful");
2143     }
2144 
2145     auto gnssXtra = gnssHal->getExtensionXtra();
2146     if (!gnssXtra.isOk()) {
2147         ALOGD("Unable to get a handle to Xtra");
2148     } else {
2149         gnssXtraIface = gnssXtra;
2150     }
2151 
2152     if (gnssHal_V2_0 != nullptr) {
2153         auto agnssRil_V2_0 = gnssHal_V2_0->getExtensionAGnssRil_2_0();
2154         if (!agnssRil_V2_0.isOk()) {
2155             ALOGD("Unable to get a handle to AGnssRil_V2_0");
2156         } else {
2157             agnssRilIface_V2_0 = agnssRil_V2_0;
2158             agnssRilIface = agnssRilIface_V2_0;
2159         }
2160     } else {
2161         auto agnssRil_V1_0 = gnssHal->getExtensionAGnssRil();
2162         if (!agnssRil_V1_0.isOk()) {
2163             ALOGD("Unable to get a handle to AGnssRil");
2164         } else {
2165             agnssRilIface = agnssRil_V1_0;
2166         }
2167     }
2168 
2169     if (gnssHal_V2_0 != nullptr) {
2170         auto agnss_V2_0 = gnssHal_V2_0->getExtensionAGnss_2_0();
2171         if (!agnss_V2_0.isOk()) {
2172             ALOGD("Unable to get a handle to AGnss_V2_0");
2173         } else {
2174             agnssIface_V2_0 = agnss_V2_0;
2175         }
2176     } else {
2177         auto agnss_V1_0 = gnssHal->getExtensionAGnss();
2178         if (!agnss_V1_0.isOk()) {
2179             ALOGD("Unable to get a handle to AGnss");
2180         } else {
2181             agnssIface = agnss_V1_0;
2182         }
2183     }
2184 
2185     auto gnssNavigationMessage = gnssHal->getExtensionGnssNavigationMessage();
2186     if (!gnssNavigationMessage.isOk()) {
2187         ALOGD("Unable to get a handle to GnssNavigationMessage");
2188     } else {
2189         gnssNavigationMessageIface = gnssNavigationMessage;
2190     }
2191 
2192     // Allow all causal combinations between IGnss.hal and IGnssMeasurement.hal. That means,
2193     // 2.1@IGnss can be paired with {1.0, 1,1, 2.0, 2.1}@IGnssMeasurement
2194     // 2.0@IGnss can be paired with {1.0, 1,1, 2.0}@IGnssMeasurement
2195     // 1.1@IGnss can be paired {1.0, 1.1}@IGnssMeasurement
2196     // 1.0@IGnss is paired with 1.0@IGnssMeasurement
2197     gnssMeasurementIface = nullptr;
2198     if (gnssHal_V2_1 != nullptr) {
2199         auto gnssMeasurement = gnssHal_V2_1->getExtensionGnssMeasurement_2_1();
2200         if (!gnssMeasurement.isOk()) {
2201             ALOGD("Unable to get a handle to GnssMeasurement_V2_1");
2202         } else {
2203             gnssMeasurementIface_V2_1 = gnssMeasurement;
2204             gnssMeasurementIface_V2_0 = gnssMeasurementIface_V2_1;
2205             gnssMeasurementIface_V1_1 = gnssMeasurementIface_V2_0;
2206             gnssMeasurementIface = gnssMeasurementIface_V1_1;
2207         }
2208     }
2209     if (gnssHal_V2_0 != nullptr && gnssMeasurementIface == nullptr) {
2210         auto gnssMeasurement = gnssHal_V2_0->getExtensionGnssMeasurement_2_0();
2211         if (!gnssMeasurement.isOk()) {
2212             ALOGD("Unable to get a handle to GnssMeasurement_V2_0");
2213         } else {
2214             gnssMeasurementIface_V2_0 = gnssMeasurement;
2215             gnssMeasurementIface_V1_1 = gnssMeasurementIface_V2_0;
2216             gnssMeasurementIface = gnssMeasurementIface_V1_1;
2217         }
2218     }
2219     if (gnssHal_V1_1 != nullptr && gnssMeasurementIface == nullptr) {
2220          auto gnssMeasurement = gnssHal_V1_1->getExtensionGnssMeasurement_1_1();
2221          if (!gnssMeasurement.isOk()) {
2222              ALOGD("Unable to get a handle to GnssMeasurement_V1_1");
2223          } else {
2224              gnssMeasurementIface_V1_1 = gnssMeasurement;
2225              gnssMeasurementIface = gnssMeasurementIface_V1_1;
2226          }
2227     }
2228     if (gnssMeasurementIface == nullptr) {
2229          auto gnssMeasurement = gnssHal->getExtensionGnssMeasurement();
2230          if (!gnssMeasurement.isOk()) {
2231              ALOGD("Unable to get a handle to GnssMeasurement");
2232          } else {
2233              gnssMeasurementIface = gnssMeasurement;
2234          }
2235     }
2236 
2237     if (gnssHal_V2_1 != nullptr) {
2238         auto gnssAntennaInfo = gnssHal_V2_1->getExtensionGnssAntennaInfo();
2239         if (!gnssAntennaInfo.isOk()) {
2240             ALOGD("Unable to get a handle to GnssAntennaInfo");
2241         } else {
2242             gnssAntennaInfoIface = gnssAntennaInfo;
2243         }
2244     }
2245 
2246     if (gnssHal_V2_1 != nullptr) {
2247         auto gnssCorrections = gnssHal_V2_1->getExtensionMeasurementCorrections_1_1();
2248         if (!gnssCorrections.isOk()) {
2249             ALOGD("Unable to get a handle to GnssMeasurementCorrections 1.1 interface");
2250         } else {
2251             gnssCorrectionsIface_V1_1 = gnssCorrections;
2252             gnssCorrectionsIface_V1_0 = gnssCorrectionsIface_V1_1;
2253         }
2254     } else if (gnssHal_V2_0 != nullptr) {
2255         auto gnssCorrections = gnssHal_V2_0->getExtensionMeasurementCorrections();
2256         if (!gnssCorrections.isOk()) {
2257             ALOGD("Unable to get a handle to GnssMeasurementCorrections interface");
2258         } else {
2259             gnssCorrectionsIface_V1_0 = gnssCorrections;
2260         }
2261     }
2262 
2263     // Allow all causal combinations between IGnss.hal and IGnssDebug.hal. That means,
2264     // 2.0@IGnss can be paired with {1.0, 2.0}@IGnssDebug
2265     // 1.0@IGnss is paired with 1.0@IGnssDebug
2266     gnssDebugIface = nullptr;
2267     if (gnssHal_V2_0 != nullptr) {
2268         auto gnssDebug = gnssHal_V2_0->getExtensionGnssDebug_2_0();
2269         if (!gnssDebug.isOk()) {
2270             ALOGD("Unable to get a handle to GnssDebug_V2_0");
2271         } else {
2272             gnssDebugIface_V2_0 = gnssDebug;
2273             gnssDebugIface = gnssDebugIface_V2_0;
2274         }
2275     }
2276     if (gnssDebugIface == nullptr) {
2277         auto gnssDebug = gnssHal->getExtensionGnssDebug();
2278         if (!gnssDebug.isOk()) {
2279             ALOGD("Unable to get a handle to GnssDebug");
2280         } else {
2281             gnssDebugIface = gnssDebug;
2282         }
2283     }
2284 
2285     auto gnssNi = gnssHal->getExtensionGnssNi();
2286     if (!gnssNi.isOk()) {
2287         ALOGD("Unable to get a handle to GnssNi");
2288     } else {
2289         gnssNiIface = gnssNi;
2290     }
2291 
2292     if (gnssHal_V2_1 != nullptr) {
2293         auto gnssConfiguration = gnssHal_V2_1->getExtensionGnssConfiguration_2_1();
2294         if (!gnssConfiguration.isOk()) {
2295             ALOGD("Unable to get a handle to GnssConfiguration_V2_1");
2296         } else {
2297             gnssConfigurationIface_V2_1 = gnssConfiguration;
2298             gnssConfigurationIface_V2_0 = gnssConfigurationIface_V2_1;
2299             gnssConfigurationIface_V1_1 = gnssConfigurationIface_V2_1;
2300             gnssConfigurationIface = gnssConfigurationIface_V2_1;
2301         }
2302     } else if (gnssHal_V2_0 != nullptr) {
2303         auto gnssConfiguration = gnssHal_V2_0->getExtensionGnssConfiguration_2_0();
2304         if (!gnssConfiguration.isOk()) {
2305             ALOGD("Unable to get a handle to GnssConfiguration_V2_0");
2306         } else {
2307             gnssConfigurationIface_V2_0 = gnssConfiguration;
2308             gnssConfigurationIface_V1_1 = gnssConfigurationIface_V2_0;
2309             gnssConfigurationIface = gnssConfigurationIface_V2_0;
2310         }
2311     } else if (gnssHal_V1_1 != nullptr) {
2312         auto gnssConfiguration = gnssHal_V1_1->getExtensionGnssConfiguration_1_1();
2313         if (!gnssConfiguration.isOk()) {
2314             ALOGD("Unable to get a handle to GnssConfiguration_V1_1");
2315         } else {
2316             gnssConfigurationIface_V1_1 = gnssConfiguration;
2317             gnssConfigurationIface = gnssConfigurationIface_V1_1;
2318         }
2319     } else {
2320         auto gnssConfiguration_V1_0 = gnssHal->getExtensionGnssConfiguration();
2321         if (!gnssConfiguration_V1_0.isOk()) {
2322             ALOGD("Unable to get a handle to GnssConfiguration");
2323         } else {
2324             gnssConfigurationIface = gnssConfiguration_V1_0;
2325         }
2326     }
2327 
2328     auto gnssGeofencing = gnssHal->getExtensionGnssGeofencing();
2329     if (!gnssGeofencing.isOk()) {
2330         ALOGD("Unable to get a handle to GnssGeofencing");
2331     } else {
2332         gnssGeofencingIface = gnssGeofencing;
2333     }
2334 
2335     // If IGnssBatching.hal@2.0 is not supported, use IGnssBatching.hal@1.0
2336     if (gnssHal_V2_0 != nullptr) {
2337         auto gnssBatching_V2_0 = gnssHal_V2_0->getExtensionGnssBatching_2_0();
2338         if (!gnssBatching_V2_0.isOk()) {
2339             ALOGD("Unable to get a handle to GnssBatching_V2_0");
2340         } else {
2341             gnssBatchingIface_V2_0 = gnssBatching_V2_0;
2342         }
2343     }
2344     if (gnssBatchingIface_V2_0 == nullptr ) {
2345         auto gnssBatching_V1_0 = gnssHal->getExtensionGnssBatching();
2346         if (!gnssBatching_V1_0.isOk()) {
2347             ALOGD("Unable to get a handle to GnssBatching");
2348         } else {
2349             gnssBatchingIface = gnssBatching_V1_0;
2350         }
2351     }
2352 
2353     if (gnssHal_V2_0 != nullptr) {
2354         auto gnssVisibilityControl = gnssHal_V2_0->getExtensionVisibilityControl();
2355         if (!gnssVisibilityControl.isOk()) {
2356             ALOGD("Unable to get a handle to GnssVisibilityControl interface");
2357         } else {
2358             gnssVisibilityControlIface = gnssVisibilityControl;
2359         }
2360     }
2361 }
2362 
android_location_GnssLocationProvider_is_supported(JNIEnv *,jclass)2363 static jboolean android_location_GnssLocationProvider_is_supported(
2364         JNIEnv* /* env */, jclass /* clazz */) {
2365     return (gnssHal != nullptr) ?  JNI_TRUE : JNI_FALSE;
2366 }
2367 
android_location_GnssNetworkConnectivityHandler_is_agps_ril_supported(JNIEnv *,jclass)2368 static jboolean android_location_GnssNetworkConnectivityHandler_is_agps_ril_supported(
2369         JNIEnv* /* env */, jclass /* clazz */) {
2370     return (agnssRilIface != nullptr) ? JNI_TRUE : JNI_FALSE;
2371 }
2372 
android_location_GnssConfiguration_get_gnss_configuration_version(JNIEnv * env,jclass)2373 static jobject android_location_GnssConfiguration_get_gnss_configuration_version(
2374         JNIEnv* env, jclass /* jclazz */) {
2375     jint major, minor;
2376     if (gnssConfigurationIface_V2_1 != nullptr) {
2377         major = 2;
2378         minor = 1;
2379     }
2380     else if (gnssConfigurationIface_V2_0 != nullptr) {
2381         major = 2;
2382         minor = 0;
2383     } else if (gnssConfigurationIface_V1_1 != nullptr) {
2384         major = 1;
2385         minor = 1;
2386     } else if (gnssConfigurationIface != nullptr) {
2387         major = 1;
2388         minor = 0;
2389     } else {
2390         return nullptr;
2391     }
2392 
2393     return createHalInterfaceVersionJavaObject(env, major, minor);
2394 }
2395 
2396 /* Initialization needed each time the GPS service is shutdown. */
android_location_GnssLocationProvider_init(JNIEnv * env,jobject obj)2397 static jboolean android_location_GnssLocationProvider_init(JNIEnv* env, jobject obj) {
2398     /*
2399      * This must be set before calling into the HAL library.
2400      */
2401     if (!mCallbacksObj)
2402         mCallbacksObj = env->NewGlobalRef(obj);
2403 
2404     /*
2405      * Fail if the main interface fails to initialize
2406      */
2407     if (gnssHal == nullptr) {
2408         ALOGE("Unable to initialize GNSS HAL.");
2409         return JNI_FALSE;
2410     }
2411 
2412     Return<bool> result = false;
2413 
2414     // Set top level IGnss.hal callback.
2415     sp<IGnssCallback_V2_1> gnssCbIface = new GnssCallback();
2416     if (gnssHal_V2_1 != nullptr) {
2417         result = gnssHal_V2_1->setCallback_2_1(gnssCbIface);
2418     } else if (gnssHal_V2_0 != nullptr) {
2419         result = gnssHal_V2_0->setCallback_2_0(gnssCbIface);
2420     } else if (gnssHal_V1_1 != nullptr) {
2421         result = gnssHal_V1_1->setCallback_1_1(gnssCbIface);
2422     } else {
2423         result = gnssHal->setCallback(gnssCbIface);
2424     }
2425 
2426     if (!checkHidlReturn(result, "IGnss setCallback() failed.")) {
2427         return JNI_FALSE;
2428     }
2429 
2430     // Set IGnssXtra.hal callback.
2431     if (gnssXtraIface == nullptr) {
2432         ALOGI("Unable to initialize IGnssXtra interface.");
2433     } else {
2434         sp<IGnssXtraCallback> gnssXtraCbIface = new GnssXtraCallback();
2435         result = gnssXtraIface->setCallback(gnssXtraCbIface);
2436         if (!checkHidlReturn(result, "IGnssXtra setCallback() failed.")) {
2437             gnssXtraIface = nullptr;
2438         }
2439     }
2440 
2441     // Set IAGnss.hal callback.
2442     if (agnssIface_V2_0 != nullptr) {
2443         sp<IAGnssCallback_V2_0> aGnssCbIface = new AGnssCallback_V2_0();
2444         auto agnssStatus = agnssIface_V2_0->setCallback(aGnssCbIface);
2445         checkHidlReturn(agnssStatus, "IAGnss 2.0 setCallback() failed.");
2446     } else if (agnssIface != nullptr) {
2447         sp<IAGnssCallback_V1_0> aGnssCbIface = new AGnssCallback_V1_0();
2448         auto agnssStatus = agnssIface->setCallback(aGnssCbIface);
2449         checkHidlReturn(agnssStatus, "IAGnss setCallback() failed.");
2450     } else {
2451         ALOGI("Unable to initialize IAGnss interface.");
2452     }
2453 
2454     // Set IGnssGeofencing.hal callback.
2455     sp<IGnssGeofenceCallback> gnssGeofencingCbIface = new GnssGeofenceCallback();
2456     if (gnssGeofencingIface != nullptr) {
2457         auto status = gnssGeofencingIface->setCallback(gnssGeofencingCbIface);
2458         checkHidlReturn(status, "IGnssGeofencing setCallback() failed.");
2459     } else {
2460         ALOGI("Unable to initialize IGnssGeofencing interface.");
2461     }
2462 
2463     // Set IGnssNi.hal callback.
2464     sp<IGnssNiCallback> gnssNiCbIface = new GnssNiCallback();
2465     if (gnssNiIface != nullptr) {
2466         auto status = gnssNiIface->setCallback(gnssNiCbIface);
2467         checkHidlReturn(status, "IGnssNi setCallback() failed.");
2468     } else {
2469         ALOGI("Unable to initialize IGnssNi interface.");
2470     }
2471 
2472     // Set IAGnssRil.hal callback.
2473     sp<IAGnssRilCallback> aGnssRilCbIface = new AGnssRilCallback();
2474     if (agnssRilIface != nullptr) {
2475         auto status = agnssRilIface->setCallback(aGnssRilCbIface);
2476         checkHidlReturn(status, "IAGnssRil setCallback() failed.");
2477     } else {
2478         ALOGI("Unable to initialize IAGnssRil interface.");
2479     }
2480 
2481     // Set IGnssVisibilityControl.hal callback.
2482     if (gnssVisibilityControlIface != nullptr) {
2483         sp<IGnssVisibilityControlCallback> gnssVisibilityControlCbIface =
2484                 new GnssVisibilityControlCallback();
2485         result = gnssVisibilityControlIface->setCallback(gnssVisibilityControlCbIface);
2486         checkHidlReturn(result, "IGnssVisibilityControl setCallback() failed.");
2487     }
2488 
2489     // Set IMeasurementCorrections.hal callback.
2490     if (gnssCorrectionsIface_V1_1 != nullptr) {
2491             sp<IMeasurementCorrectionsCallback> gnssCorrectionsIfaceCbIface =
2492                     new MeasurementCorrectionsCallback();
2493             result = gnssCorrectionsIface_V1_1->setCallback(gnssCorrectionsIfaceCbIface);
2494             checkHidlReturn(result, "IMeasurementCorrections 1.1 setCallback() failed.");
2495     } else if (gnssCorrectionsIface_V1_0 != nullptr) {
2496         sp<IMeasurementCorrectionsCallback> gnssCorrectionsIfaceCbIface =
2497                 new MeasurementCorrectionsCallback();
2498         result = gnssCorrectionsIface_V1_0->setCallback(gnssCorrectionsIfaceCbIface);
2499         checkHidlReturn(result, "IMeasurementCorrections 1.0 setCallback() failed.");
2500     } else {
2501         ALOGI("Unable to find IMeasurementCorrections.");
2502     }
2503 
2504     return JNI_TRUE;
2505 }
2506 
android_location_GnssLocationProvider_cleanup(JNIEnv *,jobject)2507 static void android_location_GnssLocationProvider_cleanup(JNIEnv* /* env */, jobject /* obj */) {
2508     if (gnssHal == nullptr) {
2509         return;
2510     }
2511 
2512     auto result = gnssHal->cleanup();
2513     checkHidlReturn(result, "IGnss cleanup() failed.");
2514 }
2515 
android_location_GnssLocationProvider_set_position_mode(JNIEnv *,jobject,jint mode,jint recurrence,jint min_interval,jint preferred_accuracy,jint preferred_time,jboolean low_power_mode)2516 static jboolean android_location_GnssLocationProvider_set_position_mode(JNIEnv* /* env */,
2517         jobject /* obj */, jint mode, jint recurrence, jint min_interval, jint preferred_accuracy,
2518         jint preferred_time, jboolean low_power_mode) {
2519     Return<bool> result = false;
2520     if (gnssHal_V1_1 != nullptr) {
2521          result = gnssHal_V1_1->setPositionMode_1_1(static_cast<IGnss_V1_0::GnssPositionMode>(mode),
2522                  static_cast<IGnss_V1_0::GnssPositionRecurrence>(recurrence),
2523                  min_interval,
2524                  preferred_accuracy,
2525                  preferred_time,
2526                  low_power_mode);
2527      } else if (gnssHal != nullptr) {
2528          result = gnssHal->setPositionMode(static_cast<IGnss_V1_0::GnssPositionMode>(mode),
2529                  static_cast<IGnss_V1_0::GnssPositionRecurrence>(recurrence),
2530                  min_interval,
2531                  preferred_accuracy,
2532                  preferred_time);
2533     }
2534 
2535     return checkHidlReturn(result, "IGnss setPositionMode() failed.");
2536 }
2537 
android_location_GnssLocationProvider_start(JNIEnv *,jobject)2538 static jboolean android_location_GnssLocationProvider_start(JNIEnv* /* env */, jobject /* obj */) {
2539     if (gnssHal == nullptr) {
2540         return JNI_FALSE;
2541     }
2542 
2543     auto result = gnssHal->start();
2544     return checkHidlReturn(result, "IGnss start() failed.");
2545 }
2546 
android_location_GnssLocationProvider_stop(JNIEnv *,jobject)2547 static jboolean android_location_GnssLocationProvider_stop(JNIEnv* /* env */, jobject /* obj */) {
2548     if (gnssHal == nullptr) {
2549         return JNI_FALSE;
2550     }
2551 
2552     auto result = gnssHal->stop();
2553     return checkHidlReturn(result, "IGnss stop() failed.");
2554 }
2555 
android_location_GnssLocationProvider_delete_aiding_data(JNIEnv *,jobject,jint flags)2556 static void android_location_GnssLocationProvider_delete_aiding_data(JNIEnv* /* env */,
2557                                                                     jobject /* obj */,
2558                                                                     jint flags) {
2559     if (gnssHal == nullptr) {
2560         return;
2561     }
2562 
2563     auto result = gnssHal->deleteAidingData(static_cast<IGnss_V1_0::GnssAidingData>(flags));
2564     checkHidlReturn(result, "IGnss deleteAidingData() failed.");
2565 }
2566 
android_location_GnssLocationProvider_agps_set_reference_location_cellid(JNIEnv *,jobject,jint type,jint mcc,jint mnc,jint lac,jint cid)2567 static void android_location_GnssLocationProvider_agps_set_reference_location_cellid(
2568         JNIEnv* /* env */, jobject /* obj */, jint type, jint mcc, jint mnc, jint lac, jint cid) {
2569     IAGnssRil_V1_0::AGnssRefLocation location;
2570 
2571     if (agnssRilIface == nullptr) {
2572         ALOGE("%s: IAGnssRil interface not available.", __func__);
2573         return;
2574     }
2575 
2576     switch (static_cast<IAGnssRil_V1_0::AGnssRefLocationType>(type)) {
2577         case IAGnssRil_V1_0::AGnssRefLocationType::GSM_CELLID:
2578         case IAGnssRil_V1_0::AGnssRefLocationType::UMTS_CELLID:
2579           location.type = static_cast<IAGnssRil_V1_0::AGnssRefLocationType>(type);
2580           location.cellID.mcc = mcc;
2581           location.cellID.mnc = mnc;
2582           location.cellID.lac = lac;
2583           location.cellID.cid = cid;
2584           break;
2585         default:
2586             ALOGE("Neither a GSM nor a UMTS cellid (%s:%d).", __FUNCTION__, __LINE__);
2587             return;
2588             break;
2589     }
2590 
2591     auto result = agnssRilIface->setRefLocation(location);
2592     checkHidlReturn(result, "IAGnssRil setRefLocation() failed.");
2593 }
2594 
android_location_GnssLocationProvider_agps_set_id(JNIEnv * env,jobject,jint type,jstring setid_string)2595 static void android_location_GnssLocationProvider_agps_set_id(JNIEnv* env, jobject /* obj */,
2596                                                              jint type, jstring  setid_string) {
2597     if (agnssRilIface == nullptr) {
2598         ALOGE("%s: IAGnssRil interface not available.", __func__);
2599         return;
2600     }
2601 
2602     ScopedJniString jniSetId{env, setid_string};
2603     auto result = agnssRilIface->setSetId((IAGnssRil_V1_0::SetIDType)type, jniSetId);
2604     checkHidlReturn(result, "IAGnssRil setSetId() failed.");
2605 }
2606 
android_location_GnssLocationProvider_read_nmea(JNIEnv * env,jobject,jbyteArray nmeaArray,jint buffer_size)2607 static jint android_location_GnssLocationProvider_read_nmea(JNIEnv* env, jobject /* obj */,
2608                                             jbyteArray nmeaArray, jint buffer_size) {
2609     // this should only be called from within a call to reportNmea
2610     jbyte* nmea = reinterpret_cast<jbyte *>(env->GetPrimitiveArrayCritical(nmeaArray, 0));
2611     int length = GnssCallback::sNmeaStringLength;
2612     if (length > buffer_size)
2613         length = buffer_size;
2614     memcpy(nmea, GnssCallback::sNmeaString, length);
2615     env->ReleasePrimitiveArrayCritical(nmeaArray, nmea, JNI_ABORT);
2616     return (jint) length;
2617 }
2618 
android_location_GnssLocationProvider_inject_time(JNIEnv *,jobject,jlong time,jlong timeReference,jint uncertainty)2619 static void android_location_GnssLocationProvider_inject_time(JNIEnv* /* env */, jobject /* obj */,
2620         jlong time, jlong timeReference, jint uncertainty) {
2621     if (gnssHal == nullptr) {
2622         return;
2623     }
2624 
2625     auto result = gnssHal->injectTime(time, timeReference, uncertainty);
2626     checkHidlReturn(result, "IGnss injectTime() failed.");
2627 }
2628 
android_location_GnssLocationProvider_inject_best_location(JNIEnv *,jobject,jint gnssLocationFlags,jdouble latitudeDegrees,jdouble longitudeDegrees,jdouble altitudeMeters,jfloat speedMetersPerSec,jfloat bearingDegrees,jfloat horizontalAccuracyMeters,jfloat verticalAccuracyMeters,jfloat speedAccuracyMetersPerSecond,jfloat bearingAccuracyDegrees,jlong timestamp,jint elapsedRealtimeFlags,jlong elapsedRealtimeNanos,jdouble elapsedRealtimeUncertaintyNanos)2629 static void android_location_GnssLocationProvider_inject_best_location(
2630         JNIEnv*,
2631         jobject,
2632         jint gnssLocationFlags,
2633         jdouble latitudeDegrees,
2634         jdouble longitudeDegrees,
2635         jdouble altitudeMeters,
2636         jfloat speedMetersPerSec,
2637         jfloat bearingDegrees,
2638         jfloat horizontalAccuracyMeters,
2639         jfloat verticalAccuracyMeters,
2640         jfloat speedAccuracyMetersPerSecond,
2641         jfloat bearingAccuracyDegrees,
2642         jlong timestamp,
2643         jint elapsedRealtimeFlags,
2644         jlong elapsedRealtimeNanos,
2645         jdouble elapsedRealtimeUncertaintyNanos) {
2646     if (gnssHal_V2_0 != nullptr) {
2647         GnssLocation_V2_0 location = createGnssLocation_V2_0(
2648                 gnssLocationFlags,
2649                 latitudeDegrees,
2650                 longitudeDegrees,
2651                 altitudeMeters,
2652                 speedMetersPerSec,
2653                 bearingDegrees,
2654                 horizontalAccuracyMeters,
2655                 verticalAccuracyMeters,
2656                 speedAccuracyMetersPerSecond,
2657                 bearingAccuracyDegrees,
2658                 timestamp,
2659                 elapsedRealtimeFlags,
2660                 elapsedRealtimeNanos,
2661                 elapsedRealtimeUncertaintyNanos);
2662         auto result = gnssHal_V2_0->injectBestLocation_2_0(location);
2663         checkHidlReturn(result, "IGnss injectBestLocation_2_0() failed.");
2664         return;
2665     }
2666 
2667     if (gnssHal_V1_1 != nullptr) {
2668         GnssLocation_V1_0 location = createGnssLocation_V1_0(
2669                 gnssLocationFlags,
2670                 latitudeDegrees,
2671                 longitudeDegrees,
2672                 altitudeMeters,
2673                 speedMetersPerSec,
2674                 bearingDegrees,
2675                 horizontalAccuracyMeters,
2676                 verticalAccuracyMeters,
2677                 speedAccuracyMetersPerSecond,
2678                 bearingAccuracyDegrees,
2679                 timestamp);
2680         auto result = gnssHal_V1_1->injectBestLocation(location);
2681         checkHidlReturn(result, "IGnss injectBestLocation() failed.");
2682     }
2683 
2684     ALOGE("IGnss injectBestLocation() is called but gnssHal_V1_1 is not available.");
2685 }
2686 
android_location_GnssLocationProvider_inject_location(JNIEnv *,jobject,jdouble latitude,jdouble longitude,jfloat accuracy)2687 static void android_location_GnssLocationProvider_inject_location(JNIEnv* /* env */,
2688         jobject /* obj */, jdouble latitude, jdouble longitude, jfloat accuracy) {
2689     if (gnssHal == nullptr) {
2690         return;
2691     }
2692 
2693     auto result = gnssHal->injectLocation(latitude, longitude, accuracy);
2694     checkHidlReturn(result, "IGnss injectLocation() failed.");
2695 }
2696 
android_location_GnssLocationProvider_supports_psds(JNIEnv *,jobject)2697 static jboolean android_location_GnssLocationProvider_supports_psds(
2698         JNIEnv* /* env */, jobject /* obj */) {
2699     return (gnssXtraIface != nullptr) ? JNI_TRUE : JNI_FALSE;
2700 }
2701 
android_location_GnssLocationProvider_inject_psds_data(JNIEnv * env,jobject,jbyteArray data,jint length)2702 static void android_location_GnssLocationProvider_inject_psds_data(JNIEnv* env, jobject /* obj */,
2703         jbyteArray data, jint length) {
2704     if (gnssXtraIface == nullptr) {
2705         ALOGE("%s: IGnssXtra interface not available.", __func__);
2706         return;
2707     }
2708 
2709     jbyte* bytes = reinterpret_cast<jbyte *>(env->GetPrimitiveArrayCritical(data, 0));
2710     auto result = gnssXtraIface->injectXtraData(std::string((const char*)bytes, length));
2711     checkHidlReturn(result, "IGnssXtra injectXtraData() failed.");
2712     env->ReleasePrimitiveArrayCritical(data, bytes, JNI_ABORT);
2713 }
2714 
2715 struct AGnssDispatcher {
2716     static void dataConnOpen(sp<IAGnss_V1_0> agnssIface, JNIEnv* env, jstring apn, jint apnIpType);
2717     static void dataConnOpen(sp<IAGnss_V2_0> agnssIface_V2_0, JNIEnv* env, jlong networkHandle,
2718             jstring apn, jint apnIpType);
2719 
2720     template <class T>
2721     static void dataConnClosed(sp<T> agnssIface);
2722 
2723     template <class T>
2724     static void dataConnFailed(sp<T> agnssIface);
2725 
2726     template <class T, class U>
2727     static void setServer(sp<T> agnssIface, JNIEnv* env, jint type, jstring hostname, jint port);
2728 
2729 private:
2730     AGnssDispatcher() = delete;
2731 };
2732 
dataConnOpen(sp<IAGnss_V1_0> agnssIface,JNIEnv * env,jstring apn,jint apnIpType)2733 void AGnssDispatcher::dataConnOpen(sp<IAGnss_V1_0> agnssIface, JNIEnv* env, jstring apn,
2734         jint apnIpType) {
2735     ScopedJniString jniApn{env, apn};
2736     auto result = agnssIface->dataConnOpen(jniApn,
2737             static_cast<IAGnss_V1_0::ApnIpType>(apnIpType));
2738     checkHidlReturn(result, "IAGnss dataConnOpen() failed. APN and its IP type not set.");
2739 }
2740 
dataConnOpen(sp<IAGnss_V2_0> agnssIface_V2_0,JNIEnv * env,jlong networkHandle,jstring apn,jint apnIpType)2741 void AGnssDispatcher::dataConnOpen(sp<IAGnss_V2_0> agnssIface_V2_0, JNIEnv* env,
2742         jlong networkHandle, jstring apn, jint apnIpType) {
2743     ScopedJniString jniApn{env, apn};
2744     auto result = agnssIface_V2_0->dataConnOpen(static_cast<uint64_t>(networkHandle), jniApn,
2745             static_cast<IAGnss_V2_0::ApnIpType>(apnIpType));
2746     checkHidlReturn(result, "IAGnss 2.0 dataConnOpen() failed. APN and its IP type not set.");
2747 }
2748 
2749 template<class T>
dataConnClosed(sp<T> agnssIface)2750 void AGnssDispatcher::dataConnClosed(sp<T> agnssIface) {
2751     auto result = agnssIface->dataConnClosed();
2752     checkHidlReturn(result, "IAGnss dataConnClosed() failed.");
2753 }
2754 
2755 template<class T>
dataConnFailed(sp<T> agnssIface)2756 void AGnssDispatcher::dataConnFailed(sp<T> agnssIface) {
2757     auto result = agnssIface->dataConnFailed();
2758     checkHidlReturn(result, "IAGnss dataConnFailed() failed.");
2759 }
2760 
2761 template <class T, class U>
setServer(sp<T> agnssIface,JNIEnv * env,jint type,jstring hostname,jint port)2762 void AGnssDispatcher::setServer(sp<T> agnssIface, JNIEnv* env, jint type, jstring hostname,
2763         jint port) {
2764     ScopedJniString jniHostName{env, hostname};
2765     auto result = agnssIface->setServer(static_cast<typename U::AGnssType>(type),
2766             jniHostName, port);
2767     checkHidlReturn(result, "IAGnss setServer() failed. Host name and port not set.");
2768 }
2769 
android_location_GnssNetworkConnectivityHandler_agps_data_conn_open(JNIEnv * env,jobject,jlong networkHandle,jstring apn,jint apnIpType)2770 static void android_location_GnssNetworkConnectivityHandler_agps_data_conn_open(
2771         JNIEnv* env, jobject /* obj */, jlong networkHandle, jstring apn, jint apnIpType) {
2772     if (apn == nullptr) {
2773         jniThrowException(env, "java/lang/IllegalArgumentException", nullptr);
2774         return;
2775     }
2776 
2777     if (agnssIface_V2_0 != nullptr) {
2778         AGnssDispatcher::dataConnOpen(agnssIface_V2_0, env, networkHandle, apn, apnIpType);
2779     } else if (agnssIface != nullptr) {
2780         AGnssDispatcher::dataConnOpen(agnssIface, env, apn, apnIpType);
2781     } else {
2782         ALOGE("%s: IAGnss interface not available.", __func__);
2783         return;
2784     }
2785 }
2786 
android_location_GnssNetworkConnectivityHandler_agps_data_conn_closed(JNIEnv *,jobject)2787 static void android_location_GnssNetworkConnectivityHandler_agps_data_conn_closed(JNIEnv* /* env */,
2788                                                                        jobject /* obj */) {
2789     if (agnssIface_V2_0 != nullptr) {
2790         AGnssDispatcher::dataConnClosed(agnssIface_V2_0);
2791     } else if (agnssIface != nullptr) {
2792         AGnssDispatcher::dataConnClosed(agnssIface);
2793     } else {
2794         ALOGE("%s: IAGnss interface not available.", __func__);
2795         return;
2796     }
2797 }
2798 
android_location_GnssNetworkConnectivityHandler_agps_data_conn_failed(JNIEnv *,jobject)2799 static void android_location_GnssNetworkConnectivityHandler_agps_data_conn_failed(JNIEnv* /* env */,
2800                                                                        jobject /* obj */) {
2801     if (agnssIface_V2_0 != nullptr) {
2802         AGnssDispatcher::dataConnFailed(agnssIface_V2_0);
2803     } else if (agnssIface != nullptr) {
2804         AGnssDispatcher::dataConnFailed(agnssIface);
2805     } else {
2806         ALOGE("%s: IAGnss interface not available.", __func__);
2807         return;
2808     }
2809 }
2810 
android_location_GnssLocationProvider_set_agps_server(JNIEnv * env,jobject,jint type,jstring hostname,jint port)2811 static void android_location_GnssLocationProvider_set_agps_server(JNIEnv* env, jobject /* obj */,
2812         jint type, jstring hostname, jint port) {
2813     if (agnssIface_V2_0 != nullptr) {
2814         AGnssDispatcher::setServer<IAGnss_V2_0, IAGnssCallback_V2_0>(agnssIface_V2_0, env, type,
2815                 hostname, port);
2816     } else if (agnssIface != nullptr) {
2817         AGnssDispatcher::setServer<IAGnss_V1_0, IAGnssCallback_V1_0>(agnssIface, env, type,
2818                 hostname, port);
2819     } else {
2820         ALOGE("%s: IAGnss interface not available.", __func__);
2821         return;
2822     }
2823 }
2824 
android_location_GnssLocationProvider_send_ni_response(JNIEnv *,jobject,jint notifId,jint response)2825 static void android_location_GnssLocationProvider_send_ni_response(JNIEnv* /* env */,
2826         jobject /* obj */, jint notifId, jint response) {
2827     if (gnssNiIface == nullptr) {
2828         ALOGE("%s: IGnssNi interface not available.", __func__);
2829         return;
2830     }
2831 
2832     auto result = gnssNiIface->respond(notifId,
2833             static_cast<IGnssNiCallback::GnssUserResponseType>(response));
2834     checkHidlReturn(result, "IGnssNi respond() failed.");
2835 }
2836 
getSatelliteData(const hidl_vec<IGnssDebug_V1_0::SatelliteData> & satelliteDataArray,size_t i)2837 const IGnssDebug_V1_0::SatelliteData& getSatelliteData(
2838         const hidl_vec<IGnssDebug_V1_0::SatelliteData>& satelliteDataArray, size_t i) {
2839     return satelliteDataArray[i];
2840 }
2841 
getSatelliteData(const hidl_vec<IGnssDebug_V2_0::SatelliteData> & satelliteDataArray,size_t i)2842 const IGnssDebug_V1_0::SatelliteData& getSatelliteData(
2843         const hidl_vec<IGnssDebug_V2_0::SatelliteData>& satelliteDataArray, size_t i) {
2844     return satelliteDataArray[i].v1_0;
2845 }
2846 
2847 template<class T>
getConstellationType(const hidl_vec<T> & satelliteDataArray,size_t i)2848 uint32_t getConstellationType(const hidl_vec<T>& satelliteDataArray, size_t i) {
2849     return static_cast<uint32_t>(satelliteDataArray[i].constellation);
2850 }
2851 
2852 template<class T>
parseDebugData(JNIEnv * env,std::stringstream & internalState,const T & data)2853 static jstring parseDebugData(JNIEnv* env, std::stringstream& internalState, const T& data) {
2854     internalState << "Gnss Location Data:: ";
2855     if (!data.position.valid) {
2856         internalState << "not valid";
2857     } else {
2858         internalState << "LatitudeDegrees: " << data.position.latitudeDegrees
2859                       << ", LongitudeDegrees: " << data.position.longitudeDegrees
2860                       << ", altitudeMeters: " << data.position.altitudeMeters
2861                       << ", speedMetersPerSecond: " << data.position.speedMetersPerSec
2862                       << ", bearingDegrees: " << data.position.bearingDegrees
2863                       << ", horizontalAccuracyMeters: "
2864                       << data.position.horizontalAccuracyMeters
2865                       << ", verticalAccuracyMeters: " << data.position.verticalAccuracyMeters
2866                       << ", speedAccuracyMetersPerSecond: "
2867                       << data.position.speedAccuracyMetersPerSecond
2868                       << ", bearingAccuracyDegrees: " << data.position.bearingAccuracyDegrees
2869                       << ", ageSeconds: " << data.position.ageSeconds;
2870     }
2871     internalState << std::endl;
2872 
2873     internalState << "Gnss Time Data:: timeEstimate: " << data.time.timeEstimate
2874                   << ", timeUncertaintyNs: " << data.time.timeUncertaintyNs
2875                   << ", frequencyUncertaintyNsPerSec: "
2876                   << data.time.frequencyUncertaintyNsPerSec << std::endl;
2877 
2878     if (data.satelliteDataArray.size() != 0) {
2879         internalState << "Satellite Data for " << data.satelliteDataArray.size()
2880                       << " satellites:: " << std::endl;
2881     }
2882 
2883     internalState << "constell: 1=GPS, 2=SBAS, 3=GLO, 4=QZSS, 5=BDS, 6=GAL, 7=IRNSS; "
2884                   << "ephType: 0=Eph, 1=Alm, 2=Unk; "
2885                   << "ephSource: 0=Demod, 1=Supl, 2=Server, 3=Unk; "
2886                   << "ephHealth: 0=Good, 1=Bad, 2=Unk" << std::endl;
2887     for (size_t i = 0; i < data.satelliteDataArray.size(); i++) {
2888         IGnssDebug_V1_0::SatelliteData satelliteData =
2889                 getSatelliteData(data.satelliteDataArray, i);
2890         internalState << "constell: "
2891                       << getConstellationType(data.satelliteDataArray, i)
2892                       << ", svid: " << std::setw(3) << satelliteData.svid
2893                       << ", serverPredAvail: "
2894                       << satelliteData.serverPredictionIsAvailable
2895                       << ", serverPredAgeSec: " << std::setw(7)
2896                       << satelliteData.serverPredictionAgeSeconds
2897                       << ", ephType: "
2898                       << static_cast<uint32_t>(satelliteData.ephemerisType)
2899                       << ", ephSource: "
2900                       << static_cast<uint32_t>(satelliteData.ephemerisSource)
2901                       << ", ephHealth: "
2902                       << static_cast<uint32_t>(satelliteData.ephemerisHealth)
2903                       << ", ephAgeSec: " << std::setw(7)
2904                       << satelliteData.ephemerisAgeSeconds << std::endl;
2905     }
2906     return (jstring) env->NewStringUTF(internalState.str().c_str());
2907 }
2908 
android_location_GnssLocationProvider_get_internal_state(JNIEnv * env,jobject)2909 static jstring android_location_GnssLocationProvider_get_internal_state(JNIEnv* env,
2910                                                                        jobject /* obj */) {
2911     jstring internalStateStr = nullptr;
2912     /*
2913      * TODO: Create a jobject to represent GnssDebug.
2914      */
2915 
2916     std::stringstream internalState;
2917 
2918     if (gnssDebugIface == nullptr) {
2919         ALOGE("%s: IGnssDebug interface not available.", __func__);
2920     } else if (gnssDebugIface_V2_0 != nullptr) {
2921         IGnssDebug_V2_0::DebugData data;
2922         auto result = gnssDebugIface_V2_0->getDebugData_2_0(
2923                 [&data](const IGnssDebug_V2_0::DebugData& debugData) {
2924                     data = debugData;
2925                 });
2926         if (checkHidlReturn(result, "IGnssDebug getDebugData_2_0() failed.")) {
2927             internalStateStr = parseDebugData(env, internalState, data);
2928         }
2929     } else {
2930         IGnssDebug_V1_0::DebugData data;
2931         auto result = gnssDebugIface->getDebugData(
2932                 [&data](const IGnssDebug_V1_0::DebugData& debugData) {
2933                     data = debugData;
2934                 });
2935         if (checkHidlReturn(result, "IGnssDebug getDebugData() failed.")) {
2936             internalStateStr = parseDebugData(env, internalState, data);
2937         }
2938     }
2939     return internalStateStr;
2940 }
2941 
android_location_GnssLocationProvider_is_gnss_visibility_control_supported(JNIEnv *,jclass)2942 static jboolean android_location_GnssLocationProvider_is_gnss_visibility_control_supported(
2943         JNIEnv* /* env */, jclass /* clazz */) {
2944     return (gnssVisibilityControlIface != nullptr) ?  JNI_TRUE : JNI_FALSE;
2945 }
2946 
android_location_GnssNetworkConnectivityHandler_update_network_state(JNIEnv * env,jobject,jboolean connected,jint type,jboolean roaming,jboolean available,jstring apn,jlong networkHandle,jshort capabilities)2947 static void android_location_GnssNetworkConnectivityHandler_update_network_state(JNIEnv* env,
2948                                                                        jobject /* obj */,
2949                                                                        jboolean connected,
2950                                                                        jint type,
2951                                                                        jboolean roaming,
2952                                                                        jboolean available,
2953                                                                        jstring apn,
2954                                                                        jlong networkHandle,
2955                                                                        jshort capabilities) {
2956     if (agnssRilIface_V2_0 != nullptr) {
2957         ScopedJniString jniApn{env, apn};
2958         IAGnssRil_V2_0::NetworkAttributes networkAttributes = {
2959             .networkHandle = static_cast<uint64_t>(networkHandle),
2960             .isConnected = static_cast<bool>(connected),
2961             .capabilities = static_cast<uint16_t>(capabilities),
2962             .apn = jniApn
2963         };
2964 
2965         auto result = agnssRilIface_V2_0->updateNetworkState_2_0(networkAttributes);
2966         checkHidlReturn(result, "IAGnssRil updateNetworkState_2_0() failed.");
2967     } else if (agnssRilIface != nullptr) {
2968         ScopedJniString jniApn{env, apn};
2969         hidl_string hidlApn{jniApn};
2970         auto result = agnssRilIface->updateNetworkState(connected,
2971                 static_cast<IAGnssRil_V1_0::NetworkType>(type), roaming);
2972         checkHidlReturn(result, "IAGnssRil updateNetworkState() failed.");
2973 
2974         if (!hidlApn.empty()) {
2975             result = agnssRilIface->updateNetworkAvailability(available, hidlApn);
2976             checkHidlReturn(result, "IAGnssRil updateNetworkAvailability() failed.");
2977         }
2978     } else {
2979         ALOGE("%s: IAGnssRil interface not available.", __func__);
2980     }
2981 }
2982 
android_location_GnssGeofenceProvider_is_geofence_supported(JNIEnv *,jobject)2983 static jboolean android_location_GnssGeofenceProvider_is_geofence_supported(
2984         JNIEnv* /* env */, jobject /* obj */) {
2985     return (gnssGeofencingIface != nullptr) ? JNI_TRUE : JNI_FALSE;
2986 }
2987 
android_location_GnssGeofenceProvider_add_geofence(JNIEnv *,jobject,jint geofenceId,jdouble latitude,jdouble longitude,jdouble radius,jint last_transition,jint monitor_transition,jint notification_responsiveness,jint unknown_timer)2988 static jboolean android_location_GnssGeofenceProvider_add_geofence(JNIEnv* /* env */,
2989         jobject /* obj */, jint geofenceId, jdouble latitude, jdouble longitude, jdouble radius,
2990         jint last_transition, jint monitor_transition, jint notification_responsiveness,
2991         jint unknown_timer) {
2992     if (gnssGeofencingIface == nullptr) {
2993         ALOGE("%s: IGnssGeofencing interface not available.", __func__);
2994         return JNI_FALSE;
2995     }
2996 
2997     auto result = gnssGeofencingIface->addGeofence(
2998             geofenceId, latitude, longitude, radius,
2999             static_cast<IGnssGeofenceCallback::GeofenceTransition>(last_transition),
3000             monitor_transition, notification_responsiveness, unknown_timer);
3001     return checkHidlReturn(result, "IGnssGeofencing addGeofence() failed.");
3002 }
3003 
android_location_GnssGeofenceProvider_remove_geofence(JNIEnv *,jobject,jint geofenceId)3004 static jboolean android_location_GnssGeofenceProvider_remove_geofence(JNIEnv* /* env */,
3005         jobject /* obj */, jint geofenceId) {
3006     if (gnssGeofencingIface == nullptr) {
3007         ALOGE("%s: IGnssGeofencing interface not available.", __func__);
3008         return JNI_FALSE;
3009     }
3010 
3011     auto result = gnssGeofencingIface->removeGeofence(geofenceId);
3012     return checkHidlReturn(result, "IGnssGeofencing removeGeofence() failed.");
3013 }
3014 
android_location_GnssGeofenceProvider_pause_geofence(JNIEnv *,jobject,jint geofenceId)3015 static jboolean android_location_GnssGeofenceProvider_pause_geofence(JNIEnv* /* env */,
3016         jobject /* obj */, jint geofenceId) {
3017     if (gnssGeofencingIface == nullptr) {
3018         ALOGE("%s: IGnssGeofencing interface not available.", __func__);
3019         return JNI_FALSE;
3020     }
3021 
3022     auto result = gnssGeofencingIface->pauseGeofence(geofenceId);
3023     return checkHidlReturn(result, "IGnssGeofencing pauseGeofence() failed.");
3024 }
3025 
android_location_GnssGeofenceProvider_resume_geofence(JNIEnv *,jobject,jint geofenceId,jint monitor_transition)3026 static jboolean android_location_GnssGeofenceProvider_resume_geofence(JNIEnv* /* env */,
3027         jobject /* obj */, jint geofenceId, jint monitor_transition) {
3028     if (gnssGeofencingIface == nullptr) {
3029         ALOGE("%s: IGnssGeofencing interface not available.", __func__);
3030         return JNI_FALSE;
3031     }
3032 
3033     auto result = gnssGeofencingIface->resumeGeofence(geofenceId, monitor_transition);
3034     return checkHidlReturn(result, "IGnssGeofencing resumeGeofence() failed.");
3035 }
3036 
android_location_GnssAntennaInfoProvider_is_antenna_info_supported(JNIEnv * env,jclass clazz)3037 static jboolean android_location_GnssAntennaInfoProvider_is_antenna_info_supported(JNIEnv* env,
3038                                                                                    jclass clazz) {
3039     if (gnssAntennaInfoIface != nullptr) {
3040         return JNI_TRUE;
3041     }
3042     return JNI_FALSE;
3043 }
3044 
android_location_GnssAntennaInfoProvider_start_antenna_info_listening(JNIEnv *,jobject)3045 static jboolean android_location_GnssAntennaInfoProvider_start_antenna_info_listening(
3046         JNIEnv* /* env */, jobject /* obj */) {
3047     if (gnssAntennaInfoIface == nullptr) {
3048         ALOGE("%s: IGnssAntennaInfo interface not available.", __func__);
3049         return JNI_FALSE;
3050     }
3051 
3052     sp<GnssAntennaInfoCallback> cbIface = new GnssAntennaInfoCallback();
3053 
3054     auto result = gnssAntennaInfoIface->setCallback(cbIface);
3055 
3056     if (!checkHidlReturn(result, "IGnssAntennaInfo setCallback() failed.")) {
3057         return JNI_FALSE;
3058     }
3059 
3060     IGnssAntennaInfo::GnssAntennaInfoStatus initRet = result;
3061     if (initRet != IGnssAntennaInfo::GnssAntennaInfoStatus::SUCCESS) {
3062         ALOGE("An error has been found on GnssAntennaInfoInterface::init, status=%d",
3063               static_cast<int32_t>(initRet));
3064         return JNI_FALSE;
3065     } else {
3066         ALOGD("gnss antenna info has been enabled");
3067     }
3068 
3069     return JNI_TRUE;
3070 }
3071 
android_location_GnssAntennaInfoProvider_stop_antenna_info_listening(JNIEnv *,jobject)3072 static jboolean android_location_GnssAntennaInfoProvider_stop_antenna_info_listening(
3073         JNIEnv* /* env */, jobject /* obj */) {
3074     if (gnssAntennaInfoIface == nullptr) {
3075         ALOGE("%s: IGnssAntennaInfo interface not available.", __func__);
3076         return JNI_FALSE;
3077     }
3078 
3079     auto result = gnssAntennaInfoIface->close();
3080     return checkHidlReturn(result, "IGnssAntennaInfo close() failed.");
3081 }
3082 
android_location_GnssMeasurementsProvider_is_measurement_supported(JNIEnv * env,jclass clazz)3083 static jboolean android_location_GnssMeasurementsProvider_is_measurement_supported(
3084     JNIEnv* env, jclass clazz) {
3085     if (gnssMeasurementIface != nullptr) {
3086         return JNI_TRUE;
3087     }
3088 
3089     return JNI_FALSE;
3090 }
3091 
android_location_GnssMeasurementsProvider_start_measurement_collection(JNIEnv *,jobject,jboolean enableFullTracking)3092 static jboolean android_location_GnssMeasurementsProvider_start_measurement_collection(
3093         JNIEnv* /* env */,
3094         jobject /* obj */,
3095         jboolean enableFullTracking) {
3096     if (gnssMeasurementIface == nullptr) {
3097         ALOGE("%s: IGnssMeasurement interface not available.", __func__);
3098         return JNI_FALSE;
3099     }
3100 
3101     sp<GnssMeasurementCallback> cbIface = new GnssMeasurementCallback();
3102     Return<IGnssMeasurement_V1_0::GnssMeasurementStatus> result =
3103             IGnssMeasurement_V1_0::GnssMeasurementStatus::ERROR_GENERIC;
3104     if (gnssMeasurementIface_V2_1 != nullptr) {
3105         result = gnssMeasurementIface_V2_1->setCallback_2_1(cbIface, enableFullTracking);
3106     } else if (gnssMeasurementIface_V2_0 != nullptr) {
3107         result = gnssMeasurementIface_V2_0->setCallback_2_0(cbIface, enableFullTracking);
3108     } else if (gnssMeasurementIface_V1_1 != nullptr) {
3109         result = gnssMeasurementIface_V1_1->setCallback_1_1(cbIface, enableFullTracking);
3110     } else {
3111         if (enableFullTracking == JNI_TRUE) {
3112             ALOGW("Full tracking mode not supported in 1.0 GNSS HAL.");
3113         }
3114         result = gnssMeasurementIface->setCallback(cbIface);
3115     }
3116 
3117     if (!checkHidlReturn(result, "IGnssMeasurement setCallback() failed.")) {
3118         return JNI_FALSE;
3119     }
3120 
3121     IGnssMeasurement_V1_0::GnssMeasurementStatus initRet = result;
3122     if (initRet != IGnssMeasurement_V1_0::GnssMeasurementStatus::SUCCESS) {
3123         ALOGE("An error has been found on GnssMeasurementInterface::init, status=%d",
3124               static_cast<int32_t>(initRet));
3125         return JNI_FALSE;
3126     } else {
3127         ALOGD("gnss measurement infc has been enabled");
3128     }
3129 
3130     return JNI_TRUE;
3131 }
3132 
android_location_GnssMeasurementsProvider_stop_measurement_collection(JNIEnv * env,jobject obj)3133 static jboolean android_location_GnssMeasurementsProvider_stop_measurement_collection(
3134         JNIEnv* env,
3135         jobject obj) {
3136     if (gnssMeasurementIface == nullptr) {
3137         ALOGE("%s: IGnssMeasurement interface not available.", __func__);
3138         return JNI_FALSE;
3139     }
3140 
3141     auto result = gnssMeasurementIface->close();
3142     return checkHidlReturn(result, "IGnssMeasurement close() failed.");
3143 }
3144 
3145 static jboolean
android_location_GnssMeasurementCorrectionsProvider_is_measurement_corrections_supported(JNIEnv * env,jclass clazz)3146     android_location_GnssMeasurementCorrectionsProvider_is_measurement_corrections_supported(
3147     JNIEnv* env, jclass clazz) {
3148     if (gnssCorrectionsIface_V1_0 != nullptr || gnssCorrectionsIface_V1_1 != nullptr) {
3149         return JNI_TRUE;
3150     }
3151 
3152     return JNI_FALSE;
3153 }
3154 
getSingleSatCorrection_1_0_withoutConstellation(JNIEnv * env,jobject singleSatCorrectionObj)3155 static SingleSatCorrection_V1_0 getSingleSatCorrection_1_0_withoutConstellation(
3156         JNIEnv* env, jobject singleSatCorrectionObj) {
3157     jint correctionFlags = env->CallIntMethod(singleSatCorrectionObj, method_correctionSatFlags);
3158     jint satId = env->CallIntMethod(singleSatCorrectionObj, method_correctionSatId);
3159     jfloat carrierFreqHz =
3160             env->CallFloatMethod(singleSatCorrectionObj, method_correctionSatCarrierFreq);
3161     jfloat probSatIsLos =
3162             env->CallFloatMethod(singleSatCorrectionObj, method_correctionSatIsLosProb);
3163     jfloat eplMeters = env->CallFloatMethod(singleSatCorrectionObj, method_correctionSatEpl);
3164     jfloat eplUncMeters = env->CallFloatMethod(singleSatCorrectionObj, method_correctionSatEplUnc);
3165     uint16_t corrFlags = static_cast<uint16_t>(correctionFlags);
3166     jobject reflectingPlaneObj;
3167     bool has_ref_plane = (corrFlags & GnssSingleSatCorrectionFlags::HAS_REFLECTING_PLANE) != 0;
3168     if (has_ref_plane) {
3169         reflectingPlaneObj =
3170                 env->CallObjectMethod(singleSatCorrectionObj, method_correctionSatRefPlane);
3171     }
3172 
3173     ReflectingPlane reflectingPlane;
3174     if (has_ref_plane) {
3175         jdouble latitudeDegreesRefPlane =
3176                 env->CallDoubleMethod(reflectingPlaneObj, method_correctionPlaneLatDeg);
3177         jdouble longitudeDegreesRefPlane =
3178                 env->CallDoubleMethod(reflectingPlaneObj, method_correctionPlaneLngDeg);
3179         jdouble altitudeDegreesRefPlane =
3180                 env->CallDoubleMethod(reflectingPlaneObj, method_correctionPlaneAltDeg);
3181         jdouble azimuthDegreeRefPlane =
3182                 env->CallDoubleMethod(reflectingPlaneObj, method_correctionPlaneAzimDeg);
3183         reflectingPlane = {
3184                 .latitudeDegrees = latitudeDegreesRefPlane,
3185                 .longitudeDegrees = longitudeDegreesRefPlane,
3186                 .altitudeMeters = altitudeDegreesRefPlane,
3187                 .azimuthDegrees = azimuthDegreeRefPlane,
3188         };
3189     }
3190 
3191     SingleSatCorrection_V1_0 singleSatCorrection = {
3192             .singleSatCorrectionFlags = corrFlags,
3193             .svid = static_cast<uint16_t>(satId),
3194             .carrierFrequencyHz = carrierFreqHz,
3195             .probSatIsLos = probSatIsLos,
3196             .excessPathLengthMeters = eplMeters,
3197             .excessPathLengthUncertaintyMeters = eplUncMeters,
3198             .reflectingPlane = reflectingPlane,
3199     };
3200 
3201     return singleSatCorrection;
3202 }
3203 
getSingleSatCorrectionList_1_1(JNIEnv * env,jobject singleSatCorrectionList,hidl_vec<SingleSatCorrection_V1_1> & list)3204 static void getSingleSatCorrectionList_1_1(JNIEnv* env, jobject singleSatCorrectionList,
3205                                            hidl_vec<SingleSatCorrection_V1_1>& list) {
3206     for (uint16_t i = 0; i < list.size(); ++i) {
3207         jobject singleSatCorrectionObj =
3208                 env->CallObjectMethod(singleSatCorrectionList, method_correctionListGet, i);
3209 
3210         SingleSatCorrection_V1_0 singleSatCorrection_1_0 =
3211                 getSingleSatCorrection_1_0_withoutConstellation(env, singleSatCorrectionObj);
3212 
3213         jint constType = env->CallIntMethod(singleSatCorrectionObj, method_correctionSatConstType);
3214 
3215         SingleSatCorrection_V1_1 singleSatCorrection_1_1 = {
3216                 .v1_0 = singleSatCorrection_1_0,
3217                 .constellation = static_cast<GnssConstellationType_V2_0>(constType),
3218         };
3219 
3220         list[i] = singleSatCorrection_1_1;
3221     }
3222 }
3223 
getSingleSatCorrectionList_1_0(JNIEnv * env,jobject singleSatCorrectionList,hidl_vec<SingleSatCorrection_V1_0> & list)3224 static void getSingleSatCorrectionList_1_0(JNIEnv* env, jobject singleSatCorrectionList,
3225                                            hidl_vec<SingleSatCorrection_V1_0>& list) {
3226     for (uint16_t i = 0; i < list.size(); ++i) {
3227         jobject singleSatCorrectionObj =
3228                 env->CallObjectMethod(singleSatCorrectionList, method_correctionListGet, i);
3229 
3230         SingleSatCorrection_V1_0 singleSatCorrection =
3231                 getSingleSatCorrection_1_0_withoutConstellation(env, singleSatCorrectionObj);
3232 
3233         jint constType = env->CallIntMethod(singleSatCorrectionObj, method_correctionSatConstType);
3234 
3235         singleSatCorrection.constellation = static_cast<GnssConstellationType_V1_0>(constType),
3236 
3237         list[i] = singleSatCorrection;
3238     }
3239 }
3240 static jboolean
android_location_GnssMeasurementCorrectionsProvider_inject_gnss_measurement_corrections(JNIEnv * env,jobject obj,jobject correctionsObj)3241     android_location_GnssMeasurementCorrectionsProvider_inject_gnss_measurement_corrections(
3242         JNIEnv* env,
3243         jobject obj /* clazz*/,
3244         jobject correctionsObj) {
3245 
3246     if (gnssCorrectionsIface_V1_0 == nullptr && gnssCorrectionsIface_V1_1 == nullptr) {
3247         ALOGW("Trying to inject GNSS measurement corrections on a chipset that does not"
3248             " support them.");
3249         return JNI_FALSE;
3250     }
3251 
3252     jobject singleSatCorrectionList = env->CallObjectMethod(correctionsObj,
3253         method_correctionsGetSingleSatCorrectionList);
3254 
3255     auto len = (singleSatCorrectionList == nullptr)
3256         ? 0
3257         : env->CallIntMethod(singleSatCorrectionList, method_listSize);
3258     if (len == 0) {
3259         ALOGI("Empty correction list injected....Returning with no HAL injection");
3260         return JNI_TRUE;
3261     }
3262 
3263     jdouble latitudeDegreesCorr = env->CallDoubleMethod(
3264         correctionsObj, method_correctionsGetLatitudeDegrees);
3265     jdouble longitudeDegreesCorr = env->CallDoubleMethod(
3266         correctionsObj, method_correctionsGetLongitudeDegrees);
3267     jdouble altitudeDegreesCorr = env->CallDoubleMethod(
3268         correctionsObj, method_correctionsGetAltitudeMeters);
3269     jdouble horizontalPositionUncertaintyMeters = env->CallDoubleMethod(
3270         correctionsObj, method_correctionsGetHorPosUncMeters);
3271     jdouble verticalPositionUncertaintyMeters = env->CallDoubleMethod(
3272             correctionsObj, method_correctionsGetVerPosUncMeters);
3273     jlong toaGpsNanosOfWeek = env->CallLongMethod(
3274         correctionsObj, method_correctionsGetToaGpsNanosecondsOfWeek);
3275 
3276     MeasurementCorrections_V1_0 measurementCorrections_1_0 = {
3277         .latitudeDegrees = latitudeDegreesCorr,
3278         .longitudeDegrees = longitudeDegreesCorr,
3279         .altitudeMeters = altitudeDegreesCorr,
3280         .horizontalPositionUncertaintyMeters = horizontalPositionUncertaintyMeters,
3281         .verticalPositionUncertaintyMeters = verticalPositionUncertaintyMeters,
3282         .toaGpsNanosecondsOfWeek = static_cast<uint64_t>(toaGpsNanosOfWeek),
3283     };
3284 
3285     if (gnssCorrectionsIface_V1_1 != nullptr) {
3286 
3287         jboolean hasEnvironmentBearingCorr = env->CallBooleanMethod(
3288             correctionsObj, method_correctionsHasEnvironmentBearing);
3289         jfloat environmentBearingDegreesCorr = env->CallFloatMethod(
3290             correctionsObj, method_correctionsGetEnvironmentBearingDegrees);
3291         jfloat environmentBearingUncertaintyDegreesCorr = env->CallFloatMethod(
3292             correctionsObj, method_correctionsGetEnvironmentBearingUncertaintyDegrees);
3293 
3294         hidl_vec<SingleSatCorrection_V1_1> list(len);
3295         getSingleSatCorrectionList_1_1(env, singleSatCorrectionList, list);
3296 
3297         MeasurementCorrections_V1_1 measurementCorrections_1_1 = {
3298                 .v1_0 = measurementCorrections_1_0,
3299                 .hasEnvironmentBearing = static_cast<bool>(hasEnvironmentBearingCorr),
3300                 .environmentBearingDegrees = environmentBearingDegreesCorr,
3301                 .environmentBearingUncertaintyDegrees = environmentBearingUncertaintyDegreesCorr,
3302                 .satCorrections = list,
3303         };
3304 
3305         auto result = gnssCorrectionsIface_V1_1->setCorrections_1_1(measurementCorrections_1_1);
3306         return checkHidlReturn(result, "IMeasurementCorrections 1.1 setCorrections() failed.");
3307     }
3308 
3309     hidl_vec<SingleSatCorrection_V1_0> list(len);
3310     getSingleSatCorrectionList_1_0(env, singleSatCorrectionList, list);
3311     measurementCorrections_1_0.satCorrections = list;
3312 
3313     auto result = gnssCorrectionsIface_V1_0->setCorrections(measurementCorrections_1_0);
3314     return checkHidlReturn(result, "IMeasurementCorrections 1.0 setCorrections() failed.");
3315 }
3316 
android_location_GnssNavigationMessageProvider_is_navigation_message_supported(JNIEnv * env,jclass clazz)3317 static jboolean android_location_GnssNavigationMessageProvider_is_navigation_message_supported(
3318         JNIEnv* env,
3319         jclass clazz) {
3320     if (gnssNavigationMessageIface != nullptr) {
3321         return JNI_TRUE;
3322     }
3323     return JNI_FALSE;
3324 }
3325 
android_location_GnssNavigationMessageProvider_start_navigation_message_collection(JNIEnv * env,jobject obj)3326 static jboolean android_location_GnssNavigationMessageProvider_start_navigation_message_collection(
3327         JNIEnv* env,
3328         jobject obj) {
3329     if (gnssNavigationMessageIface == nullptr) {
3330         ALOGE("%s: IGnssNavigationMessage interface not available.", __func__);
3331         return JNI_FALSE;
3332     }
3333 
3334     sp<IGnssNavigationMessageCallback> gnssNavigationMessageCbIface =
3335             new GnssNavigationMessageCallback();
3336     auto result = gnssNavigationMessageIface->setCallback(gnssNavigationMessageCbIface);
3337     if (!checkHidlReturn(result, "IGnssNavigationMessage setCallback() failed.")) {
3338         return JNI_FALSE;
3339     }
3340 
3341     IGnssNavigationMessage::GnssNavigationMessageStatus initRet = result;
3342     if (initRet != IGnssNavigationMessage::GnssNavigationMessageStatus::SUCCESS) {
3343         ALOGE("An error has been found in %s: %d", __FUNCTION__, static_cast<int32_t>(initRet));
3344         return JNI_FALSE;
3345     }
3346 
3347     return JNI_TRUE;
3348 }
3349 
android_location_GnssNavigationMessageProvider_stop_navigation_message_collection(JNIEnv * env,jobject obj)3350 static jboolean android_location_GnssNavigationMessageProvider_stop_navigation_message_collection(
3351         JNIEnv* env,
3352         jobject obj) {
3353     if (gnssNavigationMessageIface == nullptr) {
3354         ALOGE("%s: IGnssNavigationMessage interface not available.", __func__);
3355         return JNI_FALSE;
3356     }
3357 
3358     auto result = gnssNavigationMessageIface->close();
3359     return checkHidlReturn(result, "IGnssNavigationMessage close() failed.");
3360 }
3361 
android_location_GnssConfiguration_set_emergency_supl_pdn(JNIEnv *,jobject,jint emergencySuplPdn)3362 static jboolean android_location_GnssConfiguration_set_emergency_supl_pdn(JNIEnv*,
3363                                                                           jobject,
3364                                                                           jint emergencySuplPdn) {
3365     if (gnssConfigurationIface == nullptr) {
3366         ALOGE("%s: IGnssConfiguration interface not available.", __func__);
3367         return JNI_FALSE;
3368     }
3369 
3370     auto result = gnssConfigurationIface->setEmergencySuplPdn(emergencySuplPdn);
3371     return checkHidlReturn(result, "IGnssConfiguration setEmergencySuplPdn() failed.");
3372 }
3373 
android_location_GnssConfiguration_set_supl_version(JNIEnv *,jobject,jint version)3374 static jboolean android_location_GnssConfiguration_set_supl_version(JNIEnv*,
3375                                                                     jobject,
3376                                                                     jint version) {
3377     if (gnssConfigurationIface == nullptr) {
3378         ALOGE("%s: IGnssConfiguration interface not available.", __func__);
3379         return JNI_FALSE;
3380     }
3381     auto result = gnssConfigurationIface->setSuplVersion(version);
3382     return checkHidlReturn(result, "IGnssConfiguration setSuplVersion() failed.");
3383 }
3384 
android_location_GnssConfiguration_set_supl_es(JNIEnv *,jobject,jint suplEs)3385 static jboolean android_location_GnssConfiguration_set_supl_es(JNIEnv*,
3386                                                                jobject,
3387                                                                jint suplEs) {
3388     if (gnssConfigurationIface_V2_0 != nullptr || gnssConfigurationIface_V2_1 != nullptr) {
3389         ALOGI("Config parameter SUPL_ES is deprecated in IGnssConfiguration.hal version 2.0 and higher.");
3390         return JNI_FALSE;
3391     }
3392 
3393     if (gnssConfigurationIface == nullptr) {
3394         ALOGE("%s: IGnssConfiguration interface not available.", __func__);
3395         return JNI_FALSE;
3396     }
3397 
3398     auto result = gnssConfigurationIface->setSuplEs(suplEs);
3399     return checkHidlReturn(result, "IGnssConfiguration setSuplEs() failed.");
3400 }
3401 
android_location_GnssConfiguration_set_supl_mode(JNIEnv *,jobject,jint mode)3402 static jboolean android_location_GnssConfiguration_set_supl_mode(JNIEnv*,
3403                                                                  jobject,
3404                                                                  jint mode) {
3405     if (gnssConfigurationIface == nullptr) {
3406         ALOGE("%s: IGnssConfiguration interface not available.", __func__);
3407         return JNI_FALSE;
3408     }
3409 
3410     auto result = gnssConfigurationIface->setSuplMode(mode);
3411     return checkHidlReturn(result, "IGnssConfiguration setSuplMode() failed.");
3412 }
3413 
android_location_GnssConfiguration_set_gps_lock(JNIEnv *,jobject,jint gpsLock)3414 static jboolean android_location_GnssConfiguration_set_gps_lock(JNIEnv*,
3415                                                                 jobject,
3416                                                                 jint gpsLock) {
3417     if (gnssConfigurationIface_V2_0 != nullptr || gnssConfigurationIface_V2_1 != nullptr) {
3418         ALOGI("Config parameter GPS_LOCK is deprecated in IGnssConfiguration.hal version 2.0.");
3419         return JNI_FALSE;
3420     }
3421 
3422     if (gnssConfigurationIface == nullptr) {
3423         ALOGE("%s: IGnssConfiguration interface not available.", __func__);
3424         return JNI_FALSE;
3425     }
3426 
3427     auto result = gnssConfigurationIface->setGpsLock(gpsLock);
3428     return checkHidlReturn(result, "IGnssConfiguration setGpsLock() failed.");
3429 }
3430 
android_location_GnssConfiguration_set_lpp_profile(JNIEnv *,jobject,jint lppProfile)3431 static jboolean android_location_GnssConfiguration_set_lpp_profile(JNIEnv*,
3432                                                                    jobject,
3433                                                                    jint lppProfile) {
3434     if (gnssConfigurationIface == nullptr) {
3435         ALOGE("%s: IGnssConfiguration interface not available.", __func__);
3436         return JNI_FALSE;
3437     }
3438 
3439     auto result = gnssConfigurationIface->setLppProfile(lppProfile);
3440     return checkHidlReturn(result, "IGnssConfiguration setLppProfile() failed.");
3441 }
3442 
android_location_GnssConfiguration_set_gnss_pos_protocol_select(JNIEnv *,jobject,jint gnssPosProtocol)3443 static jboolean android_location_GnssConfiguration_set_gnss_pos_protocol_select(JNIEnv*,
3444                                                                             jobject,
3445                                                                             jint gnssPosProtocol) {
3446     if (gnssConfigurationIface == nullptr) {
3447         ALOGE("%s: IGnssConfiguration interface not available.", __func__);
3448         return JNI_FALSE;
3449     }
3450 
3451     auto result = gnssConfigurationIface->setGlonassPositioningProtocol(gnssPosProtocol);
3452     return checkHidlReturn(result, "IGnssConfiguration setGlonassPositioningProtocol() failed.");
3453 }
3454 
android_location_GnssConfiguration_set_satellite_blacklist(JNIEnv * env,jobject,jintArray constellations,jintArray sv_ids)3455 static jboolean android_location_GnssConfiguration_set_satellite_blacklist(
3456         JNIEnv* env, jobject, jintArray constellations, jintArray sv_ids) {
3457     if (gnssConfigurationIface_V1_1 == nullptr && gnssConfigurationIface_V2_1 == nullptr) {
3458         ALOGI("IGnssConfiguration interface does not support satellite blacklist.");
3459         return JNI_FALSE;
3460     }
3461 
3462     jint *constellation_array = env->GetIntArrayElements(constellations, 0);
3463     if (nullptr == constellation_array) {
3464         ALOGI("GetIntArrayElements returns nullptr.");
3465         return JNI_FALSE;
3466     }
3467     jsize length = env->GetArrayLength(constellations);
3468 
3469     jint *sv_id_array = env->GetIntArrayElements(sv_ids, 0);
3470     if (nullptr == sv_id_array) {
3471         ALOGI("GetIntArrayElements returns nullptr.");
3472         return JNI_FALSE;
3473     }
3474 
3475     if (length != env->GetArrayLength(sv_ids)) {
3476         ALOGI("Lengths of constellations and sv_ids are inconsistent.");
3477         return JNI_FALSE;
3478     }
3479 
3480     if (gnssConfigurationIface_V2_1 != nullptr) {
3481         hidl_vec<IGnssConfiguration_V2_1::BlacklistedSource> sources;
3482         sources.resize(length);
3483 
3484         for (int i = 0; i < length; i++) {
3485             sources[i].constellation = static_cast<GnssConstellationType_V2_0>(constellation_array[i]);
3486             sources[i].svid = sv_id_array[i];
3487         }
3488 
3489         auto result = gnssConfigurationIface_V2_1->setBlacklist_2_1(sources);
3490         return checkHidlReturn(result, "IGnssConfiguration_V2_1 setBlacklist_2_1() failed.");
3491     }
3492 
3493     hidl_vec<IGnssConfiguration_V1_1::BlacklistedSource> sources;
3494     sources.resize(length);
3495 
3496     for (int i = 0; i < length; i++) {
3497         sources[i].constellation = static_cast<GnssConstellationType_V1_0>(constellation_array[i]);
3498         sources[i].svid = sv_id_array[i];
3499     }
3500 
3501     auto result = gnssConfigurationIface_V1_1->setBlacklist(sources);
3502     return checkHidlReturn(result, "IGnssConfiguration setBlacklist() failed.");
3503 }
3504 
android_location_GnssConfiguration_set_es_extension_sec(JNIEnv *,jobject,jint emergencyExtensionSeconds)3505 static jboolean android_location_GnssConfiguration_set_es_extension_sec(
3506         JNIEnv*, jobject, jint emergencyExtensionSeconds) {
3507     if (gnssConfigurationIface == nullptr) {
3508         ALOGE("%s: IGnssConfiguration interface not available.", __func__);
3509         return JNI_FALSE;
3510     }
3511 
3512     if (gnssConfigurationIface_V2_0 == nullptr) {
3513         ALOGI("Config parameter ES_EXTENSION_SEC is not supported in IGnssConfiguration.hal"
3514                 " versions earlier than 2.0.");
3515         return JNI_FALSE;
3516     }
3517 
3518     auto result = gnssConfigurationIface_V2_0->setEsExtensionSec(emergencyExtensionSeconds);
3519     return checkHidlReturn(result, "IGnssConfiguration setEsExtensionSec() failed.");
3520 }
3521 
android_location_GnssBatchingProvider_get_batch_size(JNIEnv *,jclass)3522 static jint android_location_GnssBatchingProvider_get_batch_size(JNIEnv*, jclass) {
3523     if (gnssBatchingIface == nullptr) {
3524         return 0; // batching not supported, size = 0
3525     }
3526     auto result = gnssBatchingIface->getBatchSize();
3527     if (!checkHidlReturn(result, "IGnssBatching getBatchSize() failed.")) {
3528         return 0; // failure in binder, don't support batching
3529     }
3530 
3531     return static_cast<jint>(result);
3532 }
3533 
android_location_GnssBatchingProvider_init_batching(JNIEnv *,jclass)3534 static jboolean android_location_GnssBatchingProvider_init_batching(JNIEnv*, jclass) {
3535     if (gnssBatchingIface_V2_0 != nullptr) {
3536         sp<IGnssBatchingCallback_V2_0> gnssBatchingCbIface_V2_0 = new GnssBatchingCallback_V2_0();
3537         auto result = gnssBatchingIface_V2_0->init_2_0(gnssBatchingCbIface_V2_0);
3538         return checkHidlReturn(result, "IGnssBatching init_2_0() failed.");
3539     } else if (gnssBatchingIface != nullptr) {
3540         sp<IGnssBatchingCallback_V1_0> gnssBatchingCbIface_V1_0 = new GnssBatchingCallback_V1_0();
3541         auto result = gnssBatchingIface->init(gnssBatchingCbIface_V1_0);
3542         return checkHidlReturn(result, "IGnssBatching init() failed.");
3543     } else {
3544         return JNI_FALSE; // batching not supported
3545     }
3546 }
3547 
android_location_GnssBatchingProvider_cleanup_batching(JNIEnv *,jclass)3548 static void android_location_GnssBatchingProvider_cleanup_batching(JNIEnv*, jclass) {
3549     if (gnssBatchingIface == nullptr) {
3550         return; // batching not supported
3551     }
3552     auto result = gnssBatchingIface->cleanup();
3553     checkHidlReturn(result, "IGnssBatching cleanup() failed.");
3554 }
3555 
android_location_GnssBatchingProvider_start_batch(JNIEnv *,jclass,jlong periodNanos,jboolean wakeOnFifoFull)3556 static jboolean android_location_GnssBatchingProvider_start_batch(JNIEnv*, jclass,
3557         jlong periodNanos, jboolean wakeOnFifoFull) {
3558     if (gnssBatchingIface == nullptr) {
3559         return JNI_FALSE; // batching not supported
3560     }
3561 
3562     IGnssBatching_V1_0::Options options;
3563     options.periodNanos = periodNanos;
3564     if (wakeOnFifoFull) {
3565         options.flags = static_cast<uint8_t>(IGnssBatching_V1_0::Flag::WAKEUP_ON_FIFO_FULL);
3566     } else {
3567         options.flags = 0;
3568     }
3569 
3570     auto result = gnssBatchingIface->start(options);
3571     return checkHidlReturn(result, "IGnssBatching start() failed.");
3572 }
3573 
android_location_GnssBatchingProvider_flush_batch(JNIEnv *,jclass)3574 static void android_location_GnssBatchingProvider_flush_batch(JNIEnv*, jclass) {
3575     if (gnssBatchingIface == nullptr) {
3576         return; // batching not supported
3577     }
3578     auto result = gnssBatchingIface->flush();
3579     checkHidlReturn(result, "IGnssBatching flush() failed.");
3580 }
3581 
android_location_GnssBatchingProvider_stop_batch(JNIEnv *,jclass)3582 static jboolean android_location_GnssBatchingProvider_stop_batch(JNIEnv*, jclass) {
3583     if (gnssBatchingIface == nullptr) {
3584         return JNI_FALSE; // batching not supported
3585     }
3586     auto result = gnssBatchingIface->stop();
3587     return checkHidlReturn(result, "IGnssBatching stop() failed.");
3588 }
3589 
android_location_GnssVisibilityControl_enable_nfw_location_access(JNIEnv * env,jobject,jobjectArray proxyApps)3590 static jboolean android_location_GnssVisibilityControl_enable_nfw_location_access(
3591         JNIEnv* env, jobject, jobjectArray proxyApps) {
3592     if (gnssVisibilityControlIface == nullptr) {
3593         ALOGI("IGnssVisibilityControl interface not available.");
3594         return JNI_FALSE;
3595     }
3596 
3597     const jsize length = env->GetArrayLength(proxyApps);
3598     hidl_vec<hidl_string> hidlProxyApps(length);
3599     for (int i = 0; i < length; ++i) {
3600         jstring proxyApp = (jstring) (env->GetObjectArrayElement(proxyApps, i));
3601         ScopedJniString jniProxyApp(env, proxyApp);
3602         hidlProxyApps[i] = jniProxyApp;
3603     }
3604 
3605     auto result = gnssVisibilityControlIface->enableNfwLocationAccess(hidlProxyApps);
3606     return checkHidlReturn(result, "IGnssVisibilityControl enableNfwLocationAccess() failed.");
3607 }
3608 
3609 static const JNINativeMethod sMethods[] = {
3610      /* name, signature, funcPtr */
3611     {"class_init_native", "()V", reinterpret_cast<void *>(
3612             android_location_GnssLocationProvider_class_init_native)},
3613     {"native_is_supported", "()Z", reinterpret_cast<void *>(
3614             android_location_GnssLocationProvider_is_supported)},
3615     {"native_init_once", "(Z)V", reinterpret_cast<void *>(
3616             android_location_GnssLocationProvider_init_once)},
3617     {"native_init", "()Z", reinterpret_cast<void *>(android_location_GnssLocationProvider_init)},
3618     {"native_cleanup", "()V", reinterpret_cast<void *>(
3619             android_location_GnssLocationProvider_cleanup)},
3620     {"native_set_position_mode", "(IIIIIZ)Z", reinterpret_cast<void *>(
3621             android_location_GnssLocationProvider_set_position_mode)},
3622     {"native_start", "()Z", reinterpret_cast<void *>(
3623             android_location_GnssLocationProvider_start)},
3624     {"native_stop", "()Z", reinterpret_cast<void *>(
3625             android_location_GnssLocationProvider_stop)},
3626     {"native_delete_aiding_data", "(I)V", reinterpret_cast<void *>(
3627             android_location_GnssLocationProvider_delete_aiding_data)},
3628     {"native_read_nmea", "([BI)I", reinterpret_cast<void *>(
3629             android_location_GnssLocationProvider_read_nmea)},
3630     {"native_inject_time", "(JJI)V", reinterpret_cast<void *>(
3631             android_location_GnssLocationProvider_inject_time)},
3632     {"native_inject_best_location", "(IDDDFFFFFFJIJD)V", reinterpret_cast<void *>(
3633             android_location_GnssLocationProvider_inject_best_location)},
3634     {"native_inject_location", "(DDF)V", reinterpret_cast<void *>(
3635             android_location_GnssLocationProvider_inject_location)},
3636     {"native_supports_psds", "()Z", reinterpret_cast<void *>(
3637             android_location_GnssLocationProvider_supports_psds)},
3638     {"native_inject_psds_data", "([BI)V", reinterpret_cast<void *>(
3639             android_location_GnssLocationProvider_inject_psds_data)},
3640     {"native_agps_set_id", "(ILjava/lang/String;)V", reinterpret_cast<void *>(
3641             android_location_GnssLocationProvider_agps_set_id)},
3642     {"native_agps_set_ref_location_cellid", "(IIIII)V", reinterpret_cast<void *>(
3643             android_location_GnssLocationProvider_agps_set_reference_location_cellid)},
3644     {"native_set_agps_server", "(ILjava/lang/String;I)V", reinterpret_cast<void *>(
3645             android_location_GnssLocationProvider_set_agps_server)},
3646     {"native_send_ni_response", "(II)V", reinterpret_cast<void *>(
3647             android_location_GnssLocationProvider_send_ni_response)},
3648     {"native_get_internal_state", "()Ljava/lang/String;", reinterpret_cast<void *>(
3649             android_location_GnssLocationProvider_get_internal_state)},
3650     {"native_is_gnss_visibility_control_supported", "()Z", reinterpret_cast<void *>(
3651             android_location_GnssLocationProvider_is_gnss_visibility_control_supported)},
3652 };
3653 
3654 static const JNINativeMethod sMethodsBatching[] = {
3655      /* name, signature, funcPtr */
3656     {"native_get_batch_size",
3657             "()I",
3658             reinterpret_cast<void *>(android_location_GnssBatchingProvider_get_batch_size)},
3659     {"native_start_batch",
3660             "(JZ)Z",
3661             reinterpret_cast<void *>(android_location_GnssBatchingProvider_start_batch)},
3662     {"native_flush_batch",
3663             "()V",
3664             reinterpret_cast<void *>(android_location_GnssBatchingProvider_flush_batch)},
3665     {"native_stop_batch",
3666             "()Z",
3667             reinterpret_cast<void *>(android_location_GnssBatchingProvider_stop_batch)},
3668     {"native_init_batching",
3669             "()Z",
3670             reinterpret_cast<void *>(android_location_GnssBatchingProvider_init_batching)},
3671     {"native_cleanup_batching",
3672             "()V",
3673             reinterpret_cast<void *>(android_location_GnssBatchingProvider_cleanup_batching)},
3674 };
3675 
3676 static const JNINativeMethod sAntennaInfoMethods[] = {
3677         /* name, signature, funcPtr */
3678         {"native_is_antenna_info_supported", "()Z",
3679          reinterpret_cast<void*>(
3680                  android_location_GnssAntennaInfoProvider_is_antenna_info_supported)},
3681         {"native_start_antenna_info_listening", "()Z",
3682          reinterpret_cast<void*>(
3683                  android_location_GnssAntennaInfoProvider_start_antenna_info_listening)},
3684         {"native_stop_antenna_info_listening", "()Z",
3685          reinterpret_cast<void*>(
3686                  android_location_GnssAntennaInfoProvider_stop_antenna_info_listening)},
3687 };
3688 
3689 static const JNINativeMethod sGeofenceMethods[] = {
3690      /* name, signature, funcPtr */
3691     {"native_is_geofence_supported",
3692             "()Z",
3693             reinterpret_cast<void *>(android_location_GnssGeofenceProvider_is_geofence_supported)},
3694     {"native_add_geofence",
3695             "(IDDDIIII)Z",
3696             reinterpret_cast<void *>(android_location_GnssGeofenceProvider_add_geofence)},
3697     {"native_remove_geofence",
3698             "(I)Z",
3699             reinterpret_cast<void *>(android_location_GnssGeofenceProvider_remove_geofence)},
3700     {"native_pause_geofence", "(I)Z", reinterpret_cast<void *>(
3701             android_location_GnssGeofenceProvider_pause_geofence)},
3702     {"native_resume_geofence",
3703             "(II)Z",
3704             reinterpret_cast<void *>(android_location_GnssGeofenceProvider_resume_geofence)},
3705 };
3706 
3707 static const JNINativeMethod sMeasurementMethods[] = {
3708     /* name, signature, funcPtr */
3709     {"native_is_measurement_supported", "()Z",
3710             reinterpret_cast<void*>(
3711             android_location_GnssMeasurementsProvider_is_measurement_supported)},
3712     {"native_start_measurement_collection", "(Z)Z",
3713             reinterpret_cast<void*>(
3714             android_location_GnssMeasurementsProvider_start_measurement_collection)},
3715     {"native_stop_measurement_collection", "()Z",
3716             reinterpret_cast<void*>(
3717             android_location_GnssMeasurementsProvider_stop_measurement_collection)},
3718 };
3719 
3720 static const JNINativeMethod sMeasurementCorrectionsMethods[] = {
3721     /* name, signature, funcPtr */
3722     {"native_is_measurement_corrections_supported", "()Z",
3723             reinterpret_cast<void*>(
3724             android_location_GnssMeasurementCorrectionsProvider_is_measurement_corrections_supported)},
3725     {"native_inject_gnss_measurement_corrections",
3726             "(Landroid/location/GnssMeasurementCorrections;)Z",
3727             reinterpret_cast<void*>(
3728             android_location_GnssMeasurementCorrectionsProvider_inject_gnss_measurement_corrections)},
3729 };
3730 
3731 static const JNINativeMethod sNavigationMessageMethods[] = {
3732      /* name, signature, funcPtr */
3733     {"native_is_navigation_message_supported",
3734             "()Z",
3735             reinterpret_cast<void *>(
3736                     android_location_GnssNavigationMessageProvider_is_navigation_message_supported)},
3737     {"native_start_navigation_message_collection",
3738             "()Z",
3739             reinterpret_cast<void *>(
3740                     android_location_GnssNavigationMessageProvider_start_navigation_message_collection)},
3741     {"native_stop_navigation_message_collection",
3742             "()Z",
3743             reinterpret_cast<void *>(
3744                     android_location_GnssNavigationMessageProvider_stop_navigation_message_collection)},
3745 };
3746 
3747 static const JNINativeMethod sNetworkConnectivityMethods[] = {
3748      /* name, signature, funcPtr */
3749     {"native_is_agps_ril_supported", "()Z",
3750             reinterpret_cast<void *>(android_location_GnssNetworkConnectivityHandler_is_agps_ril_supported)},
3751     {"native_update_network_state",
3752             "(ZIZZLjava/lang/String;JS)V",
3753             reinterpret_cast<void *>(android_location_GnssNetworkConnectivityHandler_update_network_state)},
3754     {"native_agps_data_conn_open",
3755             "(JLjava/lang/String;I)V",
3756             reinterpret_cast<void *>(android_location_GnssNetworkConnectivityHandler_agps_data_conn_open)},
3757     {"native_agps_data_conn_closed",
3758             "()V",
3759             reinterpret_cast<void *>(android_location_GnssNetworkConnectivityHandler_agps_data_conn_closed)},
3760     {"native_agps_data_conn_failed",
3761             "()V",
3762             reinterpret_cast<void *>(android_location_GnssNetworkConnectivityHandler_agps_data_conn_failed)},
3763 };
3764 
3765 static const JNINativeMethod sConfigurationMethods[] = {
3766         /* name, signature, funcPtr */
3767         {"native_get_gnss_configuration_version",
3768          "()Lcom/android/server/location/gnss/GnssConfiguration$HalInterfaceVersion;",
3769          reinterpret_cast<void*>(
3770                  android_location_GnssConfiguration_get_gnss_configuration_version)},
3771         {"native_set_supl_es", "(I)Z",
3772          reinterpret_cast<void*>(android_location_GnssConfiguration_set_supl_es)},
3773         {"native_set_supl_version", "(I)Z",
3774          reinterpret_cast<void*>(android_location_GnssConfiguration_set_supl_version)},
3775         {"native_set_supl_mode", "(I)Z",
3776          reinterpret_cast<void*>(android_location_GnssConfiguration_set_supl_mode)},
3777         {"native_set_lpp_profile", "(I)Z",
3778          reinterpret_cast<void*>(android_location_GnssConfiguration_set_lpp_profile)},
3779         {"native_set_gnss_pos_protocol_select", "(I)Z",
3780          reinterpret_cast<void*>(android_location_GnssConfiguration_set_gnss_pos_protocol_select)},
3781         {"native_set_gps_lock", "(I)Z",
3782          reinterpret_cast<void*>(android_location_GnssConfiguration_set_gps_lock)},
3783         {"native_set_emergency_supl_pdn", "(I)Z",
3784          reinterpret_cast<void*>(android_location_GnssConfiguration_set_emergency_supl_pdn)},
3785         {"native_set_satellite_blacklist", "([I[I)Z",
3786          reinterpret_cast<void*>(android_location_GnssConfiguration_set_satellite_blacklist)},
3787         {"native_set_es_extension_sec", "(I)Z",
3788          reinterpret_cast<void*>(android_location_GnssConfiguration_set_es_extension_sec)},
3789 };
3790 
3791 static const JNINativeMethod sVisibilityControlMethods[] = {
3792      /* name, signature, funcPtr */
3793     {"native_enable_nfw_location_access",
3794             "([Ljava/lang/String;)Z",
3795             reinterpret_cast<void *>(
3796                     android_location_GnssVisibilityControl_enable_nfw_location_access)},
3797 };
3798 
register_android_server_location_GnssLocationProvider(JNIEnv * env)3799 int register_android_server_location_GnssLocationProvider(JNIEnv* env) {
3800     jniRegisterNativeMethods(env, "com/android/server/location/gnss/GnssAntennaInfoProvider",
3801                              sAntennaInfoMethods, NELEM(sAntennaInfoMethods));
3802     jniRegisterNativeMethods(env, "com/android/server/location/gnss/GnssBatchingProvider",
3803                              sMethodsBatching, NELEM(sMethodsBatching));
3804     jniRegisterNativeMethods(env, "com/android/server/location/gnss/GnssGeofenceProvider",
3805                              sGeofenceMethods, NELEM(sGeofenceMethods));
3806     jniRegisterNativeMethods(env, "com/android/server/location/gnss/GnssMeasurementsProvider",
3807                              sMeasurementMethods, NELEM(sMeasurementMethods));
3808     jniRegisterNativeMethods(env,
3809                              "com/android/server/location/gnss/GnssMeasurementCorrectionsProvider",
3810                              sMeasurementCorrectionsMethods, NELEM(sMeasurementCorrectionsMethods));
3811     jniRegisterNativeMethods(env, "com/android/server/location/gnss/GnssNavigationMessageProvider",
3812                              sNavigationMessageMethods, NELEM(sNavigationMessageMethods));
3813     jniRegisterNativeMethods(env, "com/android/server/location/gnss/GnssNetworkConnectivityHandler",
3814                              sNetworkConnectivityMethods, NELEM(sNetworkConnectivityMethods));
3815     jniRegisterNativeMethods(env, "com/android/server/location/gnss/GnssConfiguration",
3816                              sConfigurationMethods, NELEM(sConfigurationMethods));
3817     jniRegisterNativeMethods(env, "com/android/server/location/gnss/GnssVisibilityControl",
3818                              sVisibilityControlMethods, NELEM(sVisibilityControlMethods));
3819     return jniRegisterNativeMethods(env, "com/android/server/location/gnss/GnssLocationProvider",
3820                                     sMethods, NELEM(sMethods));
3821 }
3822 
3823 } /* namespace android */
3824