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