1 /* Copyright (c) 2011-2014, 2016-2021 The Linux Foundation. All rights reserved.
2 *
3 * Redistribution and use in source and binary forms, with or without
4 * modification, are permitted provided that the following conditions are
5 * met:
6 * * Redistributions of source code must retain the above copyright
7 * notice, this list of conditions and the following disclaimer.
8 * * Redistributions in binary form must reproduce the above
9 * copyright notice, this list of conditions and the following
10 * disclaimer in the documentation and/or other materials provided
11 * with the distribution.
12 * * Neither the name of The Linux Foundation, nor the names of its
13 * contributors may be used to endorse or promote products derived
14 * from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
20 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
23 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
24 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
25 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
26 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 */
29 #define LOG_NDEBUG 0 //Define to enable LOGV
30 #define LOG_TAG "LocSvc_LocApiBase"
31
32 #include <dlfcn.h>
33 #include <inttypes.h>
34 #include <gps_extended_c.h>
35 #include <LocApiBase.h>
36 #include <LocAdapterBase.h>
37 #include <log_util.h>
38 #include <LocContext.h>
39 #include <loc_misc_utils.h>
40
41 namespace loc_core {
42
43 #define TO_ALL_LOCADAPTERS(call) TO_ALL_ADAPTERS(mLocAdapters, (call))
44 #define TO_1ST_HANDLING_LOCADAPTERS(call) TO_1ST_HANDLING_ADAPTER(mLocAdapters, (call))
45
hexcode(char * hexstring,int string_size,const char * data,int data_size)46 int hexcode(char *hexstring, int string_size,
47 const char *data, int data_size)
48 {
49 int i;
50 for (i = 0; i < data_size; i++)
51 {
52 char ch = data[i];
53 if (i*2 + 3 <= string_size)
54 {
55 snprintf(&hexstring[i*2], 3, "%02X", ch);
56 }
57 else {
58 break;
59 }
60 }
61 return i;
62 }
63
decodeAddress(char * addr_string,int string_size,const char * data,int data_size)64 int decodeAddress(char *addr_string, int string_size,
65 const char *data, int data_size)
66 {
67 const char addr_prefix = 0x91;
68 int i, idxOutput = 0;
69
70 if (!data || !addr_string) { return 0; }
71
72 if (data[0] != addr_prefix)
73 {
74 LOC_LOGW("decodeAddress: address prefix is not 0x%x but 0x%x", addr_prefix, data[0]);
75 addr_string[0] = '\0';
76 return 0; // prefix not correct
77 }
78
79 for (i = 1; i < data_size; i++)
80 {
81 unsigned char ch = data[i], low = ch & 0x0F, hi = ch >> 4;
82 if (low <= 9 && idxOutput < string_size - 1) { addr_string[idxOutput++] = low + '0'; }
83 if (hi <= 9 && idxOutput < string_size - 1) { addr_string[idxOutput++] = hi + '0'; }
84 }
85
86 addr_string[idxOutput] = '\0'; // Terminates the string
87
88 return idxOutput;
89 }
90
91 struct LocSsrMsg : public LocMsg {
92 LocApiBase* mLocApi;
LocSsrMsgloc_core::LocSsrMsg93 inline LocSsrMsg(LocApiBase* locApi) :
94 LocMsg(), mLocApi(locApi)
95 {
96 locallog();
97 }
procloc_core::LocSsrMsg98 inline virtual void proc() const {
99 mLocApi->close();
100 if (LOC_API_ADAPTER_ERR_SUCCESS == mLocApi->open(mLocApi->getEvtMask())) {
101 // Notify adapters that engine up after SSR
102 mLocApi->handleEngineUpEvent();
103 }
104 }
locallogloc_core::LocSsrMsg105 inline void locallog() const {
106 LOC_LOGV("LocSsrMsg");
107 }
logloc_core::LocSsrMsg108 inline virtual void log() const {
109 locallog();
110 }
111 };
112
113 struct LocOpenMsg : public LocMsg {
114 LocApiBase* mLocApi;
115 LocAdapterBase* mAdapter;
LocOpenMsgloc_core::LocOpenMsg116 inline LocOpenMsg(LocApiBase* locApi, LocAdapterBase* adapter = nullptr) :
117 LocMsg(), mLocApi(locApi), mAdapter(adapter)
118 {
119 locallog();
120 }
procloc_core::LocOpenMsg121 inline virtual void proc() const {
122 if (LOC_API_ADAPTER_ERR_SUCCESS == mLocApi->open(mLocApi->getEvtMask()) &&
123 nullptr != mAdapter) {
124 mAdapter->handleEngineUpEvent();
125 }
126 }
locallogloc_core::LocOpenMsg127 inline void locallog() const {
128 LOC_LOGv("LocOpen Mask: %" PRIx64 "\n", mLocApi->getEvtMask());
129 }
logloc_core::LocOpenMsg130 inline virtual void log() const {
131 locallog();
132 }
133 };
134
135 struct LocCloseMsg : public LocMsg {
136 LocApiBase* mLocApi;
LocCloseMsgloc_core::LocCloseMsg137 inline LocCloseMsg(LocApiBase* locApi) :
138 LocMsg(), mLocApi(locApi)
139 {
140 locallog();
141 }
procloc_core::LocCloseMsg142 inline virtual void proc() const {
143 mLocApi->close();
144 }
locallogloc_core::LocCloseMsg145 inline void locallog() const {
146 }
logloc_core::LocCloseMsg147 inline virtual void log() const {
148 locallog();
149 }
150 };
151
152 MsgTask* LocApiBase::mMsgTask = nullptr;
153 volatile int32_t LocApiBase::mMsgTaskRefCount = 0;
154
LocApiBase(LOC_API_ADAPTER_EVENT_MASK_T excludedMask,ContextBase * context)155 LocApiBase::LocApiBase(LOC_API_ADAPTER_EVENT_MASK_T excludedMask,
156 ContextBase* context) :
157 mContext(context),
158 mMask(0), mExcludedMask(excludedMask)
159 {
160 memset(mLocAdapters, 0, sizeof(mLocAdapters));
161
162 android_atomic_inc(&mMsgTaskRefCount);
163 if (nullptr == mMsgTask) {
164 mMsgTask = new MsgTask("LocApiMsgTask");
165 }
166 }
167
getEvtMask()168 LOC_API_ADAPTER_EVENT_MASK_T LocApiBase::getEvtMask()
169 {
170 LOC_API_ADAPTER_EVENT_MASK_T mask = 0;
171
172 TO_ALL_LOCADAPTERS(mask |= mLocAdapters[i]->getEvtMask());
173
174 return mask & ~mExcludedMask;
175 }
176
isMaster()177 bool LocApiBase::isMaster()
178 {
179 bool isMaster = false;
180
181 for (int i = 0;
182 !isMaster && i < MAX_ADAPTERS && NULL != mLocAdapters[i];
183 i++) {
184 isMaster |= mLocAdapters[i]->isAdapterMaster();
185 }
186 return isMaster;
187 }
188
isInSession()189 bool LocApiBase::isInSession()
190 {
191 bool inSession = false;
192
193 for (int i = 0;
194 !inSession && i < MAX_ADAPTERS && NULL != mLocAdapters[i];
195 i++) {
196 inSession = mLocAdapters[i]->isInSession();
197 }
198
199 return inSession;
200 }
201
needReport(const UlpLocation & ulpLocation,enum loc_sess_status status,LocPosTechMask techMask)202 bool LocApiBase::needReport(const UlpLocation& ulpLocation,
203 enum loc_sess_status status,
204 LocPosTechMask techMask)
205 {
206 bool reported = false;
207
208 if (LOC_SESS_SUCCESS == status) {
209 // this is a final fix
210 LocPosTechMask mask =
211 LOC_POS_TECH_MASK_SATELLITE | LOC_POS_TECH_MASK_SENSORS | LOC_POS_TECH_MASK_HYBRID;
212 // it is a Satellite fix or a sensor fix
213 reported = (mask & techMask);
214 }
215 else if (LOC_SESS_INTERMEDIATE == status &&
216 LOC_SESS_INTERMEDIATE == ContextBase::mGps_conf.INTERMEDIATE_POS) {
217 // this is a intermediate fix and we accept intermediate
218
219 // it is NOT the case that
220 // there is inaccuracy; and
221 // we care about inaccuracy; and
222 // the inaccuracy exceeds our tolerance
223 reported = !((ulpLocation.gpsLocation.flags & LOC_GPS_LOCATION_HAS_ACCURACY) &&
224 (ContextBase::mGps_conf.ACCURACY_THRES != 0) &&
225 (ulpLocation.gpsLocation.accuracy > ContextBase::mGps_conf.ACCURACY_THRES));
226 }
227
228 return reported;
229 }
230
addAdapter(LocAdapterBase * adapter)231 void LocApiBase::addAdapter(LocAdapterBase* adapter)
232 {
233 for (int i = 0; i < MAX_ADAPTERS && mLocAdapters[i] != adapter; i++) {
234 if (mLocAdapters[i] == NULL) {
235 mLocAdapters[i] = adapter;
236 sendMsg(new LocOpenMsg(this, adapter));
237 break;
238 }
239 }
240 }
241
removeAdapter(LocAdapterBase * adapter)242 void LocApiBase::removeAdapter(LocAdapterBase* adapter)
243 {
244 for (int i = 0;
245 i < MAX_ADAPTERS && NULL != mLocAdapters[i];
246 i++) {
247 if (mLocAdapters[i] == adapter) {
248 mLocAdapters[i] = NULL;
249
250 // shift the rest of the adapters up so that the pointers
251 // in the array do not have holes. This should be more
252 // performant, because the array maintenance is much much
253 // less frequent than event handlings, which need to linear
254 // search all the adapters
255 int j = i;
256 while (++i < MAX_ADAPTERS && mLocAdapters[i] != NULL);
257
258 // i would be MAX_ADAPTERS or point to a NULL
259 i--;
260 // i now should point to a none NULL adapter within valid
261 // range although i could be equal to j, but it won't hurt.
262 // No need to check it, as it gains nothing.
263 mLocAdapters[j] = mLocAdapters[i];
264 // this makes sure that we exit the for loop
265 mLocAdapters[i] = NULL;
266
267 // if we have an empty list of adapters
268 if (0 == i) {
269 sendMsg(new LocCloseMsg(this));
270 } else {
271 // else we need to remove the bit
272 sendMsg(new LocOpenMsg(this));
273 }
274 }
275 }
276 }
277
updateEvtMask()278 void LocApiBase::updateEvtMask()
279 {
280 sendMsg(new LocOpenMsg(this));
281 }
282
updateNmeaMask(uint32_t mask)283 void LocApiBase::updateNmeaMask(uint32_t mask)
284 {
285 struct LocSetNmeaMsg : public LocMsg {
286 LocApiBase* mLocApi;
287 uint32_t mMask;
288 inline LocSetNmeaMsg(LocApiBase* locApi, uint32_t mask) :
289 LocMsg(), mLocApi(locApi), mMask(mask)
290 {
291 locallog();
292 }
293 inline virtual void proc() const {
294 mLocApi->setNMEATypesSync(mMask);
295 }
296 inline void locallog() const {
297 LOC_LOGv("LocSyncNmea NmeaMask: %" PRIx32 "\n", mMask);
298 }
299 inline virtual void log() const {
300 locallog();
301 }
302 };
303
304 sendMsg(new LocSetNmeaMsg(this, mask));
305 }
306
handleEngineUpEvent()307 void LocApiBase::handleEngineUpEvent()
308 {
309 // loop through adapters, and deliver to all adapters.
310 TO_ALL_LOCADAPTERS(mLocAdapters[i]->handleEngineUpEvent());
311 }
312
handleEngineDownEvent()313 void LocApiBase::handleEngineDownEvent()
314 { // This will take care of renegotiating the loc handle
315 sendMsg(new LocSsrMsg(this));
316
317 // loop through adapters, and deliver to all adapters.
318 TO_ALL_LOCADAPTERS(mLocAdapters[i]->handleEngineDownEvent());
319 }
320
reportPosition(UlpLocation & location,GpsLocationExtended & locationExtended,enum loc_sess_status status,LocPosTechMask loc_technology_mask,GnssDataNotification * pDataNotify,int msInWeek)321 void LocApiBase::reportPosition(UlpLocation& location,
322 GpsLocationExtended& locationExtended,
323 enum loc_sess_status status,
324 LocPosTechMask loc_technology_mask,
325 GnssDataNotification* pDataNotify,
326 int msInWeek)
327 {
328 // print the location info before delivering
329 LOC_LOGD("flags: %d\n source: %d\n latitude: %f\n longitude: %f\n "
330 "altitude: %f\n speed: %f\n bearing: %f\n accuracy: %f\n "
331 "timestamp: %" PRId64 "\n"
332 "Session status: %d\n Technology mask: %u\n "
333 "SV used in fix (gps/glo/bds/gal/qzss) : \
334 (0x%" PRIx64 "/0x%" PRIx64 "/0x%" PRIx64 "/0x%" PRIx64 "/0x%" PRIx64 "/0x%" PRIx64 ")",
335 location.gpsLocation.flags, location.position_source,
336 location.gpsLocation.latitude, location.gpsLocation.longitude,
337 location.gpsLocation.altitude, location.gpsLocation.speed,
338 location.gpsLocation.bearing, location.gpsLocation.accuracy,
339 location.gpsLocation.timestamp, status, loc_technology_mask,
340 locationExtended.gnss_sv_used_ids.gps_sv_used_ids_mask,
341 locationExtended.gnss_sv_used_ids.glo_sv_used_ids_mask,
342 locationExtended.gnss_sv_used_ids.bds_sv_used_ids_mask,
343 locationExtended.gnss_sv_used_ids.gal_sv_used_ids_mask,
344 locationExtended.gnss_sv_used_ids.qzss_sv_used_ids_mask,
345 locationExtended.gnss_sv_used_ids.navic_sv_used_ids_mask);
346 // loop through adapters, and deliver to all adapters.
347 TO_ALL_LOCADAPTERS(
348 mLocAdapters[i]->reportPositionEvent(location, locationExtended,
349 status, loc_technology_mask,
350 pDataNotify, msInWeek)
351 );
352 }
353
reportWwanZppFix(LocGpsLocation & zppLoc)354 void LocApiBase::reportWwanZppFix(LocGpsLocation &zppLoc)
355 {
356 // loop through adapters, and deliver to the first handling adapter.
357 TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->reportWwanZppFix(zppLoc));
358 }
359
reportZppBestAvailableFix(LocGpsLocation & zppLoc,GpsLocationExtended & location_extended,LocPosTechMask tech_mask)360 void LocApiBase::reportZppBestAvailableFix(LocGpsLocation &zppLoc,
361 GpsLocationExtended &location_extended, LocPosTechMask tech_mask)
362 {
363 // loop through adapters, and deliver to the first handling adapter.
364 TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->reportZppBestAvailableFix(zppLoc,
365 location_extended, tech_mask));
366 }
367
requestOdcpi(OdcpiRequestInfo & request)368 void LocApiBase::requestOdcpi(OdcpiRequestInfo& request)
369 {
370 // loop through adapters, and deliver to the first handling adapter.
371 TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestOdcpiEvent(request));
372 }
373
reportGnssEngEnergyConsumedEvent(uint64_t energyConsumedSinceFirstBoot)374 void LocApiBase::reportGnssEngEnergyConsumedEvent(uint64_t energyConsumedSinceFirstBoot)
375 {
376 // loop through adapters, and deliver to the first handling adapter.
377 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportGnssEngEnergyConsumedEvent(
378 energyConsumedSinceFirstBoot));
379 }
380
reportDeleteAidingDataEvent(GnssAidingData & aidingData)381 void LocApiBase::reportDeleteAidingDataEvent(GnssAidingData& aidingData) {
382 // loop through adapters, and deliver to the first handling adapter.
383 TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->reportDeleteAidingDataEvent(aidingData));
384 }
385
reportKlobucharIonoModel(GnssKlobucharIonoModel & ionoModel)386 void LocApiBase::reportKlobucharIonoModel(GnssKlobucharIonoModel & ionoModel) {
387 // loop through adapters, and deliver to the first handling adapter.
388 TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->reportKlobucharIonoModelEvent(ionoModel));
389 }
390
reportGnssAdditionalSystemInfo(GnssAdditionalSystemInfo & additionalSystemInfo)391 void LocApiBase::reportGnssAdditionalSystemInfo(GnssAdditionalSystemInfo& additionalSystemInfo) {
392 // loop through adapters, and deliver to the first handling adapter.
393 TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->reportGnssAdditionalSystemInfoEvent(
394 additionalSystemInfo));
395 }
396
sendNfwNotification(GnssNfwNotification & notification)397 void LocApiBase::sendNfwNotification(GnssNfwNotification& notification)
398 {
399 // loop through adapters, and deliver to the first handling adapter.
400 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportNfwNotificationEvent(notification));
401
402 }
403
reportSv(GnssSvNotification & svNotify)404 void LocApiBase::reportSv(GnssSvNotification& svNotify)
405 {
406 const char* constellationString[] = { "Unknown", "GPS", "SBAS", "GLONASS",
407 "QZSS", "BEIDOU", "GALILEO", "NAVIC" };
408
409 // print the SV info before delivering
410 LOC_LOGV("num sv: %u\n"
411 " sv: constellation svid cN0 basebandCN0"
412 " elevation azimuth flags",
413 svNotify.count);
414 for (size_t i = 0; i < svNotify.count && i < GNSS_SV_MAX; i++) {
415 if (svNotify.gnssSvs[i].type >
416 sizeof(constellationString) / sizeof(constellationString[0]) - 1) {
417 svNotify.gnssSvs[i].type = GNSS_SV_TYPE_UNKNOWN;
418 }
419 // Display what we report to clients
420 LOC_LOGV(" %03zu: %*s %02d %f %f %f %f %f 0x%02X 0x%2X",
421 i,
422 13,
423 constellationString[svNotify.gnssSvs[i].type],
424 svNotify.gnssSvs[i].svId,
425 svNotify.gnssSvs[i].cN0Dbhz,
426 svNotify.gnssSvs[i].basebandCarrierToNoiseDbHz,
427 svNotify.gnssSvs[i].elevation,
428 svNotify.gnssSvs[i].azimuth,
429 svNotify.gnssSvs[i].carrierFrequencyHz,
430 svNotify.gnssSvs[i].gnssSvOptionsMask,
431 svNotify.gnssSvs[i].gnssSignalTypeMask);
432 }
433 // loop through adapters, and deliver to all adapters.
434 TO_ALL_LOCADAPTERS(
435 mLocAdapters[i]->reportSvEvent(svNotify)
436 );
437 }
438
reportSvPolynomial(GnssSvPolynomial & svPolynomial)439 void LocApiBase::reportSvPolynomial(GnssSvPolynomial &svPolynomial)
440 {
441 // loop through adapters, and deliver to all adapters.
442 TO_ALL_LOCADAPTERS(
443 mLocAdapters[i]->reportSvPolynomialEvent(svPolynomial)
444 );
445 }
446
reportSvEphemeris(GnssSvEphemerisReport & svEphemeris)447 void LocApiBase::reportSvEphemeris(GnssSvEphemerisReport & svEphemeris)
448 {
449 // loop through adapters, and deliver to all adapters.
450 TO_ALL_LOCADAPTERS(
451 mLocAdapters[i]->reportSvEphemerisEvent(svEphemeris)
452 );
453 }
454
reportStatus(LocGpsStatusValue status)455 void LocApiBase::reportStatus(LocGpsStatusValue status)
456 {
457 // loop through adapters, and deliver to all adapters.
458 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportStatus(status));
459 }
460
reportData(GnssDataNotification & dataNotify,int msInWeek)461 void LocApiBase::reportData(GnssDataNotification& dataNotify, int msInWeek)
462 {
463 // loop through adapters, and deliver to all adapters.
464 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportDataEvent(dataNotify, msInWeek));
465 }
466
reportNmea(const char * nmea,int length)467 void LocApiBase::reportNmea(const char* nmea, int length)
468 {
469 // loop through adapters, and deliver to all adapters.
470 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportNmeaEvent(nmea, length));
471 }
472
reportXtraServer(const char * url1,const char * url2,const char * url3,const int maxlength)473 void LocApiBase::reportXtraServer(const char* url1, const char* url2,
474 const char* url3, const int maxlength)
475 {
476 // loop through adapters, and deliver to the first handling adapter.
477 TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->reportXtraServer(url1, url2, url3, maxlength));
478
479 }
480
reportLocationSystemInfo(const LocationSystemInfo & locationSystemInfo)481 void LocApiBase::reportLocationSystemInfo(const LocationSystemInfo& locationSystemInfo)
482 {
483 // loop through adapters, and deliver to all adapters.
484 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportLocationSystemInfoEvent(locationSystemInfo));
485 }
486
reportQwesCapabilities(const std::unordered_map<LocationQwesFeatureType,bool> & featureMap)487 void LocApiBase::reportQwesCapabilities
488 (
489 const std::unordered_map<LocationQwesFeatureType, bool> &featureMap
490 )
491 {
492 // loop through adapters, and deliver to all adapters.
493 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportQwesCapabilities(featureMap));
494 }
requestXtraData()495 void LocApiBase::requestXtraData()
496 {
497 // loop through adapters, and deliver to the first handling adapter.
498 TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestXtraData());
499 }
500
requestTime()501 void LocApiBase::requestTime()
502 {
503 // loop through adapters, and deliver to the first handling adapter.
504 TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestTime());
505 }
506
requestLocation()507 void LocApiBase::requestLocation()
508 {
509 // loop through adapters, and deliver to the first handling adapter.
510 TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestLocation());
511 }
512
requestATL(int connHandle,LocAGpsType agps_type,LocApnTypeMask apn_type_mask)513 void LocApiBase::requestATL(int connHandle, LocAGpsType agps_type,
514 LocApnTypeMask apn_type_mask)
515 {
516 // loop through adapters, and deliver to the first handling adapter.
517 TO_1ST_HANDLING_LOCADAPTERS(
518 mLocAdapters[i]->requestATL(connHandle, agps_type, apn_type_mask));
519 }
520
releaseATL(int connHandle)521 void LocApiBase::releaseATL(int connHandle)
522 {
523 // loop through adapters, and deliver to the first handling adapter.
524 TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->releaseATL(connHandle));
525 }
526
requestNiNotify(GnssNiNotification & notify,const void * data,const LocInEmergency emergencyState)527 void LocApiBase::requestNiNotify(GnssNiNotification ¬ify, const void* data,
528 const LocInEmergency emergencyState)
529 {
530 // loop through adapters, and deliver to the first handling adapter.
531 TO_1ST_HANDLING_LOCADAPTERS(
532 mLocAdapters[i]->requestNiNotifyEvent(notify,
533 data,
534 emergencyState));
535 }
536
getSibling()537 void* LocApiBase :: getSibling()
538 DEFAULT_IMPL(NULL)
539
540 LocApiProxyBase* LocApiBase :: getLocApiProxy()
541 DEFAULT_IMPL(NULL)
542
543 void LocApiBase::reportGnssMeasurements(GnssMeasurements& gnssMeasurements, int msInWeek)
544 {
545 // loop through adapters, and deliver to all adapters.
546 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportGnssMeasurementsEvent(gnssMeasurements, msInWeek));
547 }
548
reportGnssSvIdConfig(const GnssSvIdConfig & config)549 void LocApiBase::reportGnssSvIdConfig(const GnssSvIdConfig& config)
550 {
551 // Print the config
552 LOC_LOGv("gloBlacklistSvMask: %" PRIu64 ", bdsBlacklistSvMask: %" PRIu64 ",\n"
553 "qzssBlacklistSvMask: %" PRIu64 ", galBlacklistSvMask: %" PRIu64 ",\n"
554 "navicBlacklistSvMask: %" PRIu64,
555 config.gloBlacklistSvMask, config.bdsBlacklistSvMask,
556 config.qzssBlacklistSvMask, config.galBlacklistSvMask, config.navicBlacklistSvMask);
557
558 // Loop through adapters, and deliver to all adapters.
559 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportGnssSvIdConfigEvent(config));
560 }
561
reportGnssSvTypeConfig(const GnssSvTypeConfig & config)562 void LocApiBase::reportGnssSvTypeConfig(const GnssSvTypeConfig& config)
563 {
564 // Print the config
565 LOC_LOGv("blacklistedMask: %" PRIu64 ", enabledMask: %" PRIu64,
566 config.blacklistedSvTypesMask, config.enabledSvTypesMask);
567
568 // Loop through adapters, and deliver to all adapters.
569 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportGnssSvTypeConfigEvent(config));
570 }
571
geofenceBreach(size_t count,uint32_t * hwIds,Location & location,GeofenceBreachType breachType,uint64_t timestamp)572 void LocApiBase::geofenceBreach(size_t count, uint32_t* hwIds, Location& location,
573 GeofenceBreachType breachType, uint64_t timestamp)
574 {
575 TO_ALL_LOCADAPTERS(mLocAdapters[i]->geofenceBreachEvent(count, hwIds, location, breachType,
576 timestamp));
577 }
578
geofenceStatus(GeofenceStatusAvailable available)579 void LocApiBase::geofenceStatus(GeofenceStatusAvailable available)
580 {
581 TO_ALL_LOCADAPTERS(mLocAdapters[i]->geofenceStatusEvent(available));
582 }
583
reportDBTPosition(UlpLocation & location,GpsLocationExtended & locationExtended,enum loc_sess_status status,LocPosTechMask loc_technology_mask)584 void LocApiBase::reportDBTPosition(UlpLocation &location, GpsLocationExtended &locationExtended,
585 enum loc_sess_status status, LocPosTechMask loc_technology_mask)
586 {
587 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportPositionEvent(location, locationExtended, status,
588 loc_technology_mask));
589 }
590
reportLocations(Location * locations,size_t count,BatchingMode batchingMode)591 void LocApiBase::reportLocations(Location* locations, size_t count, BatchingMode batchingMode)
592 {
593 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportLocationsEvent(locations, count, batchingMode));
594 }
595
reportCompletedTrips(uint32_t accumulated_distance)596 void LocApiBase::reportCompletedTrips(uint32_t accumulated_distance)
597 {
598 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportCompletedTripsEvent(accumulated_distance));
599 }
600
handleBatchStatusEvent(BatchingStatus batchStatus)601 void LocApiBase::handleBatchStatusEvent(BatchingStatus batchStatus)
602 {
603 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportBatchStatusChangeEvent(batchStatus));
604 }
605
reportGnssConfig(uint32_t sessionId,const GnssConfig & gnssConfig)606 void LocApiBase::reportGnssConfig(uint32_t sessionId, const GnssConfig& gnssConfig)
607 {
608 // loop through adapters, and deliver to the first handling adapter.
609 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportGnssConfigEvent(sessionId, gnssConfig));
610 }
611
reportLatencyInfo(GnssLatencyInfo & gnssLatencyInfo)612 void LocApiBase::reportLatencyInfo(GnssLatencyInfo& gnssLatencyInfo)
613 {
614 // loop through adapters, and deliver to the first handling adapter.
615 TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportLatencyInfoEvent(gnssLatencyInfo));
616 }
617
618 enum loc_api_adapter_err LocApiBase::
open(LOC_API_ADAPTER_EVENT_MASK_T)619 open(LOC_API_ADAPTER_EVENT_MASK_T /*mask*/)
620 DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
621
622 enum loc_api_adapter_err LocApiBase::
623 close()
624 DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
625
626 void LocApiBase::startFix(const LocPosMode& /*posMode*/, LocApiResponse* /*adapterResponse*/)
627 DEFAULT_IMPL()
628
629 void LocApiBase::stopFix(LocApiResponse* /*adapterResponse*/)
630 DEFAULT_IMPL()
631
632 void LocApiBase::
633 deleteAidingData(const GnssAidingData& /*data*/, LocApiResponse* /*adapterResponse*/)
634 DEFAULT_IMPL()
635
636 void LocApiBase::
637 injectPosition(double /*latitude*/, double /*longitude*/, float /*accuracy*/,
638 bool /*onDemandCpi*/)
639 DEFAULT_IMPL()
640
641 void LocApiBase::
642 injectPosition(const Location& /*location*/, bool /*onDemandCpi*/)
643 DEFAULT_IMPL()
644
645 void LocApiBase::
646 injectPosition(const GnssLocationInfoNotification & /*locationInfo*/, bool /*onDemandCpi*/)
647 DEFAULT_IMPL()
648
649 void LocApiBase::
650 setTime(LocGpsUtcTime /*time*/, int64_t /*timeReference*/, int /*uncertainty*/)
651 DEFAULT_IMPL()
652
653 void LocApiBase::
654 atlOpenStatus(int /*handle*/, int /*is_succ*/, char* /*apn*/, uint32_t /*apnLen*/,
655 AGpsBearerType /*bear*/, LocAGpsType /*agpsType*/,
656 LocApnTypeMask /*mask*/)
657 DEFAULT_IMPL()
658
659 void LocApiBase::
660 atlCloseStatus(int /*handle*/, int /*is_succ*/)
661 DEFAULT_IMPL()
662
663 LocationError LocApiBase::
664 setServerSync(const char* /*url*/, int /*len*/, LocServerType /*type*/)
665 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
666
667 LocationError LocApiBase::
668 setServerSync(unsigned int /*ip*/, int /*port*/, LocServerType /*type*/)
669 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
670
671 void LocApiBase::
672 informNiResponse(GnssNiResponse /*userResponse*/, const void* /*passThroughData*/)
673 DEFAULT_IMPL()
674
675 LocationError LocApiBase::
676 setSUPLVersionSync(GnssConfigSuplVersion /*version*/)
677 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
678
679 enum loc_api_adapter_err LocApiBase::
680 setNMEATypesSync (uint32_t /*typesMask*/)
681 DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
682
683 LocationError LocApiBase::
684 setLPPConfigSync(GnssConfigLppProfileMask /*profileMask*/)
685 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
686
687
688 enum loc_api_adapter_err LocApiBase::
689 setSensorPropertiesSync(bool /*gyroBiasVarianceRandomWalk_valid*/,
690 float /*gyroBiasVarianceRandomWalk*/,
691 bool /*accelBiasVarianceRandomWalk_valid*/,
692 float /*accelBiasVarianceRandomWalk*/,
693 bool /*angleBiasVarianceRandomWalk_valid*/,
694 float /*angleBiasVarianceRandomWalk*/,
695 bool /*rateBiasVarianceRandomWalk_valid*/,
696 float /*rateBiasVarianceRandomWalk*/,
697 bool /*velocityBiasVarianceRandomWalk_valid*/,
698 float /*velocityBiasVarianceRandomWalk*/)
699 DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
700
701 enum loc_api_adapter_err LocApiBase::
702 setSensorPerfControlConfigSync(int /*controlMode*/,
703 int /*accelSamplesPerBatch*/,
704 int /*accelBatchesPerSec*/,
705 int /*gyroSamplesPerBatch*/,
706 int /*gyroBatchesPerSec*/,
707 int /*accelSamplesPerBatchHigh*/,
708 int /*accelBatchesPerSecHigh*/,
709 int /*gyroSamplesPerBatchHigh*/,
710 int /*gyroBatchesPerSecHigh*/,
711 int /*algorithmConfig*/)
712 DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
713
714 LocationError LocApiBase::
715 setAGLONASSProtocolSync(GnssConfigAGlonassPositionProtocolMask /*aGlonassProtocol*/)
716 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
717
718 LocationError LocApiBase::
719 setLPPeProtocolCpSync(GnssConfigLppeControlPlaneMask /*lppeCP*/)
720 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
721
722 LocationError LocApiBase::
723 setLPPeProtocolUpSync(GnssConfigLppeUserPlaneMask /*lppeUP*/)
724 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
725
726 GnssConfigSuplVersion LocApiBase::convertSuplVersion(const uint32_t /*suplVersion*/)
727 DEFAULT_IMPL(GNSS_CONFIG_SUPL_VERSION_1_0_0)
728
729 GnssConfigLppeControlPlaneMask LocApiBase::convertLppeCp(const uint32_t /*lppeControlPlaneMask*/)
730 DEFAULT_IMPL(0)
731
732 GnssConfigLppeUserPlaneMask LocApiBase::convertLppeUp(const uint32_t /*lppeUserPlaneMask*/)
733 DEFAULT_IMPL(0)
734
735 LocationError LocApiBase::setEmergencyExtensionWindowSync(
736 const uint32_t /*emergencyExtensionSeconds*/)
737 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
738
739 void LocApiBase::setMeasurementCorrections(
740 const GnssMeasurementCorrections& /*gnssMeasurementCorrections*/)
741 DEFAULT_IMPL()
742
743 void LocApiBase::
744 getWwanZppFix()
745 DEFAULT_IMPL()
746
747 void LocApiBase::
748 getBestAvailableZppFix()
749 DEFAULT_IMPL()
750
751 LocationError LocApiBase::
752 setGpsLockSync(GnssConfigGpsLock /*lock*/)
753 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
754
755 void LocApiBase::
756 requestForAidingData(GnssAidingDataSvMask /*svDataMask*/)
757 DEFAULT_IMPL()
758
759 LocationError LocApiBase::
760 setXtraVersionCheckSync(uint32_t /*check*/)
761 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
762
763 LocationError LocApiBase::setBlacklistSvSync(const GnssSvIdConfig& /*config*/)
764 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
765
766 void LocApiBase::setBlacklistSv(const GnssSvIdConfig& /*config*/,
767 LocApiResponse* /*adapterResponse*/)
768 DEFAULT_IMPL()
769
770 void LocApiBase::getBlacklistSv()
771 DEFAULT_IMPL()
772
773 void LocApiBase::setConstellationControl(const GnssSvTypeConfig& /*config*/,
774 LocApiResponse* /*adapterResponse*/)
775 DEFAULT_IMPL()
776
777 void LocApiBase::getConstellationControl()
778 DEFAULT_IMPL()
779
780 void LocApiBase::resetConstellationControl(LocApiResponse* /*adapterResponse*/)
781 DEFAULT_IMPL()
782
783 void LocApiBase::
784 setConstrainedTuncMode(bool /*enabled*/,
785 float /*tuncConstraint*/,
786 uint32_t /*energyBudget*/,
787 LocApiResponse* /*adapterResponse*/)
788 DEFAULT_IMPL()
789
790 void LocApiBase::
791 setPositionAssistedClockEstimatorMode(bool /*enabled*/,
792 LocApiResponse* /*adapterResponse*/)
793 DEFAULT_IMPL()
794
795 void LocApiBase::getGnssEnergyConsumed()
796 DEFAULT_IMPL()
797
798
799 void LocApiBase::addGeofence(uint32_t /*clientId*/, const GeofenceOption& /*options*/,
800 const GeofenceInfo& /*info*/,
801 LocApiResponseData<LocApiGeofenceData>* /*adapterResponseData*/)
802 DEFAULT_IMPL()
803
804 void LocApiBase::removeGeofence(uint32_t /*hwId*/, uint32_t /*clientId*/,
805 LocApiResponse* /*adapterResponse*/)
806 DEFAULT_IMPL()
807
808 void LocApiBase::pauseGeofence(uint32_t /*hwId*/, uint32_t /*clientId*/,
809 LocApiResponse* /*adapterResponse*/)
810 DEFAULT_IMPL()
811
812 void LocApiBase::resumeGeofence(uint32_t /*hwId*/, uint32_t /*clientId*/,
813 LocApiResponse* /*adapterResponse*/)
814 DEFAULT_IMPL()
815
816 void LocApiBase::modifyGeofence(uint32_t /*hwId*/, uint32_t /*clientId*/,
817 const GeofenceOption& /*options*/, LocApiResponse* /*adapterResponse*/)
818 DEFAULT_IMPL()
819
820 void LocApiBase::startTimeBasedTracking(const TrackingOptions& /*options*/,
821 LocApiResponse* /*adapterResponse*/)
822 DEFAULT_IMPL()
823
824 void LocApiBase::stopTimeBasedTracking(LocApiResponse* /*adapterResponse*/)
825 DEFAULT_IMPL()
826
827 void LocApiBase::startDistanceBasedTracking(uint32_t /*sessionId*/,
828 const LocationOptions& /*options*/, LocApiResponse* /*adapterResponse*/)
829 DEFAULT_IMPL()
830
831 void LocApiBase::stopDistanceBasedTracking(uint32_t /*sessionId*/,
832 LocApiResponse* /*adapterResponse*/)
833 DEFAULT_IMPL()
834
835 void LocApiBase::startBatching(uint32_t /*sessionId*/, const LocationOptions& /*options*/,
836 uint32_t /*accuracy*/, uint32_t /*timeout*/, LocApiResponse* /*adapterResponse*/)
837 DEFAULT_IMPL()
838
839 void LocApiBase::stopBatching(uint32_t /*sessionId*/, LocApiResponse* /*adapterResponse*/)
840 DEFAULT_IMPL()
841
842 LocationError LocApiBase::startOutdoorTripBatchingSync(uint32_t /*tripDistance*/,
843 uint32_t /*tripTbf*/, uint32_t /*timeout*/)
844 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
845
846 void LocApiBase::startOutdoorTripBatching(uint32_t /*tripDistance*/, uint32_t /*tripTbf*/,
847 uint32_t /*timeout*/, LocApiResponse* /*adapterResponse*/)
848 DEFAULT_IMPL()
849
850 void LocApiBase::reStartOutdoorTripBatching(uint32_t /*ongoingTripDistance*/,
851 uint32_t /*ongoingTripInterval*/, uint32_t /*batchingTimeout,*/,
852 LocApiResponse* /*adapterResponse*/)
853 DEFAULT_IMPL()
854
855 LocationError LocApiBase::stopOutdoorTripBatchingSync(bool /*deallocBatchBuffer*/)
856 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
857
858 void LocApiBase::stopOutdoorTripBatching(bool /*deallocBatchBuffer*/,
859 LocApiResponse* /*adapterResponse*/)
860 DEFAULT_IMPL()
861
862 LocationError LocApiBase::getBatchedLocationsSync(size_t /*count*/)
863 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
864
865 void LocApiBase::getBatchedLocations(size_t /*count*/, LocApiResponse* /*adapterResponse*/)
866 DEFAULT_IMPL()
867
868 LocationError LocApiBase::getBatchedTripLocationsSync(size_t /*count*/,
869 uint32_t /*accumulatedDistance*/)
870 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
871
872 void LocApiBase::getBatchedTripLocations(size_t /*count*/, uint32_t /*accumulatedDistance*/,
873 LocApiResponse* /*adapterResponse*/)
874 DEFAULT_IMPL()
875
876 LocationError LocApiBase::queryAccumulatedTripDistanceSync(uint32_t& /*accumulated_trip_distance*/,
877 uint32_t& /*numOfBatchedPositions*/)
878 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
879
880 void LocApiBase::queryAccumulatedTripDistance(
881 LocApiResponseData<LocApiBatchData>* /*adapterResponseData*/)
882 DEFAULT_IMPL()
883
884 void LocApiBase::setBatchSize(size_t /*size*/)
885 DEFAULT_IMPL()
886
887 void LocApiBase::setTripBatchSize(size_t /*size*/)
888 DEFAULT_IMPL()
889
890 void LocApiBase::addToCallQueue(LocApiResponse* /*adapterResponse*/)
891 DEFAULT_IMPL()
892
893 void LocApiBase::updateSystemPowerState(PowerStateType /*powerState*/)
894 DEFAULT_IMPL()
895
896 void LocApiBase::
897 configRobustLocation(bool /*enabled*/,
898 bool /*enableForE911*/,
899 LocApiResponse* /*adapterResponse*/)
900 DEFAULT_IMPL()
901
902 void LocApiBase::
903 getRobustLocationConfig(uint32_t sessionId, LocApiResponse* /*adapterResponse*/)
904 DEFAULT_IMPL()
905
906 void LocApiBase::
907 configMinGpsWeek(uint16_t minGpsWeek,
908 LocApiResponse* /*adapterResponse*/)
909 DEFAULT_IMPL()
910
911 void LocApiBase::
912 getMinGpsWeek(uint32_t sessionId, LocApiResponse* /*adapterResponse*/)
913 DEFAULT_IMPL()
914
915 LocationError LocApiBase::
916 setParameterSync(const GnssConfig& gnssConfig)
917 DEFAULT_IMPL(LOCATION_ERROR_SUCCESS)
918
919 void LocApiBase::
920 getParameter(uint32_t sessionId, GnssConfigFlagsMask flags, LocApiResponse* /*adapterResponse*/)
921 DEFAULT_IMPL()
922
923 void LocApiBase::
924 configConstellationMultiBand(const GnssSvTypeConfig& secondaryBandConfig,
925 LocApiResponse* /*adapterResponse*/)
926 DEFAULT_IMPL()
927
928 void LocApiBase::
929 getConstellationMultiBandConfig(uint32_t sessionId, LocApiResponse* /*adapterResponse*/)
930 DEFAULT_IMPL()
931
932 int64_t ElapsedRealtimeEstimator::getElapsedRealtimeEstimateNanos(int64_t curDataTimeNanos,
933 bool isCurDataTimeTrustable, int64_t tbf) {
934 //The algorithm works follow below steps:
935 //When isCurDataTimeTrustable is meet (means Modem timestamp is already stable),
936 //1, Wait for mFixTimeStablizationThreshold fixes; While waiting for modem time
937 // stable, we set the traveltime to a default value;
938 //2, When the mFixTimeStablizationThreshold fix comes, we think now the mode time
939 // is already stable, calculate the initial AP-Modem clock diff(mCurrentClockDiff)
940 // using formula:
941 // mCurrentClockDiff = currentTimeNanos - locationTimeNanos - currentTravelTimeNanos
942 //3, since then, when the nth fix comes,
943 // 3.1 First update mCurrentClockDiff using below formula:
944 // mCurrentClockDiff = mCurrentClockDiff + (currentTimeNanos - sinceBootTimeNanos)
945 // - (mPrevUtcTimeNanos - mPrevBootTimeNanos)
946 // 3.2 Calculate currentTravelTimeNanos:
947 // currentTravelTimeNanos = currentTimeNanos - locationTimeNanos - mCurrentClockDiff
948 //4, It is possible that locationTimeNanos will jump,
949 // reset mFixTimeStablizationThreshold to default value, jump to step 2 to continue.
950
951 int64_t currentTravelTimeNanos = mInitialTravelTime;
952 struct timespec currentTime;
953 int64_t sinceBootTimeNanos;
954 if (getCurrentTime(currentTime, sinceBootTimeNanos)) {
955 if (isCurDataTimeTrustable) {
956 if (tbf > 0 && tbf != curDataTimeNanos - mPrevDataTimeNanos) {
957 mFixTimeStablizationThreshold = 5;
958 }
959 int64_t currentTimeNanos = (int64_t)currentTime.tv_sec*1000000000 + currentTime.tv_nsec;
960 LOC_LOGd("sinceBootTimeNanos:%" PRIi64 " currentTimeNanos:%" PRIi64 ""
961 " locationTimeNanos:%" PRIi64 "",
962 sinceBootTimeNanos, currentTimeNanos, curDataTimeNanos);
963 if (mFixTimeStablizationThreshold == 0) {
964 currentTravelTimeNanos = mInitialTravelTime;
965 mCurrentClockDiff = currentTimeNanos - curDataTimeNanos - currentTravelTimeNanos;
966 } else if (mFixTimeStablizationThreshold < 0) {
967 mCurrentClockDiff = mCurrentClockDiff + (currentTimeNanos - sinceBootTimeNanos)
968 - (mPrevUtcTimeNanos - mPrevBootTimeNanos);
969 currentTravelTimeNanos = currentTimeNanos - curDataTimeNanos - mCurrentClockDiff;
970 }
971
972 mPrevUtcTimeNanos = currentTimeNanos;
973 mPrevBootTimeNanos = sinceBootTimeNanos;
974 mPrevDataTimeNanos = curDataTimeNanos;
975 mFixTimeStablizationThreshold--;
976 }
977 } else {
978 return -1;
979 }
980 LOC_LOGd("Estimated travel time: %" PRIi64 "", currentTravelTimeNanos);
981 return (sinceBootTimeNanos - currentTravelTimeNanos);
982 }
983
reset()984 void ElapsedRealtimeEstimator::reset() {
985 mCurrentClockDiff = 0;
986 mPrevDataTimeNanos = 0;
987 mPrevUtcTimeNanos = 0;
988 mPrevBootTimeNanos = 0;
989 mFixTimeStablizationThreshold = 5;
990 }
991
getElapsedRealtimeQtimer(int64_t qtimerTicksAtOrigin)992 int64_t ElapsedRealtimeEstimator::getElapsedRealtimeQtimer(int64_t qtimerTicksAtOrigin) {
993 struct timespec currentTime;
994 int64_t sinceBootTimeNanos;
995 int64_t elapsedRealTimeNanos;
996
997 if (getCurrentTime(currentTime, sinceBootTimeNanos)) {
998 uint64_t qtimerDiff = 0;
999 uint64_t qTimerTickCount = getQTimerTickCount();
1000 if (qTimerTickCount >= qtimerTicksAtOrigin) {
1001 qtimerDiff = qTimerTickCount - qtimerTicksAtOrigin;
1002 }
1003 LOC_LOGd("sinceBootTimeNanos:%" PRIi64 " qtimerTicksAtOrigin=%" PRIi64 ""
1004 " qTimerTickCount=%" PRIi64 " qtimerDiff=%" PRIi64 "",
1005 sinceBootTimeNanos, qtimerTicksAtOrigin, qTimerTickCount, qtimerDiff);
1006 uint64_t qTimerDiffNanos = qTimerTicksToNanos(double(qtimerDiff));
1007
1008 /* If the time difference between Qtimer on modem side and Qtimer on AP side
1009 is greater than one second we assume this is a dual-SoC device such as
1010 Kona and will try to get Qtimer on modem side and on AP side and
1011 will adjust our difference accordingly */
1012 if (qTimerDiffNanos > 1000000000) {
1013 uint64_t qtimerDelta = getQTimerDeltaNanos();
1014 if (qTimerDiffNanos >= qtimerDelta) {
1015 qTimerDiffNanos -= qtimerDelta;
1016 }
1017 }
1018
1019 LOC_LOGd("Qtimer travel time: %" PRIi64 "", qTimerDiffNanos);
1020 if (sinceBootTimeNanos >= qTimerDiffNanos) {
1021 elapsedRealTimeNanos = sinceBootTimeNanos - qTimerDiffNanos;
1022 } else {
1023 elapsedRealTimeNanos = -1;
1024 }
1025 } else {
1026 elapsedRealTimeNanos = -1;
1027 }
1028 return elapsedRealTimeNanos;
1029 }
1030
getCurrentTime(struct timespec & currentTime,int64_t & sinceBootTimeNanos)1031 bool ElapsedRealtimeEstimator::getCurrentTime(
1032 struct timespec& currentTime, int64_t& sinceBootTimeNanos)
1033 {
1034 struct timespec sinceBootTime;
1035 struct timespec sinceBootTimeTest;
1036 bool clockGetTimeSuccess = false;
1037 const uint32_t MAX_TIME_DELTA_VALUE_NANOS = 10000;
1038 const uint32_t MAX_GET_TIME_COUNT = 20;
1039 /* Attempt to get CLOCK_REALTIME and CLOCK_BOOTIME in succession without an interruption
1040 or context switch (for up to MAX_GET_TIME_COUNT times) to avoid errors in the calculation */
1041 for (uint32_t i = 0; i < MAX_GET_TIME_COUNT; i++) {
1042 if (clock_gettime(CLOCK_BOOTTIME, &sinceBootTime) != 0) {
1043 break;
1044 };
1045 if (clock_gettime(CLOCK_REALTIME, ¤tTime) != 0) {
1046 break;
1047 }
1048 if (clock_gettime(CLOCK_BOOTTIME, &sinceBootTimeTest) != 0) {
1049 break;
1050 };
1051 sinceBootTimeNanos = (int64_t)sinceBootTime.tv_sec * 1000000000 + sinceBootTime.tv_nsec;
1052 int64_t sinceBootTimeTestNanos =
1053 (int64_t)sinceBootTimeTest.tv_sec * 1000000000 + sinceBootTimeTest.tv_nsec;
1054 int64_t sinceBootTimeDeltaNanos = sinceBootTimeTestNanos - sinceBootTimeNanos;
1055
1056 /* sinceBootTime and sinceBootTimeTest should have a close value if there was no
1057 interruption or context switch between clock_gettime for CLOCK_BOOTIME and
1058 clock_gettime for CLOCK_REALTIME */
1059 if (sinceBootTimeDeltaNanos < MAX_TIME_DELTA_VALUE_NANOS) {
1060 clockGetTimeSuccess = true;
1061 break;
1062 } else {
1063 LOC_LOGd("Delta:%" PRIi64 "ns time too large, retry number #%u...",
1064 sinceBootTimeDeltaNanos, i + 1);
1065 }
1066 }
1067 return clockGetTimeSuccess;
1068 }
1069 } // namespace loc_core
1070