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