LocApiBase.cpp 46 KB

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