LocApiBase.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. #ifndef LOC_API_BASE_H
  30. #define LOC_API_BASE_H
  31. #include <stddef.h>
  32. #include <ctype.h>
  33. #include <loc_pla.h>
  34. #include <gps_extended.h>
  35. #include <LocationAPI.h>
  36. #include <MsgTask.h>
  37. #include <LocSharedLock.h>
  38. #include <log_util.h>
  39. #ifdef NO_UNORDERED_SET_OR_MAP
  40. #include <map>
  41. #define unordered_map map
  42. #else
  43. #include <unordered_map>
  44. #endif
  45. #include <inttypes.h>
  46. #include <functional>
  47. using namespace loc_util;
  48. namespace loc_core {
  49. class ContextBase;
  50. struct LocApiResponse;
  51. template <typename> struct LocApiResponseData;
  52. int hexcode(char *hexstring, int string_size,
  53. const char *data, int data_size);
  54. int decodeAddress(char *addr_string, int string_size,
  55. const char *data, int data_size);
  56. #define MAX_ADAPTERS 10
  57. #define MAX_FEATURE_LENGTH 100
  58. #define TO_ALL_ADAPTERS(adapters, call) \
  59. for (int i = 0; i < MAX_ADAPTERS && NULL != (adapters)[i]; i++) { \
  60. call; \
  61. }
  62. #define TO_1ST_HANDLING_ADAPTER(adapters, call) \
  63. for (int i = 0; i <MAX_ADAPTERS && NULL != (adapters)[i] && !(call); i++);
  64. class LocAdapterBase;
  65. struct LocSsrMsg;
  66. struct LocOpenMsg;
  67. typedef struct
  68. {
  69. uint32_t accumulatedDistance;
  70. uint32_t numOfBatchedPositions;
  71. } LocApiBatchData;
  72. typedef struct
  73. {
  74. uint32_t hwId;
  75. } LocApiGeofenceData;
  76. struct LocApiMsg: LocMsg {
  77. private:
  78. std::function<void ()> mProcImpl;
  79. inline virtual void proc() const {
  80. mProcImpl();
  81. }
  82. public:
  83. inline LocApiMsg(std::function<void ()> procImpl ) :
  84. mProcImpl(procImpl) {}
  85. };
  86. class LocApiProxyBase {
  87. public:
  88. inline LocApiProxyBase() {}
  89. inline virtual ~LocApiProxyBase() {}
  90. inline virtual void* getSibling2() { return NULL; }
  91. inline virtual double getGloRfLoss(uint32_t left,
  92. uint32_t center, uint32_t right, uint8_t gloFrequency) { return 0.0; }
  93. inline virtual bool getSatellitePVT(GnssSvPolynomial& svPolynomial,
  94. GnssSvMeasurementHeader& svMeasSetHeader,
  95. GnssMeasurementsData& measurementData) { return false; }
  96. inline virtual float getGeoidalSeparation(double latitude, double longitude) { return 0.0; }
  97. };
  98. class LocApiBase {
  99. friend struct LocSsrMsg;
  100. //LocOpenMsg calls open() which makes it necessary to declare
  101. //it as a friend
  102. friend struct LocOpenMsg;
  103. friend struct LocCloseMsg;
  104. friend struct LocKillMsg;
  105. friend class ContextBase;
  106. static MsgTask* mMsgTask;
  107. static volatile int32_t mMsgTaskRefCount;
  108. LocAdapterBase* mLocAdapters[MAX_ADAPTERS];
  109. protected:
  110. ContextBase *mContext;
  111. virtual enum loc_api_adapter_err
  112. open(LOC_API_ADAPTER_EVENT_MASK_T mask);
  113. virtual enum loc_api_adapter_err
  114. close();
  115. LOC_API_ADAPTER_EVENT_MASK_T getEvtMask();
  116. LOC_API_ADAPTER_EVENT_MASK_T mMask;
  117. uint32_t mNmeaMask;
  118. LocApiBase(LOC_API_ADAPTER_EVENT_MASK_T excludedMask,
  119. ContextBase* context = NULL);
  120. inline virtual ~LocApiBase() {
  121. android_atomic_dec(&mMsgTaskRefCount);
  122. if (nullptr != mMsgTask && 0 == mMsgTaskRefCount) {
  123. delete mMsgTask;
  124. mMsgTask = nullptr;
  125. }
  126. }
  127. bool isInSession();
  128. const LOC_API_ADAPTER_EVENT_MASK_T mExcludedMask;
  129. bool isMaster();
  130. public:
  131. inline void sendMsg(const LocMsg* msg) const {
  132. if (nullptr != mMsgTask) {
  133. mMsgTask->sendMsg(msg);
  134. }
  135. }
  136. inline void destroy() {
  137. close();
  138. struct LocKillMsg : public LocMsg {
  139. LocApiBase* mLocApi;
  140. inline LocKillMsg(LocApiBase* locApi) : LocMsg(), mLocApi(locApi) {}
  141. inline virtual void proc() const {
  142. delete mLocApi;
  143. }
  144. };
  145. sendMsg(new LocKillMsg(this));
  146. }
  147. static bool needReport(const UlpLocation& ulpLocation,
  148. enum loc_sess_status status,
  149. LocPosTechMask techMask);
  150. void addAdapter(LocAdapterBase* adapter);
  151. void removeAdapter(LocAdapterBase* adapter);
  152. // upward calls
  153. void handleEngineUpEvent();
  154. void handleEngineDownEvent();
  155. void reportPosition(UlpLocation& location,
  156. GpsLocationExtended& locationExtended,
  157. enum loc_sess_status status,
  158. LocPosTechMask loc_technology_mask =
  159. LOC_POS_TECH_MASK_DEFAULT,
  160. GnssDataNotification* pDataNotify = nullptr,
  161. int msInWeek = -1);
  162. void reportSv(GnssSvNotification& svNotify);
  163. void reportSvPolynomial(GnssSvPolynomial &svPolynomial);
  164. void reportSvEphemeris(GnssSvEphemerisReport &svEphemeris);
  165. void reportStatus(LocGpsStatusValue status);
  166. void reportNmea(const char* nmea, int length);
  167. void reportData(GnssDataNotification& dataNotify, int msInWeek);
  168. void reportXtraServer(const char* url1, const char* url2,
  169. const char* url3, const int maxlength);
  170. void reportLocationSystemInfo(const LocationSystemInfo& locationSystemInfo);
  171. void requestXtraData();
  172. void requestTime();
  173. void requestLocation();
  174. void requestATL(int connHandle, LocAGpsType agps_type,
  175. LocApnTypeMask apn_type_mask, LocSubId sub_id=LOC_DEFAULT_SUB);
  176. void releaseATL(int connHandle);
  177. void requestNiNotify(GnssNiNotification &notify, const void* data,
  178. const LocInEmergency emergencyState);
  179. void reportGnssMeasurements(GnssMeasurements& gnssMeasurements, int msInWeek);
  180. void reportWwanZppFix(LocGpsLocation &zppLoc);
  181. void reportZppBestAvailableFix(LocGpsLocation &zppLoc, GpsLocationExtended &location_extended,
  182. LocPosTechMask tech_mask);
  183. void reportGnssSvIdConfig(const GnssSvIdConfig& config);
  184. void reportGnssSvTypeConfig(const GnssSvTypeConfig& config);
  185. void requestOdcpi(OdcpiRequestInfo& request);
  186. void reportGnssEngEnergyConsumedEvent(uint64_t energyConsumedSinceFirstBoot);
  187. void reportDeleteAidingDataEvent(GnssAidingData& aidingData);
  188. void reportKlobucharIonoModel(GnssKlobucharIonoModel& ionoModel);
  189. void reportGnssAdditionalSystemInfo(GnssAdditionalSystemInfo& additionalSystemInfo);
  190. void sendNfwNotification(GnssNfwNotification& notification);
  191. void reportGnssConfig(uint32_t sessionId, const GnssConfig& gnssConfig);
  192. void reportLatencyInfo(GnssLatencyInfo& gnssLatencyInfo);
  193. void reportQwesCapabilities
  194. (
  195. const std::unordered_map<LocationQwesFeatureType, bool> &featureMap
  196. );
  197. void geofenceBreach(size_t count, uint32_t* hwIds, Location& location,
  198. GeofenceBreachType breachType, uint64_t timestamp);
  199. void geofenceStatus(GeofenceStatusAvailable available);
  200. void reportDBTPosition(UlpLocation &location,
  201. GpsLocationExtended &locationExtended,
  202. enum loc_sess_status status,
  203. LocPosTechMask loc_technology_mask);
  204. void reportLocations(Location* locations, size_t count, BatchingMode batchingMode);
  205. void reportCompletedTrips(uint32_t accumulated_distance);
  206. void handleBatchStatusEvent(BatchingStatus batchStatus);
  207. // downward calls
  208. virtual void* getSibling();
  209. virtual LocApiProxyBase* getLocApiProxy();
  210. virtual void startFix(const LocPosMode& fixCriteria, LocApiResponse* adapterResponse);
  211. virtual void stopFix(LocApiResponse* adapterResponse);
  212. virtual void deleteAidingData(const GnssAidingData& data, LocApiResponse* adapterResponse);
  213. virtual void injectPosition(double latitude, double longitude, float accuracy,
  214. bool onDemandCpi);
  215. virtual void injectPosition(const GnssLocationInfoNotification &locationInfo,
  216. bool onDemandCpi=false);
  217. virtual void injectPosition(const Location& location, bool onDemandCpi);
  218. virtual void injectPositionAndCivicAddress(const Location& location,
  219. const GnssCivicAddress& addr);
  220. virtual void setTime(LocGpsUtcTime time, int64_t timeReference, int uncertainty);
  221. virtual void atlOpenStatus(int handle, int is_succ, char* apn, uint32_t apnLen,
  222. AGpsBearerType bear, LocAGpsType agpsType, LocApnTypeMask mask);
  223. virtual void atlCloseStatus(int handle, int is_succ);
  224. virtual LocationError setServerSync(const char* url, int len, LocServerType type);
  225. virtual LocationError setServerSync(unsigned int ip, int port, LocServerType type);
  226. virtual void informNiResponse(GnssNiResponse userResponse, const void* passThroughData);
  227. virtual LocationError setSUPLVersionSync(GnssConfigSuplVersion version);
  228. virtual enum loc_api_adapter_err setNMEATypesSync(uint32_t typesMask);
  229. virtual LocationError setLPPConfigSync(GnssConfigLppProfileMask profileMask);
  230. virtual enum loc_api_adapter_err setSensorPropertiesSync(
  231. bool gyroBiasVarianceRandomWalk_valid, float gyroBiasVarianceRandomWalk,
  232. bool accelBiasVarianceRandomWalk_valid, float accelBiasVarianceRandomWalk,
  233. bool angleBiasVarianceRandomWalk_valid, float angleBiasVarianceRandomWalk,
  234. bool rateBiasVarianceRandomWalk_valid, float rateBiasVarianceRandomWalk,
  235. bool velocityBiasVarianceRandomWalk_valid, float velocityBiasVarianceRandomWalk);
  236. virtual enum loc_api_adapter_err setSensorPerfControlConfigSync(int controlMode,
  237. int accelSamplesPerBatch, int accelBatchesPerSec, int gyroSamplesPerBatch,
  238. int gyroBatchesPerSec, int accelSamplesPerBatchHigh, int accelBatchesPerSecHigh,
  239. int gyroSamplesPerBatchHigh, int gyroBatchesPerSecHigh, int algorithmConfig);
  240. virtual LocationError
  241. setAGLONASSProtocolSync(GnssConfigAGlonassPositionProtocolMask aGlonassProtocol);
  242. virtual LocationError setLPPeProtocolCpSync(GnssConfigLppeControlPlaneMask lppeCP);
  243. virtual LocationError setLPPeProtocolUpSync(GnssConfigLppeUserPlaneMask lppeUP);
  244. virtual GnssConfigSuplVersion convertSuplVersion(const uint32_t suplVersion);
  245. virtual GnssConfigLppeControlPlaneMask convertLppeCp(const uint32_t lppeControlPlaneMask);
  246. virtual GnssConfigLppeUserPlaneMask convertLppeUp(const uint32_t lppeUserPlaneMask);
  247. virtual LocationError setEmergencyExtensionWindowSync(const uint32_t emergencyExtensionSeconds);
  248. virtual void setMeasurementCorrections(
  249. const GnssMeasurementCorrections& gnssMeasurementCorrections);
  250. virtual void getWwanZppFix();
  251. virtual void getBestAvailableZppFix();
  252. virtual LocationError setGpsLockSync(GnssConfigGpsLock lock);
  253. virtual void requestForAidingData(GnssAidingDataSvMask svDataMask);
  254. virtual LocationError setXtraVersionCheckSync(uint32_t check);
  255. /* Requests for SV/Constellation Control */
  256. virtual LocationError setBlacklistSvSync(const GnssSvIdConfig& config);
  257. virtual void setBlacklistSv(const GnssSvIdConfig& config,
  258. LocApiResponse *adapterResponse=nullptr);
  259. virtual void getBlacklistSv();
  260. virtual void setConstellationControl(const GnssSvTypeConfig& config,
  261. LocApiResponse *adapterResponse=nullptr);
  262. virtual void getConstellationControl();
  263. virtual void resetConstellationControl(LocApiResponse *adapterResponse=nullptr);
  264. virtual void setConstrainedTuncMode(bool enabled,
  265. float tuncConstraint,
  266. uint32_t energyBudget,
  267. LocApiResponse* adapterResponse=nullptr);
  268. virtual void setPositionAssistedClockEstimatorMode(bool enabled,
  269. LocApiResponse* adapterResponse=nullptr);
  270. virtual void getGnssEnergyConsumed();
  271. virtual void addGeofence(uint32_t clientId, const GeofenceOption& options,
  272. const GeofenceInfo& info, LocApiResponseData<LocApiGeofenceData>* adapterResponseData);
  273. virtual void removeGeofence(uint32_t hwId, uint32_t clientId, LocApiResponse* adapterResponse);
  274. virtual void pauseGeofence(uint32_t hwId, uint32_t clientId, LocApiResponse* adapterResponse);
  275. virtual void resumeGeofence(uint32_t hwId, uint32_t clientId, LocApiResponse* adapterResponse);
  276. virtual void modifyGeofence(uint32_t hwId, uint32_t clientId, const GeofenceOption& options,
  277. LocApiResponse* adapterResponse);
  278. virtual void startTimeBasedTracking(const TrackingOptions& options,
  279. LocApiResponse* adapterResponse);
  280. virtual void stopTimeBasedTracking(LocApiResponse* adapterResponse);
  281. virtual void startDistanceBasedTracking(uint32_t sessionId, const LocationOptions& options,
  282. LocApiResponse* adapterResponse);
  283. virtual void stopDistanceBasedTracking(uint32_t sessionId,
  284. LocApiResponse* adapterResponse = nullptr);
  285. virtual void startBatching(uint32_t sessionId, const LocationOptions& options,
  286. uint32_t accuracy, uint32_t timeout, LocApiResponse* adapterResponse);
  287. virtual void stopBatching(uint32_t sessionId, LocApiResponse* adapterResponse);
  288. virtual LocationError startOutdoorTripBatchingSync(uint32_t tripDistance,
  289. uint32_t tripTbf, uint32_t timeout);
  290. virtual void startOutdoorTripBatching(uint32_t tripDistance,
  291. uint32_t tripTbf, uint32_t timeout, LocApiResponse* adapterResponse);
  292. virtual void reStartOutdoorTripBatching(uint32_t ongoingTripDistance,
  293. uint32_t ongoingTripInterval, uint32_t batchingTimeout,
  294. LocApiResponse* adapterResponse);
  295. virtual LocationError stopOutdoorTripBatchingSync(bool deallocBatchBuffer = true);
  296. virtual void stopOutdoorTripBatching(bool deallocBatchBuffer = true,
  297. LocApiResponse* adapterResponse = nullptr);
  298. virtual LocationError getBatchedLocationsSync(size_t count);
  299. virtual void getBatchedLocations(size_t count, LocApiResponse* adapterResponse);
  300. virtual LocationError getBatchedTripLocationsSync(size_t count, uint32_t accumulatedDistance);
  301. virtual void getBatchedTripLocations(size_t count, uint32_t accumulatedDistance,
  302. LocApiResponse* adapterResponse);
  303. virtual LocationError queryAccumulatedTripDistanceSync(uint32_t &accumulated_trip_distance,
  304. uint32_t &numOfBatchedPositions);
  305. virtual void queryAccumulatedTripDistance(
  306. LocApiResponseData<LocApiBatchData>* adapterResponseData);
  307. virtual void setBatchSize(size_t size);
  308. virtual void setTripBatchSize(size_t size);
  309. virtual void addToCallQueue(LocApiResponse* adapterResponse);
  310. void updateEvtMask();
  311. void updateNmeaMask(uint32_t mask);
  312. virtual void updateSystemPowerState(PowerStateType systemPowerState);
  313. virtual void configRobustLocation(bool enable, bool enableForE911,
  314. LocApiResponse* adapterResponse=nullptr);
  315. virtual void getRobustLocationConfig(uint32_t sessionId, LocApiResponse* adapterResponse);
  316. virtual void configMinGpsWeek(uint16_t minGpsWeek,
  317. LocApiResponse* adapterResponse=nullptr);
  318. virtual void getMinGpsWeek(uint32_t sessionId, LocApiResponse* adapterResponse);
  319. virtual LocationError setParameterSync(const GnssConfig & gnssConfig);
  320. virtual void getParameter(uint32_t sessionId, GnssConfigFlagsMask flags,
  321. LocApiResponse* adapterResponse=nullptr);
  322. virtual void configConstellationMultiBand(const GnssSvTypeConfig& secondaryBandConfig,
  323. LocApiResponse* adapterResponse=nullptr);
  324. virtual void getConstellationMultiBandConfig(uint32_t sessionId,
  325. LocApiResponse* adapterResponse=nullptr);
  326. };
  327. class ElapsedRealtimeEstimator {
  328. typedef struct {
  329. GPSTimeStruct gpsTime;
  330. int64_t qtimerTick;
  331. float timeUncMsec; // in milli-seconds
  332. } GpsTimeQtimerTickPair;
  333. private:
  334. int64_t mCurrentClockDiff;
  335. int64_t mPrevUtcTimeNanos;
  336. int64_t mPrevBootTimeNanos;
  337. int64_t mFixTimeStablizationThreshold;
  338. int64_t mInitialTravelTime;
  339. int64_t mPrevDataTimeNanos;
  340. // association between gps time and qtimer value
  341. // the two variable saves a pair of gps time and qtimer time
  342. // read at the same point
  343. GpsTimeQtimerTickPair mTimePairPVTReport;
  344. GpsTimeQtimerTickPair mTimePairMeasReport;
  345. public:
  346. inline ElapsedRealtimeEstimator(int64_t travelTimeNanosEstimate) :
  347. mInitialTravelTime(travelTimeNanosEstimate) {
  348. reset();
  349. }
  350. int64_t getElapsedRealtimeEstimateNanos(int64_t curDataTimeNanos,
  351. bool isCurDataTimeTrustable, int64_t tbfNanos);
  352. inline int64_t getElapsedRealtimeUncNanos() { return 5000000;}
  353. void reset();
  354. static int64_t getElapsedRealtimeQtimer(int64_t qtimerTicksAtOrigin);
  355. bool getElapsedRealtimeForGpsTime(const GPSTimeStruct& gpsTimeAtOrigin,
  356. int64_t &elapsedTime, float & elpasedTimeUnc);
  357. void saveGpsTimeAndQtimerPairInPvtReport(const GpsLocationExtended& locationExtended);
  358. void saveGpsTimeAndQtimerPairInMeasReport(const GnssSvMeasurementSet& svMeasurementSet);
  359. static bool getCurrentTime(struct timespec& currentTime, int64_t& sinceBootTimeNanos);
  360. };
  361. typedef LocApiBase* (getLocApi_t)(LOC_API_ADAPTER_EVENT_MASK_T exMask,
  362. ContextBase *context);
  363. } // namespace loc_core
  364. #endif //LOC_API_BASE_H