1 /* Copyright (c) 2017-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 GNSS_ADAPTER_H
30 #define GNSS_ADAPTER_H
31 
32 #include <LocAdapterBase.h>
33 #include <LocContext.h>
34 #include <IOsObserver.h>
35 #include <EngineHubProxyBase.h>
36 #include <LocationAPI.h>
37 #include <Agps.h>
38 #include <SystemStatus.h>
39 #include <XtraSystemStatusObserver.h>
40 #include <map>
41 #include <functional>
42 #include <loc_misc_utils.h>
43 #include <queue>
44 #include <NativeAgpsHandler.h>
45 
46 #define MAX_URL_LEN 256
47 #define NMEA_SENTENCE_MAX_LENGTH 200
48 #define GLONASS_SV_ID_OFFSET 64
49 #define MAX_SATELLITES_IN_USE 12
50 #define LOC_NI_NO_RESPONSE_TIME 20
51 #define LOC_GPS_NI_RESPONSE_IGNORE 4
52 #define ODCPI_EXPECTED_INJECTION_TIME_MS 10000
53 #define DELETE_AIDING_DATA_EXPECTED_TIME_MS 5000
54 
55 class GnssAdapter;
56 
57 typedef std::map<LocationSessionKey, LocationOptions> LocationSessionMap;
58 typedef std::map<LocationSessionKey, TrackingOptions> TrackingOptionsMap;
59 
60 class OdcpiTimer : public LocTimer {
61 public:
OdcpiTimer(GnssAdapter * adapter)62     OdcpiTimer(GnssAdapter* adapter) :
63             LocTimer(), mAdapter(adapter), mActive(false) {}
64 
start()65     inline void start() {
66         mActive = true;
67         LocTimer::start(ODCPI_EXPECTED_INJECTION_TIME_MS, false);
68     }
stop()69     inline void stop() {
70         mActive = false;
71         LocTimer::stop();
72     }
restart()73     inline void restart() {
74         stop();
75         start();
76     }
isActive()77     inline bool isActive() {
78         return mActive;
79     }
80 
81 private:
82     // Override
83     virtual void timeOutCallback() override;
84 
85     GnssAdapter* mAdapter;
86     bool mActive;
87 };
88 
89 typedef struct {
90     pthread_t               thread;        /* NI thread */
91     uint32_t                respTimeLeft;  /* examine time for NI response */
92     bool                    respRecvd;     /* NI User reponse received or not from Java layer*/
93     void*                   rawRequest;
94     uint32_t                reqID;         /* ID to check against response */
95     GnssNiResponse          resp;
96     pthread_cond_t          tCond;
97     pthread_mutex_t         tLock;
98     GnssAdapter*            adapter;
99 } NiSession;
100 typedef struct {
101     NiSession session;    /* SUPL NI Session */
102     NiSession sessionEs;  /* Emergency SUPL NI Session */
103     uint32_t reqIDCounter;
104 } NiData;
105 
106 typedef enum {
107     NMEA_PROVIDER_AP = 0, // Application Processor Provider of NMEA
108     NMEA_PROVIDER_MP      // Modem Processor Provider of NMEA
109 } NmeaProviderType;
110 typedef struct {
111     GnssSvType svType;
112     const char* talker;
113     uint64_t mask;
114     uint32_t svIdOffset;
115 } NmeaSvMeta;
116 
117 typedef struct {
118     double latitude;
119     double longitude;
120     float  accuracy;
121     // the CPI will be blocked until the boot time
122     // specified in blockedTillTsMs
123     int64_t blockedTillTsMs;
124     // CPIs whose both latitude and longitude differ
125     // no more than latLonThreshold will be blocked
126     // in units of degree
127     double latLonDiffThreshold;
128 } BlockCPIInfo;
129 
130 typedef struct {
131     bool isValid;
132     bool enable;
133     float tuncThresholdMs; // need to be specified if enable is true
134     uint32_t energyBudget; // need to be specified if enable is true
135 } TuncConfigInfo;
136 
137 typedef struct {
138     bool isValid;
139     bool enable;
140 } PaceConfigInfo;
141 
142 typedef struct {
143     bool isValid;
144     bool enable;
145     bool enableFor911;
146 } RobustLocationConfigInfo;
147 
148 typedef struct {
149     TuncConfigInfo tuncConfigInfo;
150     PaceConfigInfo paceConfigInfo;
151     RobustLocationConfigInfo robustLocationConfigInfo;
152     LeverArmConfigInfo  leverArmConfigInfo;
153 } LocIntegrationConfigInfo;
154 
155 using namespace loc_core;
156 
157 namespace loc_core {
158     class SystemStatus;
159 }
160 
161 typedef std::function<void(
162     uint64_t gnssEnergyConsumedFromFirstBoot
163 )> GnssEnergyConsumedCallback;
164 
165 typedef void* QDgnssListenerHDL;
166 typedef std::function<void(
167     bool    sessionActive
168 )> QDgnssSessionActiveCb;
169 
170 struct CdfwInterface {
171     void (*startDgnssApiService)(const MsgTask& msgTask);
172     QDgnssListenerHDL (*createUsableReporter)(
173             QDgnssSessionActiveCb sessionActiveCb);
174     void (*destroyUsableReporter)(QDgnssListenerHDL handle);
175     void (*reportUsable)(QDgnssListenerHDL handle, bool usable);
176 };
177 
178 typedef uint16_t  DGnssStateBitMask;
179 #define DGNSS_STATE_ENABLE_NTRIP_COMMAND      0X01
180 #define DGNSS_STATE_NO_NMEA_PENDING           0X02
181 #define DGNSS_STATE_NTRIP_SESSION_STARTED     0X04
182 
183 class GnssReportLoggerUtil {
184 public:
185     typedef void (*LogGnssLatency)(const GnssLatencyInfo& gnssLatencyMeasInfo);
186 
GnssReportLoggerUtil()187     GnssReportLoggerUtil() : mLogLatency(nullptr) {
188         const char* libname = "liblocdiagiface.so";
189         void* libHandle = nullptr;
190         mLogLatency = (LogGnssLatency)dlGetSymFromLib(libHandle, libname, "LogGnssLatency");
191     }
192 
193     bool isLogEnabled();
194     void log(const GnssLatencyInfo& gnssLatencyMeasInfo);
195 
196 private:
197     LogGnssLatency mLogLatency;
198 };
199 
200 class GnssAdapter : public LocAdapterBase {
201 
202     /* ==== Engine Hub ===================================================================== */
203     EngineHubProxyBase* mEngHubProxy;
204     bool mNHzNeeded;
205     bool mSPEAlreadyRunningAtHighestInterval;
206 
207     /* ==== TRACKING ======================================================================= */
208     TrackingOptionsMap mTimeBasedTrackingSessions;
209     LocationSessionMap mDistanceBasedTrackingSessions;
210     LocPosMode mLocPositionMode;
211     GnssSvUsedInPosition mGnssSvIdUsedInPosition;
212     bool mGnssSvIdUsedInPosAvail;
213     GnssSvMbUsedInPosition mGnssMbSvIdUsedInPosition;
214     bool mGnssMbSvIdUsedInPosAvail;
215 
216     /* ==== CONTROL ======================================================================== */
217     LocationControlCallbacks mControlCallbacks;
218     uint32_t mAfwControlId;
219     uint32_t mNmeaMask;
220     uint64_t mPrevNmeaRptTimeNsec;
221     GnssSvIdConfig mGnssSvIdConfig;
222     GnssSvTypeConfig mGnssSeconaryBandConfig;
223     GnssSvTypeConfig mGnssSvTypeConfig;
224     GnssSvTypeConfigCallback mGnssSvTypeConfigCb;
225     bool mSupportNfwControl;
226     LocIntegrationConfigInfo mLocConfigInfo;
227 
228     /* ==== NI ============================================================================= */
229     NiData mNiData;
230 
231     /* ==== AGPS =========================================================================== */
232     // This must be initialized via initAgps()
233     AgpsManager mAgpsManager;
234     void initAgps(const AgpsCbInfo& cbInfo);
235 
236     /* ==== NFW =========================================================================== */
237     NfwStatusCb mNfwCb;
238     IsInEmergencySession mIsE911Session;
initNfw(const NfwCbInfo & cbInfo)239     inline void initNfw(const NfwCbInfo& cbInfo) {
240         mNfwCb = (NfwStatusCb)cbInfo.visibilityControlCb;
241         mIsE911Session = (IsInEmergencySession)cbInfo.isInEmergencySession;
242     }
243 
244     /* ==== Measurement Corrections========================================================= */
245     bool mIsMeasCorrInterfaceOpen;
246     measCorrSetCapabilitiesCb mMeasCorrSetCapabilitiesCb;
247     bool initMeasCorr(bool bSendCbWhenNotSupported);
248     bool mIsAntennaInfoInterfaceOpened;
249 
250     /* ==== DGNSS Data Usable Report======================================================== */
251     QDgnssListenerHDL mQDgnssListenerHDL;
252     const CdfwInterface* mCdfwInterface;
253     bool mDGnssNeedReport;
254     bool mDGnssDataUsage;
255     void reportDGnssDataUsable(const GnssSvMeasurementSet &svMeasurementSet);
256 
257     /* ==== ODCPI ========================================================================== */
258     OdcpiRequestCallback mOdcpiRequestCb;
259     bool mOdcpiRequestActive;
260     OdcpiPrioritytype mCallbackPriority;
261     OdcpiTimer mOdcpiTimer;
262     OdcpiRequestInfo mOdcpiRequest;
263     void odcpiTimerExpire();
264 
265     /* ==== DELETEAIDINGDATA =============================================================== */
266     int64_t mLastDeleteAidingDataTime;
267 
268     /* === SystemStatus ===================================================================== */
269     SystemStatus* mSystemStatus;
270     std::string mServerUrl;
271     std::string mMoServerUrl;
272     XtraSystemStatusObserver mXtraObserver;
273     LocationSystemInfo mLocSystemInfo;
274     std::vector<GnssSvIdSource> mBlacklistedSvIds;
275     PowerStateType mSystemPowerState;
276 
277     /* === Misc ===================================================================== */
278     BlockCPIInfo mBlockCPIInfo;
279     bool mPowerOn;
280     uint32_t mAllowFlpNetworkFixes;
281     std::queue<GnssLatencyInfo> mGnssLatencyInfoQueue;
282     GnssReportLoggerUtil mLogger;
283     bool mDreIntEnabled;
284 
285     /* === NativeAgpsHandler ======================================================== */
286     NativeAgpsHandler mNativeAgpsHandler;
287 
288     /* === Misc callback from QMI LOC API ============================================== */
289     GnssEnergyConsumedCallback mGnssEnergyConsumedCb;
290     std::function<void(bool)> mPowerStateCb;
291 
292     /*==== CONVERSION ===================================================================*/
293     static void convertOptions(LocPosMode& out, const TrackingOptions& trackingOptions);
294     static void convertLocation(Location& out, const UlpLocation& ulpLocation,
295                                 const GpsLocationExtended& locationExtended);
296     static void convertLocationInfo(GnssLocationInfoNotification& out,
297                                     const GpsLocationExtended& locationExtended,
298                                     loc_sess_status status);
299     static uint16_t getNumSvUsed(uint64_t svUsedIdsMask,
300                                  int totalSvCntInThisConstellation);
301 
302     /* ======== UTILITIES ================================================================== */
303     inline void initOdcpi(const OdcpiRequestCallback& callback, OdcpiPrioritytype priority);
304     inline void injectOdcpi(const Location& location);
305     static bool isFlpClient(LocationCallbacks& locationCallbacks);
306 
307     /*==== DGnss Ntrip Source ==========================================================*/
308     StartDgnssNtripParams   mStartDgnssNtripParams;
309     bool    mSendNmeaConsent;
310     DGnssStateBitMask   mDgnssState;
311     void checkUpdateDgnssNtrip(bool isLocationValid);
312     void stopDgnssNtrip();
313     uint64_t   mDgnssLastNmeaBootTimeMilli;
314 
315 protected:
316 
317     /* ==== CLIENT ========================================================================= */
318     virtual void updateClientsEventMask();
319     virtual void stopClientSessions(LocationAPI* client);
320     inline void setNmeaReportRateConfig();
321     void logLatencyInfo();
322 
323 public:
324 
325     GnssAdapter();
~GnssAdapter()326     virtual inline ~GnssAdapter() { }
327 
328     /* ==== SSR ============================================================================ */
329     /* ======== EVENTS ====(Called from QMI Thread)========================================= */
330     virtual void handleEngineUpEvent();
331     /* ======== UTILITIES ================================================================== */
332     void restartSessions(bool modemSSR = false);
333     void checkAndRestartTimeBasedSession();
334     void checkAndRestartSPESession();
335     void suspendSessions();
336 
337     /* ==== CLIENT ========================================================================= */
338     /* ======== COMMANDS ====(Called from Client Thread)==================================== */
339     virtual void addClientCommand(LocationAPI* client, const LocationCallbacks& callbacks);
340 
341     /* ==== TRACKING ======================================================================= */
342     /* ======== COMMANDS ====(Called from Client Thread)==================================== */
343     uint32_t startTrackingCommand(
344             LocationAPI* client, TrackingOptions& trackingOptions);
345     void updateTrackingOptionsCommand(
346             LocationAPI* client, uint32_t id, TrackingOptions& trackingOptions);
347     void stopTrackingCommand(LocationAPI* client, uint32_t id);
348     /* ======== RESPONSES ================================================================== */
349     void reportResponse(LocationAPI* client, LocationError err, uint32_t sessionId);
350     /* ======== UTILITIES ================================================================== */
351     bool isTimeBasedTrackingSession(LocationAPI* client, uint32_t sessionId);
352     bool isDistanceBasedTrackingSession(LocationAPI* client, uint32_t sessionId);
353     bool hasCallbacksToStartTracking(LocationAPI* client);
354     bool isTrackingSession(LocationAPI* client, uint32_t sessionId);
355     void saveTrackingSession(LocationAPI* client, uint32_t sessionId,
356                              const TrackingOptions& trackingOptions);
357     void eraseTrackingSession(LocationAPI* client, uint32_t sessionId);
358 
359     bool setLocPositionMode(const LocPosMode& mode);
getLocPositionMode()360     LocPosMode& getLocPositionMode() { return mLocPositionMode; }
361 
362     bool startTimeBasedTrackingMultiplex(LocationAPI* client, uint32_t sessionId,
363                                          const TrackingOptions& trackingOptions);
364     void startTimeBasedTracking(LocationAPI* client, uint32_t sessionId,
365             const TrackingOptions& trackingOptions);
366     bool stopTimeBasedTrackingMultiplex(LocationAPI* client, uint32_t id);
367     void stopTracking(LocationAPI* client, uint32_t id);
368     bool updateTrackingMultiplex(LocationAPI* client, uint32_t id,
369             const TrackingOptions& trackingOptions);
370     void updateTracking(LocationAPI* client, uint32_t sessionId,
371             const TrackingOptions& updatedOptions, const TrackingOptions& oldOptions);
372     bool checkAndSetSPEToRunforNHz(TrackingOptions & out);
373 
374     void setConstrainedTunc(bool enable, float tuncConstraint,
375                             uint32_t energyBudget, uint32_t sessionId);
376     void setPositionAssistedClockEstimator(bool enable, uint32_t sessionId);
377     void gnssUpdateSvConfig(uint32_t sessionId,
378                         const GnssSvTypeConfig& constellationEnablementConfig,
379                         const GnssSvIdConfig& blacklistSvConfig);
380 
381     void gnssUpdateSecondaryBandConfig(
382         uint32_t sessionId, const GnssSvTypeConfig& secondaryBandConfig);
383     void gnssGetSecondaryBandConfig(uint32_t sessionId);
384     void resetSvConfig(uint32_t sessionId);
385     void configLeverArm(uint32_t sessionId, const LeverArmConfigInfo& configInfo);
386     void configRobustLocation(uint32_t sessionId, bool enable, bool enableForE911);
387     void configMinGpsWeek(uint32_t sessionId, uint16_t minGpsWeek);
388 
389     /* ==== NI ============================================================================= */
390     /* ======== COMMANDS ====(Called from Client Thread)==================================== */
391     void gnssNiResponseCommand(LocationAPI* client, uint32_t id, GnssNiResponse response);
392     /* ======================(Called from NI Thread)======================================== */
393     void gnssNiResponseCommand(GnssNiResponse response, void* rawRequest);
394     /* ======== UTILITIES ================================================================== */
395     bool hasNiNotifyCallback(LocationAPI* client);
getNiData()396     NiData& getNiData() { return mNiData; }
397 
398     /* ==== CONTROL CLIENT ================================================================= */
399     /* ======== COMMANDS ====(Called from Client Thread)==================================== */
400     uint32_t enableCommand(LocationTechnologyType techType);
401     void disableCommand(uint32_t id);
402     void setControlCallbacksCommand(LocationControlCallbacks& controlCallbacks);
403     void readConfigCommand();
404     void requestUlpCommand();
405     void initEngHubProxyCommand();
406     uint32_t* gnssUpdateConfigCommand(const GnssConfig& config);
407     uint32_t* gnssGetConfigCommand(GnssConfigFlagsMask mask);
408     uint32_t gnssDeleteAidingDataCommand(GnssAidingData& data);
409     void deleteAidingData(const GnssAidingData &data, uint32_t sessionId);
410     void gnssUpdateXtraThrottleCommand(const bool enabled);
411     std::vector<LocationError> gnssUpdateConfig(const std::string& oldMoServerUrl,
412             GnssConfig& gnssConfigRequested,
413             GnssConfig& gnssConfigNeedEngineUpdate, size_t count = 0);
414 
415     /* ==== GNSS SV TYPE CONFIG ============================================================ */
416     /* ==== COMMANDS ====(Called from Client Thread)======================================== */
417     /* ==== These commands are received directly from client bypassing Location API ======== */
418     void gnssUpdateSvTypeConfigCommand(GnssSvTypeConfig config);
419     void gnssGetSvTypeConfigCommand(GnssSvTypeConfigCallback callback);
420     void gnssResetSvTypeConfigCommand();
421 
422     /* ==== UTILITIES ====================================================================== */
423     LocationError gnssSvIdConfigUpdateSync(const std::vector<GnssSvIdSource>& blacklistedSvIds);
424     LocationError gnssSvIdConfigUpdateSync();
425     void gnssSvIdConfigUpdate(const std::vector<GnssSvIdSource>& blacklistedSvIds);
426     void gnssSvIdConfigUpdate();
427     void gnssSvTypeConfigUpdate(const GnssSvTypeConfig& config);
428     void gnssSvTypeConfigUpdate(bool sendReset = false);
gnssSetSvTypeConfig(const GnssSvTypeConfig & config)429     inline void gnssSetSvTypeConfig(const GnssSvTypeConfig& config)
430     { mGnssSvTypeConfig = config; }
gnssSetSvTypeConfigCallback(GnssSvTypeConfigCallback callback)431     inline void gnssSetSvTypeConfigCallback(GnssSvTypeConfigCallback callback)
432     { mGnssSvTypeConfigCb = callback; }
gnssGetSvTypeConfigCallback()433     inline GnssSvTypeConfigCallback gnssGetSvTypeConfigCallback()
434     { return mGnssSvTypeConfigCb; }
435     void setConfig();
436     void gnssSecondaryBandConfigUpdate(LocApiResponse* locApiResponse= nullptr);
437 
438     /* ========= AGPS ====================================================================== */
439     /* ======== COMMANDS ====(Called from Client Thread)==================================== */
440     void initDefaultAgpsCommand();
441     void initAgpsCommand(const AgpsCbInfo& cbInfo);
442     void initNfwCommand(const NfwCbInfo& cbInfo);
443     void dataConnOpenCommand(AGpsExtType agpsType,
444             const char* apnName, int apnLen, AGpsBearerType bearerType);
445     void dataConnClosedCommand(AGpsExtType agpsType);
446     void dataConnFailedCommand(AGpsExtType agpsType);
447     void getGnssEnergyConsumedCommand(GnssEnergyConsumedCallback energyConsumedCb);
448     void nfwControlCommand(bool enable);
449     uint32_t setConstrainedTuncCommand (bool enable, float tuncConstraint,
450                                         uint32_t energyBudget);
451     uint32_t setPositionAssistedClockEstimatorCommand (bool enable);
452     uint32_t gnssUpdateSvConfigCommand(const GnssSvTypeConfig& constellationEnablementConfig,
453                                        const GnssSvIdConfig& blacklistSvConfig);
454     uint32_t gnssUpdateSecondaryBandConfigCommand(
455                                        const GnssSvTypeConfig& secondaryBandConfig);
456     uint32_t gnssGetSecondaryBandConfigCommand();
457     uint32_t configLeverArmCommand(const LeverArmConfigInfo& configInfo);
458     uint32_t configRobustLocationCommand(bool enable, bool enableForE911);
459     bool openMeasCorrCommand(const measCorrSetCapabilitiesCb setCapabilitiesCb);
460     bool measCorrSetCorrectionsCommand(const GnssMeasurementCorrections gnssMeasCorr);
closeMeasCorrCommand()461     inline void closeMeasCorrCommand() { mIsMeasCorrInterfaceOpen = false; }
462     uint32_t antennaInfoInitCommand(const antennaInfoCb antennaInfoCallback);
antennaInfoCloseCommand()463     inline void antennaInfoCloseCommand() { mIsAntennaInfoInterfaceOpened = false; }
464     uint32_t configMinGpsWeekCommand(uint16_t minGpsWeek);
465     uint32_t configDeadReckoningEngineParamsCommand(const DeadReckoningEngineConfig& dreConfig);
466     uint32_t configEngineRunStateCommand(PositioningEngineMask engType,
467                                          LocEngineRunState engState);
468 
469     /* ========= ODCPI ===================================================================== */
470     /* ======== COMMANDS ====(Called from Client Thread)==================================== */
471     void initOdcpiCommand(const OdcpiRequestCallback& callback, OdcpiPrioritytype priority);
472     void injectOdcpiCommand(const Location& location);
473     /* ======== RESPONSES ================================================================== */
474     void reportResponse(LocationError err, uint32_t sessionId);
475     void reportResponse(size_t count, LocationError* errs, uint32_t* ids);
476     /* ======== UTILITIES ================================================================== */
getControlCallbacks()477     LocationControlCallbacks& getControlCallbacks() { return mControlCallbacks; }
setControlCallbacks(const LocationControlCallbacks & controlCallbacks)478     void setControlCallbacks(const LocationControlCallbacks& controlCallbacks)
479     { mControlCallbacks = controlCallbacks; }
setAfwControlId(uint32_t id)480     void setAfwControlId(uint32_t id) { mAfwControlId = id; }
getAfwControlId()481     uint32_t getAfwControlId() { return mAfwControlId; }
isInSession()482     virtual bool isInSession() { return !mTimeBasedTrackingSessions.empty(); }
483     void initDefaultAgps();
484     bool initEngHubProxy();
485     void initCDFWService();
486     void odcpiTimerExpireEvent();
487 
488     /* ==== REPORTS ======================================================================== */
489     /* ======== EVENTS ====(Called from QMI/EngineHub Thread)===================================== */
490     virtual void reportPositionEvent(const UlpLocation& ulpLocation,
491                                      const GpsLocationExtended& locationExtended,
492                                      enum loc_sess_status status,
493                                      LocPosTechMask techMask,
494                                      GnssDataNotification* pDataNotify = nullptr,
495                                      int msInWeek = -1);
496     virtual void reportEnginePositionsEvent(unsigned int count,
497                                             EngineLocationInfo* locationArr);
498 
499     virtual void reportSvEvent(const GnssSvNotification& svNotify,
500                                bool fromEngineHub=false);
501     virtual void reportNmeaEvent(const char* nmea, size_t length);
502     virtual void reportDataEvent(const GnssDataNotification& dataNotify, int msInWeek);
503     virtual bool requestNiNotifyEvent(const GnssNiNotification& notify, const void* data,
504                                       const LocInEmergency emergencyState);
505     virtual void reportGnssMeasurementsEvent(const GnssMeasurements& gnssMeasurements,
506                                                 int msInWeek);
507     virtual void reportSvPolynomialEvent(GnssSvPolynomial &svPolynomial);
508     virtual void reportSvEphemerisEvent(GnssSvEphemerisReport & svEphemeris);
509     virtual void reportGnssSvIdConfigEvent(const GnssSvIdConfig& config);
510     virtual void reportGnssSvTypeConfigEvent(const GnssSvTypeConfig& config);
511     virtual void reportGnssConfigEvent(uint32_t sessionId, const GnssConfig& gnssConfig);
512     virtual bool reportGnssEngEnergyConsumedEvent(uint64_t energyConsumedSinceFirstBoot);
513     virtual void reportLocationSystemInfoEvent(const LocationSystemInfo& locationSystemInfo);
514 
515     virtual bool requestATL(int connHandle, LocAGpsType agps_type, LocApnTypeMask apn_type_mask);
516     virtual bool releaseATL(int connHandle);
517     virtual bool requestOdcpiEvent(OdcpiRequestInfo& request);
518     virtual bool reportDeleteAidingDataEvent(GnssAidingData& aidingData);
519     virtual bool reportKlobucharIonoModelEvent(GnssKlobucharIonoModel& ionoModel);
520     virtual bool reportGnssAdditionalSystemInfoEvent(
521             GnssAdditionalSystemInfo& additionalSystemInfo);
522     virtual void reportNfwNotificationEvent(GnssNfwNotification& notification);
523     virtual void reportLatencyInfoEvent(const GnssLatencyInfo& gnssLatencyInfo);
524     virtual bool reportQwesCapabilities
525     (
526         const std::unordered_map<LocationQwesFeatureType, bool> &featureMap
527     );
528 
529     /* ======== UTILITIES ================================================================= */
530     bool needReportForGnssClient(const UlpLocation& ulpLocation,
531             enum loc_sess_status status, LocPosTechMask techMask);
532     bool needReportForFlpClient(enum loc_sess_status status, LocPosTechMask techMask);
533     bool needToGenerateNmeaReport(const uint32_t &gpsTimeOfWeekMs,
534         const struct timespec32_t &apTimeStamp);
535     void reportPosition(const UlpLocation &ulpLocation,
536                         const GpsLocationExtended &locationExtended,
537                         enum loc_sess_status status,
538                         LocPosTechMask techMask);
539     void reportEnginePositions(unsigned int count,
540                                const EngineLocationInfo* locationArr);
541     void reportSv(GnssSvNotification& svNotify);
542     void reportNmea(const char* nmea, size_t length);
543     void reportData(GnssDataNotification& dataNotify);
544     bool requestNiNotify(const GnssNiNotification& notify, const void* data,
545                          const bool bInformNiAccept);
546     void reportGnssMeasurementData(const GnssMeasurementsNotification& measurements);
547     void reportGnssSvIdConfig(const GnssSvIdConfig& config);
548     void reportGnssSvTypeConfig(const GnssSvTypeConfig& config);
549     void reportGnssConfig(uint32_t sessionId, const GnssConfig& gnssConfig);
550     void requestOdcpi(const OdcpiRequestInfo& request);
551     void invokeGnssEnergyConsumedCallback(uint64_t energyConsumedSinceFirstBoot);
552     void saveGnssEnergyConsumedCallback(GnssEnergyConsumedCallback energyConsumedCb);
553     void reportLocationSystemInfo(const LocationSystemInfo & locationSystemInfo);
reportNfwNotification(const GnssNfwNotification & notification)554     inline void reportNfwNotification(const GnssNfwNotification& notification) {
555         if (NULL != mNfwCb) {
556             mNfwCb(notification);
557         }
558     }
getE911State(void)559     inline bool getE911State(void) {
560         if (NULL != mIsE911Session) {
561             return mIsE911Session();
562         }
563         return false;
564     }
565 
566     void updateSystemPowerState(PowerStateType systemPowerState);
567     void reportSvPolynomial(const GnssSvPolynomial &svPolynomial);
568 
569 
570     std::vector<double> parseDoublesString(char* dString);
571     void reportGnssAntennaInformation(const antennaInfoCb antennaInfoCallback);
572 
573     /*======== GNSSDEBUG ================================================================*/
574     bool getDebugReport(GnssDebugReport& report);
575     /* get AGC information from system status and fill it */
576     void getAgcInformation(GnssMeasurementsNotification& measurements, int msInWeek);
577     /* get Data information from system status and fill it */
578     void getDataInformation(GnssDataNotification& data, int msInWeek);
579 
580     /*==== SYSTEM STATUS ================================================================*/
getSystemStatus(void)581     inline SystemStatus* getSystemStatus(void) { return mSystemStatus; }
getServerUrl(void)582     std::string& getServerUrl(void) { return mServerUrl; }
getMoServerUrl(void)583     std::string& getMoServerUrl(void) { return mMoServerUrl; }
584 
585     /*==== CONVERSION ===================================================================*/
586     static uint32_t convertSuplVersion(const GnssConfigSuplVersion suplVersion);
587     static uint32_t convertEP4ES(const GnssConfigEmergencyPdnForEmergencySupl);
588     static uint32_t convertSuplEs(const GnssConfigSuplEmergencyServices suplEmergencyServices);
589     static uint32_t convertLppeCp(const GnssConfigLppeControlPlaneMask lppeControlPlaneMask);
590     static uint32_t convertLppeUp(const GnssConfigLppeUserPlaneMask lppeUserPlaneMask);
591     static uint32_t convertAGloProt(const GnssConfigAGlonassPositionProtocolMask);
592     static uint32_t convertSuplMode(const GnssConfigSuplModeMask suplModeMask);
593     static void convertSatelliteInfo(std::vector<GnssDebugSatelliteInfo>& out,
594                                      const GnssSvType& in_constellation,
595                                      const SystemStatusReports& in);
596     static bool convertToGnssSvIdConfig(
597             const std::vector<GnssSvIdSource>& blacklistedSvIds, GnssSvIdConfig& config);
598     static void convertFromGnssSvIdConfig(
599             const GnssSvIdConfig& svConfig, std::vector<GnssSvIdSource>& blacklistedSvIds);
600     static void convertGnssSvIdMaskToList(
601             uint64_t svIdMask, std::vector<GnssSvIdSource>& svIds,
602             GnssSvId initialSvId, GnssSvType svType);
603     static void computeVRPBasedLla(const UlpLocation& loc, GpsLocationExtended& locExt,
604                                    const LeverArmConfigInfo& leverArmConfigInfo);
605 
606     void injectLocationCommand(double latitude, double longitude, float accuracy);
607     void injectLocationExtCommand(const GnssLocationInfoNotification &locationInfo);
608 
609     void injectTimeCommand(int64_t time, int64_t timeReference, int32_t uncertainty);
610     void blockCPICommand(double latitude, double longitude, float accuracy,
611                          int blockDurationMsec, double latLonDiffThreshold);
612 
613     /* ==== MISCELLANEOUS ================================================================== */
614     /* ======== COMMANDS ====(Called from Client Thread)==================================== */
615     void getPowerStateChangesCommand(std::function<void(bool)> powerStateCb);
616     /* ======== UTILITIES ================================================================== */
617     void reportPowerStateIfChanged();
savePowerStateCallback(std::function<void (bool)> powerStateCb)618     void savePowerStateCallback(std::function<void(bool)> powerStateCb){
619             mPowerStateCb = powerStateCb; }
getPowerState()620     bool getPowerState() { return mPowerOn; }
getSystemPowerState()621     inline PowerStateType getSystemPowerState() { return mSystemPowerState; }
622 
setAllowFlpNetworkFixes(uint32_t allow)623     void setAllowFlpNetworkFixes(uint32_t allow) { mAllowFlpNetworkFixes = allow; }
getAllowFlpNetworkFixes()624     uint32_t getAllowFlpNetworkFixes() { return mAllowFlpNetworkFixes; }
625     void setSuplHostServer(const char* server, int port, LocServerType type);
626     void notifyClientOfCachedLocationSystemInfo(LocationAPI* client,
627                                                 const LocationCallbacks& callbacks);
628     LocationCapabilitiesMask getCapabilities();
629     void updateSystemPowerStateCommand(PowerStateType systemPowerState);
630 
631     /*==== DGnss Usable Report Flag ====================================================*/
setDGnssUsableFLag(bool dGnssNeedReport)632     inline void setDGnssUsableFLag(bool dGnssNeedReport) { mDGnssNeedReport = dGnssNeedReport;}
isNMEAPrintEnabled()633     inline bool isNMEAPrintEnabled() {
634        return ((mContext != NULL) && (0 != mContext->mGps_conf.ENABLE_NMEA_PRINT));
635     }
636 
637     /*==== DGnss Ntrip Source ==========================================================*/
updateNTRIPGGAConsentCommand(bool consentAccepted)638     void updateNTRIPGGAConsentCommand(bool consentAccepted) { mSendNmeaConsent = consentAccepted; }
639     void enablePPENtripStreamCommand(const GnssNtripConnectionParams& params, bool enableRTKEngine);
640     void disablePPENtripStreamCommand();
641     void handleEnablePPENtrip(const GnssNtripConnectionParams& params);
642     void handleDisablePPENtrip();
643     void reportGGAToNtrip(const char* nmea);
isDgnssNmeaRequired()644     inline bool isDgnssNmeaRequired() { return mSendNmeaConsent &&
645             mStartDgnssNtripParams.ntripParams.requiresNmeaLocation;}
646 };
647 
648 #endif //GNSS_ADAPTER_H
649