LocApiBase.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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 __unused,
  92. uint32_t center __unused, uint32_t right __unused, uint8_t gloFrequency __unused) { return 0.0; }
  93. inline virtual bool getSatellitePVT(GnssSvPolynomial& svPolynomial __unused,
  94. GnssSvMeasurementHeader& svMeasSetHeader __unused,
  95. GnssMeasurementsData& measurementData __unused) { return false; }
  96. inline virtual float getGeoidalSeparation(double latitude __unused, double longitude __unused) { 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 reportEngDebugDataInfo(GnssEngineDebugDataInfo& gnssEngineDebugDataInfo);
  194. void reportQwesCapabilities
  195. (
  196. const std::unordered_map<LocationQwesFeatureType, bool> &featureMap
  197. );
  198. void geofenceBreach(size_t count, uint32_t* hwIds, Location& location,
  199. GeofenceBreachType breachType, uint64_t timestamp);
  200. void geofenceStatus(GeofenceStatusAvailable available);
  201. void reportDBTPosition(UlpLocation &location,
  202. GpsLocationExtended &locationExtended,
  203. enum loc_sess_status status,
  204. LocPosTechMask loc_technology_mask);
  205. void reportLocations(Location* locations, size_t count, BatchingMode batchingMode);
  206. void reportCompletedTrips(uint32_t accumulated_distance);
  207. void handleBatchStatusEvent(BatchingStatus batchStatus);
  208. // downward calls
  209. virtual void* getSibling();
  210. virtual LocApiProxyBase* getLocApiProxy();
  211. virtual void deleteAidingData(const GnssAidingData& data, LocApiResponse* adapterResponse);
  212. virtual void injectPosition(double latitude, double longitude, float accuracy,
  213. bool onDemandCpi);
  214. virtual void injectPosition(const GnssLocationInfoNotification &locationInfo,
  215. bool onDemandCpi=false);
  216. virtual void injectPosition(const Location& location, bool onDemandCpi);
  217. virtual void injectPositionAndCivicAddress(const Location& location,
  218. const GnssCivicAddress& addr);
  219. virtual void setTime(LocGpsUtcTime time, int64_t timeReference, int uncertainty);
  220. virtual void atlOpenStatus(int handle, int is_succ, char* apn, uint32_t apnLen,
  221. AGpsBearerType bear, LocAGpsType agpsType, LocApnTypeMask mask);
  222. virtual void atlCloseStatus(int handle, int is_succ);
  223. virtual LocationError setServerSync(const char* url, int len, LocServerType type);
  224. virtual LocationError setServerSync(unsigned int ip, int port, LocServerType type);
  225. virtual void informNiResponse(GnssNiResponse userResponse, const void* passThroughData);
  226. virtual LocationError setSUPLVersionSync(GnssConfigSuplVersion version);
  227. virtual enum loc_api_adapter_err setNMEATypesSync(uint32_t typesMask);
  228. virtual LocationError setLPPConfigSync(GnssConfigLppProfileMask profileMask);
  229. virtual enum loc_api_adapter_err setSensorPropertiesSync(
  230. bool gyroBiasVarianceRandomWalk_valid, float gyroBiasVarianceRandomWalk,
  231. bool accelBiasVarianceRandomWalk_valid, float accelBiasVarianceRandomWalk,
  232. bool angleBiasVarianceRandomWalk_valid, float angleBiasVarianceRandomWalk,
  233. bool rateBiasVarianceRandomWalk_valid, float rateBiasVarianceRandomWalk,
  234. bool velocityBiasVarianceRandomWalk_valid, float velocityBiasVarianceRandomWalk);
  235. virtual enum loc_api_adapter_err setSensorPerfControlConfigSync(int controlMode,
  236. int accelSamplesPerBatch, int accelBatchesPerSec, int gyroSamplesPerBatch,
  237. int gyroBatchesPerSec, int accelSamplesPerBatchHigh, int accelBatchesPerSecHigh,
  238. int gyroSamplesPerBatchHigh, int gyroBatchesPerSecHigh, int algorithmConfig);
  239. virtual LocationError
  240. setAGLONASSProtocolSync(GnssConfigAGlonassPositionProtocolMask aGlonassProtocol);
  241. virtual LocationError setLPPeProtocolCpSync(GnssConfigLppeControlPlaneMask lppeCP);
  242. virtual LocationError setLPPeProtocolUpSync(GnssConfigLppeUserPlaneMask lppeUP);
  243. virtual GnssConfigSuplVersion convertSuplVersion(const uint32_t suplVersion);
  244. virtual GnssConfigLppeControlPlaneMask convertLppeCp(const uint32_t lppeControlPlaneMask);
  245. virtual GnssConfigLppeUserPlaneMask convertLppeUp(const uint32_t lppeUserPlaneMask);
  246. virtual LocationError setEmergencyExtensionWindowSync(const uint32_t emergencyExtensionSeconds);
  247. virtual void setMeasurementCorrections(
  248. const GnssMeasurementCorrections& gnssMeasurementCorrections);
  249. virtual void getWwanZppFix();
  250. virtual void getBestAvailableZppFix();
  251. virtual LocationError setGpsLockSync(GnssConfigGpsLock lock);
  252. virtual void requestForAidingData(GnssAidingDataSvMask svDataMask);
  253. virtual LocationError setXtraVersionCheckSync(uint32_t check);
  254. /* Requests for SV/Constellation Control */
  255. virtual LocationError setBlacklistSvSync(const GnssSvIdConfig& config);
  256. virtual void setBlacklistSv(const GnssSvIdConfig& config,
  257. LocApiResponse *adapterResponse=nullptr);
  258. virtual void getBlacklistSv();
  259. virtual void setConstellationControl(const GnssSvTypeConfig& config,
  260. LocApiResponse *adapterResponse=nullptr);
  261. virtual void getConstellationControl();
  262. virtual void resetConstellationControl(LocApiResponse *adapterResponse=nullptr);
  263. virtual void setConstrainedTuncMode(bool enabled,
  264. float tuncConstraint,
  265. uint32_t energyBudget,
  266. LocApiResponse* adapterResponse=nullptr);
  267. virtual void setPositionAssistedClockEstimatorMode(bool enabled,
  268. LocApiResponse* adapterResponse=nullptr);
  269. virtual void getGnssEnergyConsumed();
  270. virtual void addGeofence(uint32_t clientId, const GeofenceOption& options,
  271. const GeofenceInfo& info, LocApiResponseData<LocApiGeofenceData>* adapterResponseData);
  272. virtual void removeGeofence(uint32_t hwId, uint32_t clientId, LocApiResponse* adapterResponse);
  273. virtual void pauseGeofence(uint32_t hwId, uint32_t clientId, LocApiResponse* adapterResponse);
  274. virtual void resumeGeofence(uint32_t hwId, uint32_t clientId, LocApiResponse* adapterResponse);
  275. virtual void modifyGeofence(uint32_t hwId, uint32_t clientId, const GeofenceOption& options,
  276. LocApiResponse* adapterResponse);
  277. virtual void startTimeBasedTracking(const TrackingOptions& options,
  278. LocApiResponse* adapterResponse);
  279. virtual void stopTimeBasedTracking(LocApiResponse* adapterResponse);
  280. virtual void startDistanceBasedTracking(uint32_t sessionId, const LocationOptions& options,
  281. LocApiResponse* adapterResponse);
  282. virtual void stopDistanceBasedTracking(uint32_t sessionId,
  283. LocApiResponse* adapterResponse = nullptr);
  284. virtual void startBatching(uint32_t sessionId, const LocationOptions& options,
  285. uint32_t accuracy, uint32_t timeout, LocApiResponse* adapterResponse);
  286. virtual void stopBatching(uint32_t sessionId, LocApiResponse* adapterResponse);
  287. virtual LocationError startOutdoorTripBatchingSync(uint32_t tripDistance,
  288. uint32_t tripTbf, uint32_t timeout);
  289. virtual void startOutdoorTripBatching(uint32_t tripDistance,
  290. uint32_t tripTbf, uint32_t timeout, LocApiResponse* adapterResponse);
  291. virtual void reStartOutdoorTripBatching(uint32_t ongoingTripDistance,
  292. uint32_t ongoingTripInterval, uint32_t batchingTimeout,
  293. LocApiResponse* adapterResponse);
  294. virtual LocationError stopOutdoorTripBatchingSync(bool deallocBatchBuffer = true);
  295. virtual void stopOutdoorTripBatching(bool deallocBatchBuffer = true,
  296. LocApiResponse* adapterResponse = nullptr);
  297. virtual LocationError getBatchedLocationsSync(size_t count);
  298. virtual void getBatchedLocations(size_t count, LocApiResponse* adapterResponse);
  299. virtual LocationError getBatchedTripLocationsSync(size_t count, uint32_t accumulatedDistance);
  300. virtual void getBatchedTripLocations(size_t count, uint32_t accumulatedDistance,
  301. LocApiResponse* adapterResponse);
  302. virtual LocationError queryAccumulatedTripDistanceSync(uint32_t &accumulated_trip_distance,
  303. uint32_t &numOfBatchedPositions);
  304. virtual void queryAccumulatedTripDistance(
  305. LocApiResponseData<LocApiBatchData>* adapterResponseData);
  306. virtual void setBatchSize(size_t size);
  307. virtual void setTripBatchSize(size_t size);
  308. virtual void addToCallQueue(LocApiResponse* adapterResponse);
  309. void updateEvtMask();
  310. void updateNmeaMask(uint32_t mask);
  311. virtual void updateSystemPowerState(PowerStateType systemPowerState);
  312. virtual void configRobustLocation(bool enable, bool enableForE911,
  313. LocApiResponse* adapterResponse=nullptr);
  314. virtual void getRobustLocationConfig(uint32_t sessionId, LocApiResponse* adapterResponse);
  315. virtual void configMinGpsWeek(uint16_t minGpsWeek,
  316. LocApiResponse* adapterResponse=nullptr);
  317. virtual void getMinGpsWeek(uint32_t sessionId, LocApiResponse* adapterResponse);
  318. virtual LocationError setParameterSync(const GnssConfig & gnssConfig);
  319. virtual void getParameter(uint32_t sessionId, GnssConfigFlagsMask flags,
  320. LocApiResponse* adapterResponse=nullptr);
  321. virtual void configConstellationMultiBand(const GnssSvTypeConfig& secondaryBandConfig,
  322. LocApiResponse* adapterResponse=nullptr);
  323. virtual void getConstellationMultiBandConfig(uint32_t sessionId,
  324. LocApiResponse* adapterResponse=nullptr);
  325. };
  326. class ElapsedRealtimeEstimator {
  327. typedef struct {
  328. GPSTimeStruct gpsTime;
  329. int64_t qtimerTick;
  330. float timeUncMsec; // in milli-seconds
  331. } GpsTimeQtimerTickPair;
  332. private:
  333. int64_t mCurrentClockDiff;
  334. int64_t mPrevUtcTimeNanos;
  335. int64_t mPrevBootTimeNanos;
  336. int64_t mFixTimeStablizationThreshold;
  337. int64_t mInitialTravelTime;
  338. int64_t mPrevDataTimeNanos;
  339. // association between gps time and qtimer value
  340. // the two variable saves a pair of gps time and qtimer time
  341. // read at the same point
  342. GpsTimeQtimerTickPair mTimePairPVTReport;
  343. GpsTimeQtimerTickPair mTimePairMeasReport;
  344. public:
  345. inline ElapsedRealtimeEstimator(int64_t travelTimeNanosEstimate) :
  346. mInitialTravelTime(travelTimeNanosEstimate) {
  347. reset();
  348. }
  349. int64_t getElapsedRealtimeEstimateNanos(int64_t curDataTimeNanos,
  350. bool isCurDataTimeTrustable, int64_t tbfNanos);
  351. inline int64_t getElapsedRealtimeUncNanos() { return 5000000;}
  352. void reset();
  353. static int64_t getElapsedRealtimeQtimer(int64_t qtimerTicksAtOrigin);
  354. bool getElapsedRealtimeForGpsTime(const GpsLocationExtended& locationExtended,
  355. int64_t &elapsedTime, float & elpasedTimeUnc);
  356. void saveGpsTimeAndQtimerPairInPvtReport(const GpsLocationExtended& locationExtended);
  357. void saveGpsTimeAndQtimerPairInMeasReport(const GnssSvMeasurementSet& svMeasurementSet);
  358. static bool getCurrentTime(struct timespec& currentTime, int64_t& sinceBootTimeNanos);
  359. };
  360. typedef LocApiBase* (getLocApi_t)(LOC_API_ADAPTER_EVENT_MASK_T exMask,
  361. ContextBase *context);
  362. } // namespace loc_core
  363. #endif //LOC_API_BASE_H