1 /* Copyright (c) 2009-2016, 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 
30 #define LOG_NDDEBUG 0
31 #define LOG_TAG "LocSvc_eng"
32 
33 #include <stdint.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <unistd.h>
37 #include <dlfcn.h>
38 #include <ctype.h>
39 #include <math.h>
40 #include <pthread.h>
41 #include <arpa/inet.h>
42 #include <netinet/in.h>         /* struct sockaddr_in */
43 #include <sys/socket.h>
44 #include <sys/time.h>
45 #include <netdb.h>
46 #include <time.h>
47 #include <new>
48 #include <LocEngAdapter.h>
49 
50 #include <cutils/sched_policy.h>
51 #ifndef USE_GLIB
52 #include <utils/SystemClock.h>
53 #include <utils/Log.h>
54 #endif /* USE_GLIB */
55 
56 #ifdef USE_GLIB
57 #include <glib.h>
58 #include <sys/syscall.h>
59 #endif /* USE_GLIB */
60 
61 #include <string.h>
62 
63 #include <loc_eng.h>
64 #include <loc_eng_ni.h>
65 #include <loc_eng_dmn_conn.h>
66 #include <loc_eng_dmn_conn_handler.h>
67 #include <loc_eng_msg.h>
68 #include <loc_eng_nmea.h>
69 #include <msg_q.h>
70 #include <loc.h>
71 #include "log_util.h"
72 #include "platform_lib_includes.h"
73 #include "loc_core_log.h"
74 #include "loc_eng_log.h"
75 
76 #define SUCCESS TRUE
77 #define FAILURE FALSE
78 
79 #ifndef GPS_CONF_FILE
80 #define GPS_CONF_FILE            "/vendor/etc/gps.conf"   //??? platform independent
81 #endif
82 
83 #ifndef SAP_CONF_FILE
84 #define SAP_CONF_FILE            "/vendor/etc/sap.conf"
85 #endif
86 
87 #define XTRA1_GPSONEXTRA         "xtra1.gpsonextra.net"
88 
89 using namespace loc_core;
90 
91 boolean configAlreadyRead = false;
92 unsigned int agpsStatus = 0;
93 
94 /* Parameter spec table */
95 static const loc_param_s_type gps_conf_table[] =
96 {
97   {"GPS_LOCK",                       &gps_conf.GPS_LOCK,                       NULL, 'n'},
98   {"SUPL_VER",                       &gps_conf.SUPL_VER,                       NULL, 'n'},
99   {"LPP_PROFILE",                    &gps_conf.LPP_PROFILE,                    NULL, 'n'},
100   {"A_GLONASS_POS_PROTOCOL_SELECT",  &gps_conf.A_GLONASS_POS_PROTOCOL_SELECT,  NULL, 'n'},
101   {"AGPS_CERT_WRITABLE_MASK",        &gps_conf.AGPS_CERT_WRITABLE_MASK,        NULL, 'n'},
102   {"SUPL_MODE",                      &gps_conf.SUPL_MODE,                      NULL, 'n'},
103   {"INTERMEDIATE_POS",               &gps_conf.INTERMEDIATE_POS,               NULL, 'n'},
104   {"ACCURACY_THRES",                 &gps_conf.ACCURACY_THRES,                 NULL, 'n'},
105   {"NMEA_PROVIDER",                  &gps_conf.NMEA_PROVIDER,                  NULL, 'n'},
106   {"CAPABILITIES",                   &gps_conf.CAPABILITIES,                   NULL, 'n'},
107   {"XTRA_VERSION_CHECK",             &gps_conf.XTRA_VERSION_CHECK,             NULL, 'n'},
108   {"XTRA_SERVER_1",                  &gps_conf.XTRA_SERVER_1,                  NULL, 's'},
109   {"XTRA_SERVER_2",                  &gps_conf.XTRA_SERVER_2,                  NULL, 's'},
110   {"XTRA_SERVER_3",                  &gps_conf.XTRA_SERVER_3,                  NULL, 's'},
111   {"USE_EMERGENCY_PDN_FOR_EMERGENCY_SUPL",  &gps_conf.USE_EMERGENCY_PDN_FOR_EMERGENCY_SUPL,          NULL, 'n'},
112 };
113 
114 static const loc_param_s_type sap_conf_table[] =
115 {
116   {"GYRO_BIAS_RANDOM_WALK",          &sap_conf.GYRO_BIAS_RANDOM_WALK,          &sap_conf.GYRO_BIAS_RANDOM_WALK_VALID, 'f'},
117   {"ACCEL_RANDOM_WALK_SPECTRAL_DENSITY",     &sap_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY,    &sap_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY_VALID, 'f'},
118   {"ANGLE_RANDOM_WALK_SPECTRAL_DENSITY",     &sap_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY,    &sap_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY_VALID, 'f'},
119   {"RATE_RANDOM_WALK_SPECTRAL_DENSITY",      &sap_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY,     &sap_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY_VALID, 'f'},
120   {"VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY",  &sap_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY, &sap_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY_VALID, 'f'},
121   {"SENSOR_ACCEL_BATCHES_PER_SEC",   &sap_conf.SENSOR_ACCEL_BATCHES_PER_SEC,   NULL, 'n'},
122   {"SENSOR_ACCEL_SAMPLES_PER_BATCH", &sap_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH, NULL, 'n'},
123   {"SENSOR_GYRO_BATCHES_PER_SEC",    &sap_conf.SENSOR_GYRO_BATCHES_PER_SEC,    NULL, 'n'},
124   {"SENSOR_GYRO_SAMPLES_PER_BATCH",  &sap_conf.SENSOR_GYRO_SAMPLES_PER_BATCH,  NULL, 'n'},
125   {"SENSOR_ACCEL_BATCHES_PER_SEC_HIGH",   &sap_conf.SENSOR_ACCEL_BATCHES_PER_SEC_HIGH,   NULL, 'n'},
126   {"SENSOR_ACCEL_SAMPLES_PER_BATCH_HIGH", &sap_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH_HIGH, NULL, 'n'},
127   {"SENSOR_GYRO_BATCHES_PER_SEC_HIGH",    &sap_conf.SENSOR_GYRO_BATCHES_PER_SEC_HIGH,    NULL, 'n'},
128   {"SENSOR_GYRO_SAMPLES_PER_BATCH_HIGH",  &sap_conf.SENSOR_GYRO_SAMPLES_PER_BATCH_HIGH,  NULL, 'n'},
129   {"SENSOR_CONTROL_MODE",            &sap_conf.SENSOR_CONTROL_MODE,            NULL, 'n'},
130   {"SENSOR_USAGE",                   &sap_conf.SENSOR_USAGE,                   NULL, 'n'},
131   {"SENSOR_ALGORITHM_CONFIG_MASK",   &sap_conf.SENSOR_ALGORITHM_CONFIG_MASK,   NULL, 'n'},
132   {"SENSOR_PROVIDER",                &sap_conf.SENSOR_PROVIDER,                NULL, 'n'}
133 };
134 
loc_default_parameters(void)135 static void loc_default_parameters(void)
136 {
137    /*Defaults for gps.conf*/
138    gps_conf.INTERMEDIATE_POS = 0;
139    gps_conf.ACCURACY_THRES = 0;
140    gps_conf.NMEA_PROVIDER = 0;
141    gps_conf.GPS_LOCK = 0;
142    gps_conf.SUPL_VER = 0x10000;
143    gps_conf.SUPL_MODE = 0x3;
144    gps_conf.CAPABILITIES = 0x7;
145    /* LTE Positioning Profile configuration is disable by default*/
146    gps_conf.LPP_PROFILE = 0;
147    /*By default no positioning protocol is selected on A-GLONASS system*/
148    gps_conf.A_GLONASS_POS_PROTOCOL_SELECT = 0;
149    /*XTRA version check is disabled by default*/
150    gps_conf.XTRA_VERSION_CHECK=0;
151    /*Use emergency PDN by default*/
152    gps_conf.USE_EMERGENCY_PDN_FOR_EMERGENCY_SUPL = 1;
153 
154    /*Defaults for sap.conf*/
155    sap_conf.GYRO_BIAS_RANDOM_WALK = 0;
156    sap_conf.SENSOR_ACCEL_BATCHES_PER_SEC = 2;
157    sap_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH = 5;
158    sap_conf.SENSOR_GYRO_BATCHES_PER_SEC = 2;
159    sap_conf.SENSOR_GYRO_SAMPLES_PER_BATCH = 5;
160    sap_conf.SENSOR_ACCEL_BATCHES_PER_SEC_HIGH = 4;
161    sap_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH_HIGH = 25;
162    sap_conf.SENSOR_GYRO_BATCHES_PER_SEC_HIGH = 4;
163    sap_conf.SENSOR_GYRO_SAMPLES_PER_BATCH_HIGH = 25;
164    sap_conf.SENSOR_CONTROL_MODE = 0; /* AUTO */
165    sap_conf.SENSOR_USAGE = 0; /* Enabled */
166    sap_conf.SENSOR_ALGORITHM_CONFIG_MASK = 0; /* INS Disabled = FALSE*/
167    /* Values MUST be set by OEMs in configuration for sensor-assisted
168       navigation to work. There are NO default values */
169    sap_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY = 0;
170    sap_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY = 0;
171    sap_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY = 0;
172    sap_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY = 0;
173    sap_conf.GYRO_BIAS_RANDOM_WALK_VALID = 0;
174    sap_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY_VALID = 0;
175    sap_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY_VALID = 0;
176    sap_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY_VALID = 0;
177    sap_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY_VALID = 0;
178    /* default provider is SSC */
179    sap_conf.SENSOR_PROVIDER = 1;
180 
181    /* None of the 10 slots for agps certificates are writable by default */
182    gps_conf.AGPS_CERT_WRITABLE_MASK = 0;
183 }
184 
185 // 2nd half of init(), singled out for
186 // modem restart to use.
187 static int loc_eng_reinit(loc_eng_data_s_type &loc_eng_data);
188 static void loc_eng_agps_reinit(loc_eng_data_s_type &loc_eng_data);
189 
190 static int loc_eng_set_server(loc_eng_data_s_type &loc_eng_data,
191                               LocServerType type, const char *hostname, int port);
192 // Internal functions
193 static void loc_inform_gps_status(loc_eng_data_s_type &loc_eng_data,
194                                   GpsStatusValue status);
195 static void loc_eng_report_status(loc_eng_data_s_type &loc_eng_data,
196                                   GpsStatusValue status);
197 static void loc_eng_process_conn_request(loc_eng_data_s_type &loc_eng_data,
198                                          int connHandle, AGpsType agps_type);
199 static void loc_eng_agps_close_status(loc_eng_data_s_type &loc_eng_data, int is_succ);
200 static void loc_eng_handle_engine_down(loc_eng_data_s_type &loc_eng_data) ;
201 static void loc_eng_handle_engine_up(loc_eng_data_s_type &loc_eng_data) ;
202 
203 static int loc_eng_start_handler(loc_eng_data_s_type &loc_eng_data);
204 static int loc_eng_stop_handler(loc_eng_data_s_type &loc_eng_data);
205 static int loc_eng_get_zpp_handler(loc_eng_data_s_type &loc_eng_data);
206 static void deleteAidingData(loc_eng_data_s_type &logEng);
207 static AgpsStateMachine*
208 getAgpsStateMachine(loc_eng_data_s_type& logEng, AGpsExtType agpsType);
209 static int dataCallCb(void *cb_data);
update_aiding_data_for_deletion(loc_eng_data_s_type & loc_eng_data)210 static void update_aiding_data_for_deletion(loc_eng_data_s_type& loc_eng_data) {
211     if (loc_eng_data.engine_status != GPS_STATUS_ENGINE_ON &&
212         loc_eng_data.aiding_data_for_deletion != 0)
213     {
214         loc_eng_data.adapter->deleteAidingData(loc_eng_data.aiding_data_for_deletion);
215         loc_eng_data.aiding_data_for_deletion = 0;
216     }
217 }
218 
noProc(void * data)219 static void* noProc(void* data)
220 {
221     return NULL;
222 }
223 
224 /*********************************************************************
225  * definitions of the static messages used in the file
226  *********************************************************************/
227 //        case LOC_ENG_MSG_REQUEST_NI:
LocEngRequestNi(void * locEng,GpsNiNotification & notif,const void * data)228 LocEngRequestNi::LocEngRequestNi(void* locEng,
229                                  GpsNiNotification &notif,
230                                  const void* data) :
231     LocMsg(), mLocEng(locEng), mNotify(notif), mPayload(data) {
232     locallog();
233 }
proc() const234 void LocEngRequestNi::proc() const {
235     loc_eng_ni_request_handler(*((loc_eng_data_s_type*)mLocEng),
236                                &mNotify, mPayload);
237 }
locallog() const238 void LocEngRequestNi::locallog() const
239 {
240     LOC_LOGV("id: %d\n  type: %s\n  flags: %d\n  time out: %d\n  "
241              "default response: %s\n  requestor id encoding: %s\n"
242              "  text encoding: %s\n  passThroughData: %p",
243              mNotify.notification_id,
244              loc_get_ni_type_name(mNotify.ni_type),
245              mNotify.notify_flags,
246              mNotify.timeout,
247              loc_get_ni_response_name(mNotify.default_response),
248              loc_get_ni_encoding_name(mNotify.requestor_id_encoding),
249              loc_get_ni_encoding_name(mNotify.text_encoding),
250              mPayload);
251 }
log() const252 inline void LocEngRequestNi::log() const {
253     locallog();
254 }
255 
256 //        case LOC_ENG_MSG_INFORM_NI_RESPONSE:
257 // in loc_eng_ni.cpp
258 
259 //        case LOC_ENG_MSG_START_FIX:
LocEngStartFix(LocEngAdapter * adapter)260 LocEngStartFix::LocEngStartFix(LocEngAdapter* adapter) :
261     LocMsg(), mAdapter(adapter)
262 {
263     locallog();
264 }
proc() const265 inline void LocEngStartFix::proc() const
266 {
267     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mAdapter->getOwner();
268     loc_eng_start_handler(*locEng);
269 }
locallog() const270 inline void LocEngStartFix::locallog() const
271 {
272     LOC_LOGV("LocEngStartFix");
273 }
log() const274 inline void LocEngStartFix::log() const
275 {
276     locallog();
277 }
send() const278 void LocEngStartFix::send() const {
279     mAdapter->sendMsg(this);
280 }
281 
282 //        case LOC_ENG_MSG_STOP_FIX:
LocEngStopFix(LocEngAdapter * adapter)283 LocEngStopFix::LocEngStopFix(LocEngAdapter* adapter) :
284     LocMsg(), mAdapter(adapter)
285 {
286     locallog();
287 }
proc() const288 inline void LocEngStopFix::proc() const
289 {
290     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mAdapter->getOwner();
291     loc_eng_stop_handler(*locEng);
292 }
locallog() const293 inline void LocEngStopFix::locallog() const
294 {
295     LOC_LOGV("LocEngStopFix");
296 }
log() const297 inline void LocEngStopFix::log() const
298 {
299     locallog();
300 }
send() const301 void LocEngStopFix::send() const {
302     mAdapter->sendMsg(this);
303 }
304 
305 //        case LOC_ENG_MSG_SET_POSITION_MODE:
LocEngPositionMode(LocEngAdapter * adapter,LocPosMode & mode)306 LocEngPositionMode::LocEngPositionMode(LocEngAdapter* adapter,
307                                        LocPosMode &mode) :
308     LocMsg(), mAdapter(adapter), mPosMode(mode)
309 {
310     mPosMode.logv();
311 }
proc() const312 inline void LocEngPositionMode::proc() const {
313     mAdapter->setPositionMode(&mPosMode);
314 }
log() const315 inline void LocEngPositionMode::log() const {
316     mPosMode.logv();
317 }
send() const318 void LocEngPositionMode::send() const {
319     mAdapter->sendMsg(this);
320 }
321 
LocEngGetZpp(LocEngAdapter * adapter)322 LocEngGetZpp::LocEngGetZpp(LocEngAdapter* adapter) :
323     LocMsg(), mAdapter(adapter)
324 {
325     locallog();
326 }
proc() const327 inline void LocEngGetZpp::proc() const
328 {
329     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mAdapter->getOwner();
330     loc_eng_get_zpp_handler(*locEng);
331 }
locallog() const332 inline void LocEngGetZpp::locallog() const
333 {
334     LOC_LOGV("LocEngGetZpp");
335 }
log() const336 inline void LocEngGetZpp::log() const
337 {
338     locallog();
339 }
send() const340 void LocEngGetZpp::send() const {
341     mAdapter->sendMsg(this);
342 }
343 
344 struct LocEngSetTime : public LocMsg {
345     LocEngAdapter* mAdapter;
346     const GpsUtcTime mTime;
347     const int64_t mTimeReference;
348     const int mUncertainty;
LocEngSetTimeLocEngSetTime349     inline LocEngSetTime(LocEngAdapter* adapter,
350                          GpsUtcTime t, int64_t tf, int unc) :
351         LocMsg(), mAdapter(adapter),
352         mTime(t), mTimeReference(tf), mUncertainty(unc)
353     {
354         locallog();
355     }
procLocEngSetTime356     inline virtual void proc() const {
357         mAdapter->setTime(mTime, mTimeReference, mUncertainty);
358     }
locallogLocEngSetTime359     inline void locallog() const {
360         LOC_LOGV("time: %lld\n  timeReference: %lld\n  uncertainty: %d",
361                  mTime, mTimeReference, mUncertainty);
362     }
logLocEngSetTime363     inline virtual void log() const {
364         locallog();
365     }
366 };
367 
368  //       case LOC_ENG_MSG_INJECT_LOCATION:
369 struct LocEngInjectLocation : public LocMsg {
370     LocEngAdapter* mAdapter;
371     const double mLatitude;
372     const double mLongitude;
373     const float mAccuracy;
LocEngInjectLocationLocEngInjectLocation374     inline LocEngInjectLocation(LocEngAdapter* adapter,
375                                 double lat, double lon, float accur) :
376         LocMsg(), mAdapter(adapter),
377         mLatitude(lat), mLongitude(lon), mAccuracy(accur)
378     {
379         locallog();
380     }
procLocEngInjectLocation381     inline virtual void proc() const {
382         mAdapter->injectPosition(mLatitude, mLongitude, mAccuracy);
383     }
locallogLocEngInjectLocation384     inline void locallog() const {
385         LOC_LOGV("latitude: %f\n  longitude: %f\n  accuracy: %f",
386                  mLatitude, mLongitude, mAccuracy);
387     }
logLocEngInjectLocation388     inline virtual void log() const {
389         locallog();
390     }
391 };
392 
393 //        case LOC_ENG_MSG_SET_SERVER_IPV4:
394 struct LocEngSetServerIpv4 : public LocMsg {
395     LocEngAdapter* mAdapter;
396     const unsigned int mNlAddr;
397     const int mPort;
398     const LocServerType mServerType;
LocEngSetServerIpv4LocEngSetServerIpv4399     inline LocEngSetServerIpv4(LocEngAdapter* adapter,
400                                unsigned int ip,
401                                int port,
402                                LocServerType type) :
403         LocMsg(), mAdapter(adapter),
404         mNlAddr(ip), mPort(port), mServerType(type)
405     {
406         locallog();
407     }
procLocEngSetServerIpv4408     inline virtual void proc() const {
409         mAdapter->setServer(mNlAddr, mPort, mServerType);
410     }
locallogLocEngSetServerIpv4411     inline void locallog() const {
412         LOC_LOGV("LocEngSetServerIpv4 - addr: %x, port: %d, type: %s",
413                  mNlAddr, mPort, loc_get_server_type_name(mServerType));
414     }
logLocEngSetServerIpv4415     inline virtual void log() const {
416         locallog();
417     }
418 };
419 
420 //        case LOC_ENG_MSG_SET_SERVER_URL:
421 struct LocEngSetServerUrl : public LocMsg {
422     LocEngAdapter* mAdapter;
423     const int mLen;
424     char* mUrl;
LocEngSetServerUrlLocEngSetServerUrl425     inline LocEngSetServerUrl(LocEngAdapter* adapter,
426                               char* urlString,
427                               int url_len) :
428         LocMsg(), mAdapter(adapter),
429         mLen(url_len), mUrl(new char[mLen+1])
430     {
431         memcpy((void*)mUrl, (void*)urlString, url_len);
432         mUrl[mLen] = 0;
433         locallog();
434     }
~LocEngSetServerUrlLocEngSetServerUrl435     inline ~LocEngSetServerUrl()
436     {
437         delete[] mUrl;
438     }
procLocEngSetServerUrl439     inline virtual void proc() const {
440         mAdapter->setServer(mUrl, mLen);
441     }
locallogLocEngSetServerUrl442     inline void locallog() const {
443         LOC_LOGV("LocEngSetServerUrl - url: %s", mUrl);
444     }
logLocEngSetServerUrl445     inline virtual void log() const {
446         locallog();
447     }
448 };
449 
450 //        case LOC_ENG_MSG_A_GLONASS_PROTOCOL:
451 struct LocEngAGlonassProtocol : public LocMsg {
452     LocEngAdapter* mAdapter;
453     const unsigned long mAGlonassProtocl;
LocEngAGlonassProtocolLocEngAGlonassProtocol454     inline LocEngAGlonassProtocol(LocEngAdapter* adapter,
455                                   unsigned long protocol) :
456         LocMsg(), mAdapter(adapter), mAGlonassProtocl(protocol)
457     {
458         locallog();
459     }
procLocEngAGlonassProtocol460     inline virtual void proc() const {
461         mAdapter->setAGLONASSProtocol(mAGlonassProtocl);
462     }
locallogLocEngAGlonassProtocol463     inline  void locallog() const {
464         LOC_LOGV("A-GLONASS protocol: 0x%lx", mAGlonassProtocl);
465     }
logLocEngAGlonassProtocol466     inline virtual void log() const {
467         locallog();
468     }
469 };
470 
471 //        case LOC_ENG_MSG_SUPL_VERSION:
472 struct LocEngSuplVer : public LocMsg {
473     LocEngAdapter* mAdapter;
474     const int mSuplVer;
LocEngSuplVerLocEngSuplVer475     inline LocEngSuplVer(LocEngAdapter* adapter,
476                          int suplVer) :
477         LocMsg(), mAdapter(adapter), mSuplVer(suplVer)
478     {
479         locallog();
480     }
procLocEngSuplVer481     inline virtual void proc() const {
482         mAdapter->setSUPLVersion(mSuplVer);
483     }
locallogLocEngSuplVer484     inline  void locallog() const {
485         LOC_LOGV("SUPL Version: %d", mSuplVer);
486     }
logLocEngSuplVer487     inline virtual void log() const {
488         locallog();
489     }
490 };
491 
492 struct LocEngSuplMode : public LocMsg {
493     UlpProxyBase* mUlp;
494 
LocEngSuplModeLocEngSuplMode495     inline LocEngSuplMode(UlpProxyBase* ulp) :
496         LocMsg(), mUlp(ulp)
497     {
498         locallog();
499     }
procLocEngSuplMode500     inline virtual void proc() const {
501         mUlp->setCapabilities(ContextBase::getCarrierCapabilities());
502     }
locallogLocEngSuplMode503     inline  void locallog() const {
504     }
logLocEngSuplMode505     inline virtual void log() const {
506         locallog();
507     }
508 };
509 
510 //        case LOC_ENG_MSG_LPP_CONFIG:
511 struct LocEngLppConfig : public LocMsg {
512     LocEngAdapter* mAdapter;
513     const int mLppConfig;
LocEngLppConfigLocEngLppConfig514     inline LocEngLppConfig(LocEngAdapter* adapter,
515                            int lppConfig) :
516         LocMsg(), mAdapter(adapter), mLppConfig(lppConfig)
517     {
518         locallog();
519     }
procLocEngLppConfig520     inline virtual void proc() const {
521         mAdapter->setLPPConfig(mLppConfig);
522     }
locallogLocEngLppConfig523     inline void locallog() const {
524         LOC_LOGV("LocEngLppConfig - profile: %d", mLppConfig);
525     }
logLocEngLppConfig526     inline virtual void log() const {
527         locallog();
528     }
529 };
530 
531 //        case LOC_ENG_MSG_SET_SENSOR_CONTROL_CONFIG:
532 struct LocEngSensorControlConfig : public LocMsg {
533     LocEngAdapter* mAdapter;
534     const int mSensorsDisabled;
535     const int mSensorProvider;
LocEngSensorControlConfigLocEngSensorControlConfig536     inline LocEngSensorControlConfig(LocEngAdapter* adapter,
537                                      int sensorsDisabled, int sensorProvider) :
538         LocMsg(), mAdapter(adapter), mSensorsDisabled(sensorsDisabled),
539         mSensorProvider(sensorProvider)
540     {
541         locallog();
542     }
procLocEngSensorControlConfig543     inline virtual void proc() const {
544         mAdapter->setSensorControlConfig(mSensorsDisabled, mSensorProvider);
545     }
locallogLocEngSensorControlConfig546     inline  void locallog() const {
547         LOC_LOGV("LocEngSensorControlConfig - Sensors Disabled: %d, Sensor Provider: %d",
548                  mSensorsDisabled, mSensorProvider);
549     }
logLocEngSensorControlConfig550     inline virtual void log() const {
551         locallog();
552     }
553 };
554 
555 //        case LOC_ENG_MSG_SET_SENSOR_PROPERTIES:
556 struct LocEngSensorProperties : public LocMsg {
557     LocEngAdapter* mAdapter;
558     const bool mGyroBiasVarianceRandomWalkValid;
559     const float mGyroBiasVarianceRandomWalk;
560     const bool mAccelRandomWalkValid;
561     const float mAccelRandomWalk;
562     const bool mAngleRandomWalkValid;
563     const float mAngleRandomWalk;
564     const bool mRateRandomWalkValid;
565     const float mRateRandomWalk;
566     const bool mVelocityRandomWalkValid;
567     const float mVelocityRandomWalk;
LocEngSensorPropertiesLocEngSensorProperties568     inline LocEngSensorProperties(LocEngAdapter* adapter,
569                                   bool gyroBiasRandomWalk_valid,
570                                   float gyroBiasRandomWalk,
571                                   bool accelRandomWalk_valid,
572                                   float accelRandomWalk,
573                                   bool angleRandomWalk_valid,
574                                   float angleRandomWalk,
575                                   bool rateRandomWalk_valid,
576                                   float rateRandomWalk,
577                                   bool velocityRandomWalk_valid,
578                                   float velocityRandomWalk) :
579         LocMsg(), mAdapter(adapter),
580         mGyroBiasVarianceRandomWalkValid(gyroBiasRandomWalk_valid),
581         mGyroBiasVarianceRandomWalk(gyroBiasRandomWalk),
582         mAccelRandomWalkValid(accelRandomWalk_valid),
583         mAccelRandomWalk(accelRandomWalk),
584         mAngleRandomWalkValid(angleRandomWalk_valid),
585         mAngleRandomWalk(angleRandomWalk),
586         mRateRandomWalkValid(rateRandomWalk_valid),
587         mRateRandomWalk(rateRandomWalk),
588         mVelocityRandomWalkValid(velocityRandomWalk_valid),
589         mVelocityRandomWalk(velocityRandomWalk)
590     {
591         locallog();
592     }
procLocEngSensorProperties593     inline virtual void proc() const {
594         mAdapter->setSensorProperties(mGyroBiasVarianceRandomWalkValid,
595                                       mGyroBiasVarianceRandomWalk,
596                                       mAccelRandomWalkValid,
597                                       mAccelRandomWalk,
598                                       mAngleRandomWalkValid,
599                                       mAngleRandomWalk,
600                                       mRateRandomWalkValid,
601                                       mRateRandomWalk,
602                                       mVelocityRandomWalkValid,
603                                       mVelocityRandomWalk);
604     }
locallogLocEngSensorProperties605     inline  void locallog() const {
606         LOC_LOGV("Sensor properties validity, Gyro Random walk: %d "
607                  "Accel Random Walk: %d "
608                  "Angle Random Walk: %d Rate Random Walk: %d "
609                  "Velocity Random Walk: %d\n"
610                  "Sensor properties, Gyro Random walk: %f "
611                  "Accel Random Walk: %f "
612                  "Angle Random Walk: %f Rate Random Walk: %f "
613                  "Velocity Random Walk: %f",
614                  mGyroBiasVarianceRandomWalkValid,
615                  mAccelRandomWalkValid,
616                  mAngleRandomWalkValid,
617                  mRateRandomWalkValid,
618                  mVelocityRandomWalkValid,
619                  mGyroBiasVarianceRandomWalk,
620                  mAccelRandomWalk,
621                  mAngleRandomWalk,
622                  mRateRandomWalk,
623                  mVelocityRandomWalk
624             );
625     }
logLocEngSensorProperties626     inline virtual void log() const {
627         locallog();
628     }
629 };
630 
631 //        case LOC_ENG_MSG_SET_SENSOR_PERF_CONTROL_CONFIG:
632 struct LocEngSensorPerfControlConfig : public LocMsg {
633     LocEngAdapter* mAdapter;
634     const int mControlMode;
635     const int mAccelSamplesPerBatch;
636     const int mAccelBatchesPerSec;
637     const int mGyroSamplesPerBatch;
638     const int mGyroBatchesPerSec;
639     const int mAccelSamplesPerBatchHigh;
640     const int mAccelBatchesPerSecHigh;
641     const int mGyroSamplesPerBatchHigh;
642     const int mGyroBatchesPerSecHigh;
643     const int mAlgorithmConfig;
LocEngSensorPerfControlConfigLocEngSensorPerfControlConfig644     inline LocEngSensorPerfControlConfig(LocEngAdapter* adapter,
645                                          int controlMode,
646                                          int accelSamplesPerBatch,
647                                          int accelBatchesPerSec,
648                                          int gyroSamplesPerBatch,
649                                          int gyroBatchesPerSec,
650                                          int accelSamplesPerBatchHigh,
651                                          int accelBatchesPerSecHigh,
652                                          int gyroSamplesPerBatchHigh,
653                                          int gyroBatchesPerSecHigh,
654                                          int algorithmConfig) :
655         LocMsg(), mAdapter(adapter),
656         mControlMode(controlMode),
657         mAccelSamplesPerBatch(accelSamplesPerBatch),
658         mAccelBatchesPerSec(accelBatchesPerSec),
659         mGyroSamplesPerBatch(gyroSamplesPerBatch),
660         mGyroBatchesPerSec(gyroBatchesPerSec),
661         mAccelSamplesPerBatchHigh(accelSamplesPerBatchHigh),
662         mAccelBatchesPerSecHigh(accelBatchesPerSecHigh),
663         mGyroSamplesPerBatchHigh(gyroSamplesPerBatchHigh),
664         mGyroBatchesPerSecHigh(gyroBatchesPerSecHigh),
665         mAlgorithmConfig(algorithmConfig)
666     {
667         locallog();
668     }
procLocEngSensorPerfControlConfig669     inline virtual void proc() const {
670         mAdapter->setSensorPerfControlConfig(mControlMode,
671                                              mAccelSamplesPerBatch,
672                                              mAccelBatchesPerSec,
673                                              mGyroSamplesPerBatch,
674                                              mGyroBatchesPerSec,
675                                              mAccelSamplesPerBatchHigh,
676                                              mAccelBatchesPerSecHigh,
677                                              mGyroSamplesPerBatchHigh,
678                                              mGyroBatchesPerSecHigh,
679                                              mAlgorithmConfig);
680     }
locallogLocEngSensorPerfControlConfig681     inline void locallog() const {
682         LOC_LOGV("Sensor Perf Control Config (performanceControlMode)(%u) "
683                  "accel(#smp,#batches) (%u,%u) "
684                  "gyro(#smp,#batches) (%u,%u), "
685                  "accel_high(#smp,#batches) (%u,%u) "
686                  "gyro_high(#smp,#batches) (%u,%u), "
687                  "algorithmConfig(%u)\n",
688                  mControlMode,
689                  mAccelSamplesPerBatch, mAccelBatchesPerSec,
690                  mGyroSamplesPerBatch, mGyroBatchesPerSec,
691                  mAccelSamplesPerBatchHigh, mAccelBatchesPerSecHigh,
692                  mGyroSamplesPerBatchHigh, mGyroBatchesPerSecHigh,
693                  mAlgorithmConfig);
694     }
logLocEngSensorPerfControlConfig695     inline virtual void log() const {
696         locallog();
697     }
698 };
699 
700 //        case LOC_ENG_MSG_EXT_POWER_CONFIG:
701 struct LocEngExtPowerConfig : public LocMsg {
702     LocEngAdapter* mAdapter;
703     const int mIsBatteryCharging;
LocEngExtPowerConfigLocEngExtPowerConfig704     inline LocEngExtPowerConfig(LocEngAdapter* adapter,
705                                 int isBatteryCharging) :
706         LocMsg(), mAdapter(adapter),
707         mIsBatteryCharging(isBatteryCharging)
708     {
709         locallog();
710     }
procLocEngExtPowerConfig711     inline virtual void proc() const {
712         mAdapter->setExtPowerConfig(mIsBatteryCharging);
713     }
locallogLocEngExtPowerConfig714     inline void locallog() const {
715         LOC_LOGV("LocEngExtPowerConfig - isBatteryCharging: %d",
716                  mIsBatteryCharging);
717     }
logLocEngExtPowerConfig718     inline virtual void log() const {
719         locallog();
720     }
721 };
722 
723 //        case LOC_ENG_MSG_REPORT_POSITION:
LocEngReportPosition(LocAdapterBase * adapter,UlpLocation & loc,GpsLocationExtended & locExtended,void * locExt,enum loc_sess_status st,LocPosTechMask technology)724 LocEngReportPosition::LocEngReportPosition(LocAdapterBase* adapter,
725                                            UlpLocation &loc,
726                                            GpsLocationExtended &locExtended,
727                                            void* locExt,
728                                            enum loc_sess_status st,
729                                            LocPosTechMask technology) :
730     LocMsg(), mAdapter(adapter), mLocation(loc),
731     mLocationExtended(locExtended),
732     mLocationExt(((loc_eng_data_s_type*)
733                   ((LocEngAdapter*)
734                    (mAdapter))->getOwner())->location_ext_parser(locExt)),
735     mStatus(st), mTechMask(technology)
736 {
737     locallog();
738 }
proc() const739 void LocEngReportPosition::proc() const {
740     LocEngAdapter* adapter = (LocEngAdapter*)mAdapter;
741     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)adapter->getOwner();
742 
743     if (locEng->mute_session_state != LOC_MUTE_SESS_IN_SESSION) {
744         bool reported = false;
745         if (locEng->location_cb != NULL) {
746             if (LOC_SESS_FAILURE == mStatus) {
747                 // in case we want to handle the failure case
748                 locEng->location_cb(NULL, NULL);
749                 reported = true;
750             }
751             // what's in the else if is... (line by line)
752             // 1. this is a final fix; and
753             //   1.1 it is a Satellite fix; or
754             //   1.2 it is a sensor fix
755             // 2. (must be intermediate fix... implicit)
756             //   2.1 we accepte intermediate; and
757             //   2.2 it is NOT the case that
758             //   2.2.1 there is inaccuracy; and
759             //   2.2.2 we care about inaccuracy; and
760             //   2.2.3 the inaccuracy exceeds our tolerance
761             else if ((LOC_SESS_SUCCESS == mStatus &&
762                       ((LOC_POS_TECH_MASK_SATELLITE |
763                         LOC_POS_TECH_MASK_SENSORS   |
764                         LOC_POS_TECH_MASK_HYBRID) &
765                        mTechMask)) ||
766                      (LOC_SESS_INTERMEDIATE == locEng->intermediateFix &&
767                       !((mLocation.gpsLocation.flags &
768                          GPS_LOCATION_HAS_ACCURACY) &&
769                         (gps_conf.ACCURACY_THRES != 0) &&
770                         (mLocation.gpsLocation.accuracy >
771                          gps_conf.ACCURACY_THRES)))) {
772                 locEng->location_cb((UlpLocation*)&(mLocation),
773                                     (void*)mLocationExt);
774                 reported = true;
775             }
776         }
777 
778         // if we have reported this fix
779         if (reported &&
780             // and if this is a singleshot
781             GPS_POSITION_RECURRENCE_SINGLE ==
782             locEng->adapter->getPositionMode().recurrence) {
783             if (LOC_SESS_INTERMEDIATE == mStatus) {
784                 // modem could be still working for a final fix,
785                 // although we no longer need it.  So stopFix().
786                 locEng->adapter->stopFix();
787             }
788             // turn off the session flag.
789             locEng->adapter->setInSession(false);
790         }
791 
792         LOC_LOGV("LocEngReportPosition::proc() - generateNmea: %d, position source: %d, "
793                  "engine_status: %d, isInSession: %d",
794                         locEng->generateNmea, mLocation.position_source,
795                         locEng->engine_status, locEng->adapter->isInSession());
796 
797         if (locEng->generateNmea &&
798             locEng->adapter->isInSession())
799         {
800             unsigned char generate_nmea = reported &&
801                                           (mStatus != LOC_SESS_FAILURE);
802             loc_eng_nmea_generate_pos(locEng, mLocation, mLocationExtended,
803                                       generate_nmea);
804         }
805 
806         // Free the allocated memory for rawData
807         UlpLocation* gp = (UlpLocation*)&(mLocation);
808         if (gp != NULL && gp->rawData != NULL)
809         {
810             delete (char*)gp->rawData;
811             gp->rawData = NULL;
812             gp->rawDataSize = 0;
813         }
814     }
815 }
locallog() const816 void LocEngReportPosition::locallog() const {
817     LOC_LOGV("LocEngReportPosition");
818 }
log() const819 void LocEngReportPosition::log() const {
820     locallog();
821 }
send() const822 void LocEngReportPosition::send() const {
823     mAdapter->sendMsg(this);
824 }
825 
826 
827 //        case LOC_ENG_MSG_REPORT_SV:
LocEngReportSv(LocAdapterBase * adapter,GnssSvStatus & sv,GpsLocationExtended & locExtended,void * svExt)828 LocEngReportSv::LocEngReportSv(LocAdapterBase* adapter,
829                                GnssSvStatus &sv,
830                                GpsLocationExtended &locExtended,
831                                void* svExt) :
832     LocMsg(), mAdapter(adapter), mSvStatus(sv),
833     mLocationExtended(locExtended),
834     mSvExt(((loc_eng_data_s_type*)
835             ((LocEngAdapter*)
836              (mAdapter))->getOwner())->sv_ext_parser(svExt))
837 {
838     locallog();
839 }
proc() const840 void LocEngReportSv::proc() const {
841     LocEngAdapter* adapter = (LocEngAdapter*)mAdapter;
842     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)adapter->getOwner();
843 
844     if (locEng->mute_session_state != LOC_MUTE_SESS_IN_SESSION)
845     {
846         if (locEng->gnss_sv_status_cb != NULL) {
847             LOC_LOGE("Calling gnss_sv_status_cb");
848             locEng->gnss_sv_status_cb((GnssSvStatus*)&(mSvStatus));
849         }
850 
851         if (locEng->generateNmea)
852         {
853             loc_eng_nmea_generate_sv(locEng, mSvStatus, mLocationExtended);
854         }
855     }
856 }
locallog() const857 void LocEngReportSv::locallog() const {
858     LOC_LOGV("%s:%d] LocEngReportSv",__func__, __LINE__);
859 }
log() const860 inline void LocEngReportSv::log() const {
861     locallog();
862 }
send() const863 void LocEngReportSv::send() const {
864     mAdapter->sendMsg(this);
865 }
866 
867 //        case LOC_ENG_MSG_REPORT_STATUS:
LocEngReportStatus(LocAdapterBase * adapter,GpsStatusValue engineStatus)868 LocEngReportStatus::LocEngReportStatus(LocAdapterBase* adapter,
869                                        GpsStatusValue engineStatus) :
870     LocMsg(),  mAdapter(adapter), mStatus(engineStatus)
871 {
872     locallog();
873 }
proc() const874 inline void LocEngReportStatus::proc() const
875 {
876     LocEngAdapter* adapter = (LocEngAdapter*)mAdapter;
877     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)adapter->getOwner();
878 
879     loc_eng_report_status(*locEng, mStatus);
880     update_aiding_data_for_deletion(*locEng);
881 }
locallog() const882 inline void LocEngReportStatus::locallog() const {
883     LOC_LOGV("LocEngReportStatus");
884 }
log() const885 inline void LocEngReportStatus::log() const {
886     locallog();
887 }
888 
889 //        case LOC_ENG_MSG_REPORT_NMEA:
LocEngReportNmea(void * locEng,const char * data,int len)890 LocEngReportNmea::LocEngReportNmea(void* locEng,
891                                    const char* data, int len) :
892     LocMsg(), mLocEng(locEng), mNmea(new char[len]), mLen(len)
893 {
894     memcpy((void*)mNmea, (void*)data, len);
895     locallog();
896 }
proc() const897 void LocEngReportNmea::proc() const {
898     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*) mLocEng;
899 
900     struct timeval tv;
901     gettimeofday(&tv, (struct timezone *) NULL);
902     int64_t now = tv.tv_sec * 1000LL + tv.tv_usec / 1000;
903 
904     if (locEng->nmea_cb != NULL)
905         locEng->nmea_cb(now, mNmea, mLen);
906 }
locallog() const907 inline void LocEngReportNmea::locallog() const {
908     LOC_LOGV("LocEngReportNmea");
909 }
log() const910 inline void LocEngReportNmea::log() const {
911     locallog();
912 }
913 
914 //        case LOC_ENG_MSG_REPORT_XTRA_SERVER:
LocEngReportXtraServer(void * locEng,const char * url1,const char * url2,const char * url3,const int maxlength)915 LocEngReportXtraServer::LocEngReportXtraServer(void* locEng,
916                                                const char *url1,
917                                                const char *url2,
918                                                const char *url3,
919                                                const int maxlength) :
920     LocMsg(), mLocEng(locEng), mMaxLen(maxlength),
921     mServers(new char[3*(mMaxLen+1)])
922 {
923     char * cptr = mServers;
924     memset(mServers, 0, 3*(mMaxLen+1));
925 
926     // Override modem URLs with uncommented gps.conf urls
927     if( gps_conf.XTRA_SERVER_1[0] != '\0' ) {
928         url1 = &gps_conf.XTRA_SERVER_1[0];
929     }
930     if( gps_conf.XTRA_SERVER_2[0] != '\0' ) {
931         url2 = &gps_conf.XTRA_SERVER_2[0];
932     }
933     if( gps_conf.XTRA_SERVER_3[0] != '\0' ) {
934         url3 = &gps_conf.XTRA_SERVER_3[0];
935     }
936     // copy non xtra1.gpsonextra.net URLs into the forwarding buffer.
937     if( NULL == strcasestr(url1, XTRA1_GPSONEXTRA) ) {
938         strlcpy(cptr, url1, mMaxLen + 1);
939         cptr += mMaxLen + 1;
940     }
941     if( NULL == strcasestr(url2, XTRA1_GPSONEXTRA) ) {
942         strlcpy(cptr, url2, mMaxLen + 1);
943         cptr += mMaxLen + 1;
944     }
945     if( NULL == strcasestr(url3, XTRA1_GPSONEXTRA) ) {
946         strlcpy(cptr, url3, mMaxLen + 1);
947     }
948     locallog();
949 }
950 
proc() const951 void LocEngReportXtraServer::proc() const {
952     loc_eng_xtra_data_s_type* locEngXtra =
953         &(((loc_eng_data_s_type*)mLocEng)->xtra_module_data);
954 
955     if (locEngXtra->report_xtra_server_cb != NULL) {
956         CALLBACK_LOG_CALLFLOW("report_xtra_server_cb", %s, mServers);
957         locEngXtra->report_xtra_server_cb(mServers,
958                                           &(mServers[mMaxLen+1]),
959                                           &(mServers[(mMaxLen+1)<<1]));
960     } else {
961         LOC_LOGE("Callback function for request xtra is NULL");
962     }
963 }
locallog() const964 inline void LocEngReportXtraServer::locallog() const {
965     LOC_LOGV("LocEngReportXtraServers: server1: %s\n  server2: %s\n"
966              "  server3: %s\n",
967              mServers, &mServers[mMaxLen+1], &mServers[(mMaxLen+1)<<1]);
968 }
log() const969 inline void LocEngReportXtraServer::log() const {
970     locallog();
971 }
972 
973 //        case LOC_ENG_MSG_REQUEST_BIT:
974 //        case LOC_ENG_MSG_RELEASE_BIT:
LocEngReqRelBIT(void * locEng,AGpsExtType type,int ipv4,char * ipv6,bool isReq)975 LocEngReqRelBIT::LocEngReqRelBIT(void* locEng, AGpsExtType type,
976                                  int ipv4, char* ipv6, bool isReq) :
977     LocMsg(), mLocEng(locEng), mType(type), mIPv4Addr(ipv4),
978     mIPv6Addr(ipv6 ? new char[16] : NULL), mIsReq(isReq) {
979     if (NULL != ipv6)
980         memcpy(mIPv6Addr, ipv6, 16);
981     locallog();
982 }
~LocEngReqRelBIT()983 inline LocEngReqRelBIT::~LocEngReqRelBIT() {
984     if (mIPv6Addr) {
985         delete[] mIPv6Addr;
986     }
987 }
proc() const988 void LocEngReqRelBIT::proc() const {
989     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
990     BITSubscriber s(getAgpsStateMachine(*locEng, mType),
991                     mIPv4Addr, mIPv6Addr);
992     AgpsStateMachine* sm = (AgpsStateMachine*)s.mStateMachine;
993 
994     if (mIsReq) {
995         sm->subscribeRsrc((Subscriber*)&s);
996     } else {
997         sm->unsubscribeRsrc((Subscriber*)&s);
998     }
999 }
locallog() const1000 inline void LocEngReqRelBIT::locallog() const {
1001     LOC_LOGV("LocEngRequestBIT - ipv4: %d.%d.%d.%d, ipv6: %s",
1002              (unsigned char)mIPv4Addr,
1003              (unsigned char)(mIPv4Addr>>8),
1004              (unsigned char)(mIPv4Addr>>16),
1005              (unsigned char)(mIPv4Addr>>24),
1006              NULL != mIPv6Addr ? mIPv6Addr : "");
1007 }
log() const1008 inline void LocEngReqRelBIT::log() const {
1009     locallog();
1010 }
send() const1011 void LocEngReqRelBIT::send() const {
1012     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
1013     locEng->adapter->sendMsg(this);
1014 }
1015 
1016 //        case LOC_ENG_MSG_RELEASE_BIT:
1017 struct LocEngReleaseBIT : public LocMsg {
1018     const BITSubscriber mSubscriber;
LocEngReleaseBITLocEngReleaseBIT1019     inline LocEngReleaseBIT(const AgpsStateMachine* stateMachine,
1020                             unsigned int ipv4, char* ipv6) :
1021         LocMsg(),
1022         mSubscriber(stateMachine, ipv4, ipv6)
1023     {
1024         locallog();
1025     }
procLocEngReleaseBIT1026     inline virtual void proc() const
1027     {
1028         AgpsStateMachine* sm = (AgpsStateMachine*)mSubscriber.mStateMachine;
1029         sm->unsubscribeRsrc((Subscriber*)&mSubscriber);
1030     }
locallogLocEngReleaseBIT1031     inline void locallog() const {
1032         LOC_LOGV("LocEngReleaseBIT - ipv4: %d.%d.%d.%d, ipv6: %s",
1033                  (unsigned char)(mSubscriber.ID>>24),
1034                  (unsigned char)(mSubscriber.ID>>16),
1035                  (unsigned char)(mSubscriber.ID>>8),
1036                  (unsigned char)mSubscriber.ID,
1037                  NULL != mSubscriber.mIPv6Addr ? mSubscriber.mIPv6Addr : "");
1038     }
logLocEngReleaseBIT1039     virtual void log() const {
1040         locallog();
1041     }
1042 };
1043 
1044 //        LocEngSuplEsOpened
LocEngSuplEsOpened(void * locEng)1045 LocEngSuplEsOpened::LocEngSuplEsOpened(void* locEng) :
1046     LocMsg(), mLocEng(locEng) {
1047     locallog();
1048 }
proc() const1049 void LocEngSuplEsOpened::proc() const {
1050     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
1051     if (locEng->ds_nif) {
1052         AgpsStateMachine* sm = locEng->ds_nif;
1053         sm->onRsrcEvent(RSRC_GRANTED);
1054     }
1055 }
locallog() const1056 void LocEngSuplEsOpened::locallog() const {
1057     LOC_LOGV("LocEngSuplEsOpened");
1058 }
log() const1059 void LocEngSuplEsOpened::log() const {
1060     locallog();
1061 }
1062 
1063 //        LocEngSuplEsClosed
LocEngSuplEsClosed(void * locEng)1064 LocEngSuplEsClosed::LocEngSuplEsClosed(void* locEng) :
1065     LocMsg(), mLocEng(locEng) {
1066     locallog();
1067 }
proc() const1068 void LocEngSuplEsClosed::proc() const {
1069     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
1070     if (locEng->ds_nif) {
1071         AgpsStateMachine* sm = locEng->ds_nif;
1072         sm->onRsrcEvent(RSRC_RELEASED);
1073     }
1074 }
locallog() const1075 void LocEngSuplEsClosed::locallog() const {
1076     LOC_LOGV("LocEngSuplEsClosed");
1077 }
log() const1078 void LocEngSuplEsClosed::log() const {
1079     locallog();
1080 }
1081 
1082 
1083 //        case LOC_ENG_MSG_REQUEST_SUPL_ES:
LocEngRequestSuplEs(void * locEng,int id)1084 LocEngRequestSuplEs::LocEngRequestSuplEs(void* locEng, int id) :
1085     LocMsg(), mLocEng(locEng), mID(id) {
1086     locallog();
1087 }
proc() const1088 void LocEngRequestSuplEs::proc() const {
1089     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
1090     if (locEng->ds_nif) {
1091         AgpsStateMachine* sm = locEng->ds_nif;
1092         DSSubscriber s(sm, mID);
1093         sm->subscribeRsrc((Subscriber*)&s);
1094     }
1095     else if (locEng->agnss_nif) {
1096         AgpsStateMachine *sm = locEng->agnss_nif;
1097         ATLSubscriber s(mID,
1098                         sm,
1099                         locEng->adapter,
1100                         false);
1101         sm->subscribeRsrc((Subscriber*)&s);
1102         LOC_LOGD("%s:%d]: Using regular ATL for SUPL ES", __func__, __LINE__);
1103     }
1104     else {
1105         locEng->adapter->atlOpenStatus(mID, 0, NULL, -1, -1);
1106     }
1107 }
locallog() const1108 inline void LocEngRequestSuplEs::locallog() const {
1109     LOC_LOGV("LocEngRequestSuplEs");
1110 }
log() const1111 inline void LocEngRequestSuplEs::log() const {
1112     locallog();
1113 }
1114 
1115 //        case LOC_ENG_MSG_REQUEST_ATL:
LocEngRequestATL(void * locEng,int id,AGpsExtType agps_type)1116 LocEngRequestATL::LocEngRequestATL(void* locEng, int id,
1117                                    AGpsExtType agps_type) :
1118     LocMsg(), mLocEng(locEng), mID(id), mType(agps_type) {
1119     locallog();
1120 }
proc() const1121 void LocEngRequestATL::proc() const {
1122     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
1123     AgpsStateMachine* sm = (AgpsStateMachine*)
1124                            getAgpsStateMachine(*locEng, mType);
1125     if (sm) {
1126         ATLSubscriber s(mID,
1127                         sm,
1128                         locEng->adapter,
1129                         AGPS_TYPE_INVALID == mType);
1130         sm->subscribeRsrc((Subscriber*)&s);
1131     } else {
1132         locEng->adapter->atlOpenStatus(mID, 0, NULL, -1, mType);
1133     }
1134 }
locallog() const1135 inline void LocEngRequestATL::locallog() const {
1136     LOC_LOGV("LocEngRequestATL");
1137 }
log() const1138 inline void LocEngRequestATL::log() const {
1139     locallog();
1140 }
1141 
1142 //        case LOC_ENG_MSG_RELEASE_ATL:
LocEngReleaseATL(void * locEng,int id)1143 LocEngReleaseATL::LocEngReleaseATL(void* locEng, int id) :
1144     LocMsg(), mLocEng(locEng), mID(id) {
1145     locallog();
1146 }
proc() const1147 void LocEngReleaseATL::proc() const {
1148     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
1149 
1150    if (locEng->agnss_nif) {
1151         ATLSubscriber s1(mID, locEng->agnss_nif, locEng->adapter, false);
1152         if (locEng->agnss_nif->unsubscribeRsrc((Subscriber*)&s1)) {
1153             LOC_LOGD("%s:%d]: Unsubscribed from agnss_nif",
1154                      __func__, __LINE__);
1155             return;
1156         }
1157     }
1158 
1159     if (locEng->internet_nif) {
1160         ATLSubscriber s2(mID, locEng->internet_nif, locEng->adapter, false);
1161         if (locEng->internet_nif->unsubscribeRsrc((Subscriber*)&s2)) {
1162             LOC_LOGD("%s:%d]: Unsubscribed from internet_nif",
1163                      __func__, __LINE__);
1164             return;
1165         }
1166     }
1167 
1168     if (locEng->ds_nif) {
1169         DSSubscriber s3(locEng->ds_nif, mID);
1170         if (locEng->ds_nif->unsubscribeRsrc((Subscriber*)&s3)) {
1171             LOC_LOGD("%s:%d]: Unsubscribed from ds_nif",
1172                      __func__, __LINE__);
1173             return;
1174         }
1175     }
1176 
1177     LOC_LOGW("%s:%d]: Could not release ATL. "
1178              "No subscribers found\n",
1179              __func__, __LINE__);
1180     locEng->adapter->atlCloseStatus(mID, 0);
1181 }
locallog() const1182 inline void LocEngReleaseATL::locallog() const {
1183     LOC_LOGV("LocEngReleaseATL");
1184 }
log() const1185 inline void LocEngReleaseATL::log() const {
1186     locallog();
1187 }
1188 
1189 //        case LOC_ENG_MSG_REQUEST_WIFI:
1190 //        case LOC_ENG_MSG_RELEASE_WIFI:
LocEngReqRelWifi(void * locEng,AGpsExtType type,loc_if_req_sender_id_e_type sender_id,char * s,char * p,bool isReq)1191 LocEngReqRelWifi::LocEngReqRelWifi(void* locEng, AGpsExtType type,
1192                                    loc_if_req_sender_id_e_type sender_id,
1193                                    char* s, char* p, bool isReq) :
1194     LocMsg(), mLocEng(locEng), mType(type), mSenderId(sender_id),
1195     mSSID(NULL == s ? NULL : new char[SSID_BUF_SIZE]),
1196     mPassword(NULL == p ? NULL : new char[SSID_BUF_SIZE]),
1197     mIsReq(isReq) {
1198     if (NULL != s)
1199         strlcpy(mSSID, s, SSID_BUF_SIZE);
1200     if (NULL != p)
1201         strlcpy(mPassword, p, SSID_BUF_SIZE);
1202     locallog();
1203 }
~LocEngReqRelWifi()1204 LocEngReqRelWifi::~LocEngReqRelWifi() {
1205     if (NULL != mSSID) {
1206         delete[] mSSID;
1207     }
1208     if (NULL != mPassword) {
1209         delete[] mPassword;
1210     }
1211 }
proc() const1212 void LocEngReqRelWifi::proc() const {
1213     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
1214     if (locEng->wifi_nif) {
1215         WIFISubscriber s(locEng->wifi_nif, mSSID, mPassword, mSenderId);
1216         if (mIsReq) {
1217             locEng->wifi_nif->subscribeRsrc((Subscriber*)&s);
1218         } else {
1219             locEng->wifi_nif->unsubscribeRsrc((Subscriber*)&s);
1220         }
1221     } else {
1222         locEng->adapter->atlOpenStatus(mSenderId, 0, NULL, -1, mType);
1223     }
1224 }
locallog() const1225 inline void LocEngReqRelWifi::locallog() const {
1226     LOC_LOGV("%s - senderId: %d, ssid: %s, password: %s",
1227              mIsReq ? "LocEngRequestWifi" : "LocEngReleaseWifi",
1228              mSenderId,
1229              NULL != mSSID ? mSSID : "",
1230              NULL != mPassword ? mPassword : "");
1231 }
log() const1232 inline void LocEngReqRelWifi::log() const {
1233     locallog();
1234 }
send() const1235 void LocEngReqRelWifi::send() const {
1236     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
1237     locEng->adapter->sendMsg(this);
1238 }
1239 
1240 //        case LOC_ENG_MSG_REQUEST_XTRA_DATA:
LocEngRequestXtra(void * locEng)1241 LocEngRequestXtra::LocEngRequestXtra(void* locEng) :
1242     mLocEng(locEng) {
1243     locallog();
1244 }
proc() const1245 void LocEngRequestXtra::proc() const
1246 {
1247     loc_eng_xtra_data_s_type* locEngXtra =
1248         &(((loc_eng_data_s_type*)mLocEng)->xtra_module_data);
1249 
1250     if (locEngXtra->download_request_cb != NULL) {
1251         CALLBACK_LOG_CALLFLOW("download_request_cb", %p, mLocEng);
1252         locEngXtra->download_request_cb();
1253     } else {
1254         LOC_LOGE("Callback function for request xtra is NULL");
1255     }
1256 }
locallog() const1257 inline void LocEngRequestXtra::locallog() const {
1258     LOC_LOGV("LocEngReqXtra");
1259 }
log() const1260 inline void LocEngRequestXtra::log() const {
1261     locallog();
1262 }
1263 
1264 //        case LOC_ENG_MSG_REQUEST_TIME:
LocEngRequestTime(void * locEng)1265 LocEngRequestTime::LocEngRequestTime(void* locEng) :
1266     LocMsg(), mLocEng(locEng)
1267 {
1268     locallog();
1269 }
proc() const1270 void LocEngRequestTime::proc() const {
1271     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
1272     if (gps_conf.CAPABILITIES & GPS_CAPABILITY_ON_DEMAND_TIME) {
1273         if (locEng->request_utc_time_cb != NULL) {
1274             locEng->request_utc_time_cb();
1275         } else {
1276             LOC_LOGE("Callback function for request time is NULL");
1277         }
1278     }
1279 }
locallog() const1280 inline void LocEngRequestTime::locallog() const {
1281     LOC_LOGV("LocEngReqTime");
1282 }
log() const1283 inline void LocEngRequestTime::log() const {
1284     locallog();
1285 }
1286 
1287 //        case LOC_ENG_MSG_DELETE_AIDING_DATA:
1288 struct LocEngDelAidData : public LocMsg {
1289     loc_eng_data_s_type* mLocEng;
1290     const GpsAidingData mType;
LocEngDelAidDataLocEngDelAidData1291     inline LocEngDelAidData(loc_eng_data_s_type* locEng,
1292                             GpsAidingData f) :
1293         LocMsg(), mLocEng(locEng), mType(f)
1294     {
1295         locallog();
1296     }
procLocEngDelAidData1297     inline virtual void proc() const {
1298         mLocEng->aiding_data_for_deletion = mType;
1299         update_aiding_data_for_deletion(*mLocEng);
1300     }
locallogLocEngDelAidData1301     inline void locallog() const {
1302         LOC_LOGV("aiding data msak %d", mType);
1303     }
logLocEngDelAidData1304     virtual void log() const {
1305         locallog();
1306     }
1307 };
1308 
1309 //        case LOC_ENG_MSG_ENABLE_DATA:
1310 struct LocEngEnableData : public LocMsg {
1311     LocEngAdapter* mAdapter;
1312     const int mEnable;
1313     char* mAPN;
1314     const int mLen;
LocEngEnableDataLocEngEnableData1315     inline LocEngEnableData(LocEngAdapter* adapter,
1316                             const char* name, int len, int enable) :
1317         LocMsg(), mAdapter(adapter),
1318         mEnable(enable), mAPN(NULL), mLen(len)
1319     {
1320         if (NULL != name) {
1321             mAPN = new char[len+1];
1322             memcpy((void*)mAPN, (void*)name, len);
1323             mAPN[len] = 0;
1324         }
1325         locallog();
1326     }
~LocEngEnableDataLocEngEnableData1327     inline ~LocEngEnableData() {
1328         if (NULL != mAPN) {
1329             delete[] mAPN;
1330         }
1331     }
procLocEngEnableData1332     inline virtual void proc() const {
1333         mAdapter->enableData(mEnable);
1334         if (NULL != mAPN) {
1335             mAdapter->setAPN(mAPN, mLen);
1336         }
1337     }
locallogLocEngEnableData1338     inline void locallog() const {
1339         LOC_LOGV("apn: %s\n  enable: %d",
1340                  (NULL == mAPN) ? "NULL" : mAPN, mEnable);
1341     }
logLocEngEnableData1342     inline virtual void log() const {
1343         locallog();
1344     }
1345 };
1346 
1347 //        case LOC_ENG_MSG_INJECT_XTRA_DATA:
1348 // loc_eng_xtra.cpp
1349 
1350 //        case LOC_ENG_MSG_SET_CAPABILITIES:
1351 struct LocEngSetCapabilities : public LocMsg {
1352     loc_eng_data_s_type* mLocEng;
LocEngSetCapabilitiesLocEngSetCapabilities1353     inline LocEngSetCapabilities(loc_eng_data_s_type* locEng) :
1354         LocMsg(), mLocEng(locEng)
1355     {
1356         locallog();
1357     }
procLocEngSetCapabilities1358     inline virtual void proc() const {
1359         if (NULL != mLocEng->set_capabilities_cb) {
1360             LOC_LOGV("calling set_capabilities_cb 0x%x",
1361                      gps_conf.CAPABILITIES);
1362             mLocEng->set_capabilities_cb(gps_conf.CAPABILITIES);
1363         } else {
1364             LOC_LOGV("set_capabilities_cb is NULL.\n");
1365         }
1366     }
locallogLocEngSetCapabilities1367     inline void locallog() const
1368     {
1369         LOC_LOGV("LocEngSetCapabilities");
1370     }
logLocEngSetCapabilities1371     inline virtual void log() const
1372     {
1373         locallog();
1374     }
1375 };
1376 
1377 struct LocEngSetSystemInfo : public LocMsg {
1378     loc_eng_data_s_type* mLocEng;
LocEngSetSystemInfoLocEngSetSystemInfo1379     inline LocEngSetSystemInfo(loc_eng_data_s_type* locEng) :
1380         LocMsg(), mLocEng(locEng)
1381     {
1382         locallog();
1383     }
procLocEngSetSystemInfo1384     inline virtual void proc() const {
1385         if (NULL != mLocEng->set_system_info_cb) {
1386             LOC_LOGV("calling set_system_info_cb 0x%x",
1387                 mLocEng->adapter->mGnssInfo.year_of_hw);
1388             mLocEng->set_system_info_cb(&(mLocEng->adapter->mGnssInfo));
1389         }
1390         else {
1391             LOC_LOGV("set_system_info_cb is NULL.\n");
1392         }
1393     }
locallogLocEngSetSystemInfo1394     inline void locallog() const
1395     {
1396         LOC_LOGV("LocEngSetSystemInfo");
1397     }
logLocEngSetSystemInfo1398     inline virtual void log() const
1399     {
1400         locallog();
1401     }
1402 };
1403 
1404 //        case LOC_ENG_MSG_LOC_INIT:
1405 struct LocEngInit : public LocMsg {
1406     loc_eng_data_s_type* mLocEng;
LocEngInitLocEngInit1407     inline LocEngInit(loc_eng_data_s_type* locEng) :
1408         LocMsg(), mLocEng(locEng)
1409     {
1410         locallog();
1411     }
procLocEngInit1412     inline virtual void proc() const {
1413         loc_eng_reinit(*mLocEng);
1414         // set the capabilities
1415         mLocEng->adapter->sendMsg(new LocEngSetCapabilities(mLocEng));
1416         mLocEng->adapter->sendMsg(new LocEngSetSystemInfo(mLocEng));
1417     }
locallogLocEngInit1418     inline void locallog() const
1419     {
1420         LOC_LOGV("LocEngInit");
1421     }
logLocEngInit1422     inline virtual void log() const
1423     {
1424         locallog();
1425     }
1426 };
1427 
1428 //        case LOC_ENG_MSG_REQUEST_XTRA_SERVER:
1429 // loc_eng_xtra.cpp
1430 
1431 //        case LOC_ENG_MSG_ATL_OPEN_SUCCESS:
1432 struct LocEngAtlOpenSuccess : public LocMsg {
1433     AgpsStateMachine* mStateMachine;
1434     const int mLen;
1435     char* mAPN;
1436     const AGpsBearerType mBearerType;
LocEngAtlOpenSuccessLocEngAtlOpenSuccess1437     inline LocEngAtlOpenSuccess(AgpsStateMachine* statemachine,
1438                                 const char* name,
1439                                 int len,
1440                                 AGpsBearerType btype) :
1441         LocMsg(),
1442         mStateMachine(statemachine), mLen(len),
1443         mAPN(new char[len+1]), mBearerType(btype)
1444     {
1445         memcpy((void*)mAPN, (void*)name, len);
1446         mAPN[len] = 0;
1447         locallog();
1448     }
~LocEngAtlOpenSuccessLocEngAtlOpenSuccess1449     inline ~LocEngAtlOpenSuccess()
1450     {
1451         delete[] mAPN;
1452     }
procLocEngAtlOpenSuccess1453     inline virtual void proc() const {
1454         mStateMachine->setBearer(mBearerType);
1455         mStateMachine->setAPN(mAPN, mLen);
1456         mStateMachine->onRsrcEvent(RSRC_GRANTED);
1457     }
locallogLocEngAtlOpenSuccess1458     inline void locallog() const {
1459         LOC_LOGV("LocEngAtlOpenSuccess agps type: %s\n  apn: %s\n"
1460                  "  bearer type: %s",
1461                  loc_get_agps_type_name(mStateMachine->getType()),
1462                  mAPN,
1463                  loc_get_agps_bear_name(mBearerType));
1464     }
logLocEngAtlOpenSuccess1465     inline virtual void log() const {
1466         locallog();
1467     }
1468 };
1469 
1470 //        case LOC_ENG_MSG_ATL_CLOSED:
1471 struct LocEngAtlClosed : public LocMsg {
1472     AgpsStateMachine* mStateMachine;
LocEngAtlClosedLocEngAtlClosed1473     inline LocEngAtlClosed(AgpsStateMachine* statemachine) :
1474         LocMsg(), mStateMachine(statemachine) {
1475         locallog();
1476     }
procLocEngAtlClosed1477     inline virtual void proc() const {
1478         mStateMachine->onRsrcEvent(RSRC_RELEASED);
1479     }
locallogLocEngAtlClosed1480     inline void locallog() const {
1481         LOC_LOGV("LocEngAtlClosed");
1482     }
logLocEngAtlClosed1483     inline virtual void log() const {
1484         locallog();
1485     }
1486 };
1487 
1488 //        case LOC_ENG_MSG_ATL_OPEN_FAILED:
1489 struct LocEngAtlOpenFailed : public LocMsg {
1490     AgpsStateMachine* mStateMachine;
LocEngAtlOpenFailedLocEngAtlOpenFailed1491     inline LocEngAtlOpenFailed(AgpsStateMachine* statemachine) :
1492         LocMsg(), mStateMachine(statemachine) {
1493         locallog();
1494     }
procLocEngAtlOpenFailed1495     inline virtual void proc() const {
1496         mStateMachine->onRsrcEvent(RSRC_DENIED);
1497     }
locallogLocEngAtlOpenFailed1498     inline void locallog() const {
1499         LOC_LOGV("LocEngAtlOpenFailed");
1500     }
logLocEngAtlOpenFailed1501     inline virtual void log() const {
1502         locallog();
1503     }
1504 };
1505 
1506 //        case LOC_ENG_MSG_ENGINE_DOWN:
LocEngDown(void * locEng)1507 LocEngDown::LocEngDown(void* locEng) :
1508     LocMsg(), mLocEng(locEng) {
1509     locallog();
1510 }
proc() const1511 inline void LocEngDown::proc() const {
1512     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
1513     loc_eng_handle_engine_down(*locEng);
1514 }
locallog() const1515 inline void LocEngDown::locallog() const {
1516     LOC_LOGV("LocEngDown");
1517 }
log() const1518 inline void LocEngDown::log() const {
1519     locallog();
1520 }
1521 
1522 //        case LOC_ENG_MSG_ENGINE_UP:
LocEngUp(void * locEng)1523 LocEngUp::LocEngUp(void* locEng) :
1524     LocMsg(), mLocEng(locEng) {
1525     locallog();
1526 }
proc() const1527 inline void LocEngUp::proc() const {
1528     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
1529     loc_eng_handle_engine_up(*locEng);
1530 }
locallog() const1531 inline void LocEngUp::locallog() const {
1532     LOC_LOGV("LocEngUp");
1533 }
log() const1534 inline void LocEngUp::log() const {
1535     locallog();
1536 }
1537 
1538 struct LocEngDataClientInit : public LocMsg {
1539     loc_eng_data_s_type* mLocEng;
LocEngDataClientInitLocEngDataClientInit1540     inline LocEngDataClientInit(loc_eng_data_s_type* locEng) :
1541         LocMsg(), mLocEng(locEng) {
1542         locallog();
1543     }
procLocEngDataClientInit1544     virtual void proc() const {
1545         loc_eng_data_s_type *locEng = (loc_eng_data_s_type *)mLocEng;
1546         if(!locEng->adapter->initDataServiceClient()) {
1547             locEng->ds_nif = new DSStateMachine(servicerTypeExt,
1548                                                (void *)dataCallCb,
1549                                                locEng->adapter);
1550         }
1551     }
locallogLocEngDataClientInit1552     void locallog() const {
1553         LOC_LOGV("LocEngDataClientInit\n");
1554     }
logLocEngDataClientInit1555     virtual void log() const {
1556         locallog();
1557     }
1558 };
1559 
1560 struct LocEngInstallAGpsCert : public LocMsg {
1561     LocEngAdapter* mpAdapter;
1562     const size_t mNumberOfCerts;
1563     const uint32_t mSlotBitMask;
1564     DerEncodedCertificate* mpData;
LocEngInstallAGpsCertLocEngInstallAGpsCert1565     inline LocEngInstallAGpsCert(LocEngAdapter* adapter,
1566                               const DerEncodedCertificate* pData,
1567                               size_t numberOfCerts,
1568                               uint32_t slotBitMask) :
1569         LocMsg(), mpAdapter(adapter),
1570         mNumberOfCerts(numberOfCerts), mSlotBitMask(slotBitMask),
1571         mpData(new DerEncodedCertificate[mNumberOfCerts])
1572     {
1573         for (int i=0; i < mNumberOfCerts; i++) {
1574             mpData[i].data = new u_char[pData[i].length];
1575             if (mpData[i].data) {
1576                 memcpy(mpData[i].data, (void*)pData[i].data, pData[i].length);
1577                 mpData[i].length = pData[i].length;
1578             } else {
1579                 LOC_LOGE("malloc failed for cert#%d", i);
1580                 break;
1581             }
1582         }
1583         locallog();
1584     }
~LocEngInstallAGpsCertLocEngInstallAGpsCert1585     inline ~LocEngInstallAGpsCert()
1586     {
1587         for (int i=0; i < mNumberOfCerts; i++) {
1588             if (mpData[i].data) {
1589                 delete[] mpData[i].data;
1590             }
1591         }
1592         delete[] mpData;
1593     }
procLocEngInstallAGpsCert1594     inline virtual void proc() const {
1595         mpAdapter->installAGpsCert(mpData, mNumberOfCerts, mSlotBitMask);
1596     }
locallogLocEngInstallAGpsCert1597     inline void locallog() const {
1598         LOC_LOGV("LocEngInstallAGpsCert - certs=%u mask=%u",
1599                  mNumberOfCerts, mSlotBitMask);
1600     }
logLocEngInstallAGpsCert1601     inline virtual void log() const {
1602         locallog();
1603     }
1604 };
1605 
1606 struct LocEngUpdateRegistrationMask : public LocMsg {
1607     loc_eng_data_s_type* mLocEng;
1608     LOC_API_ADAPTER_EVENT_MASK_T mMask;
1609     loc_registration_mask_status mIsEnabled;
LocEngUpdateRegistrationMaskLocEngUpdateRegistrationMask1610     inline LocEngUpdateRegistrationMask(loc_eng_data_s_type* locEng,
1611                                         LOC_API_ADAPTER_EVENT_MASK_T mask,
1612                                         loc_registration_mask_status isEnabled) :
1613         LocMsg(), mLocEng(locEng), mMask(mask), mIsEnabled(isEnabled) {
1614         locallog();
1615     }
procLocEngUpdateRegistrationMask1616     inline virtual void proc() const {
1617         loc_eng_data_s_type *locEng = (loc_eng_data_s_type *)mLocEng;
1618         locEng->adapter->updateRegistrationMask(mMask,
1619                                                 mIsEnabled);
1620     }
locallogLocEngUpdateRegistrationMask1621     void locallog() const {
1622         LOC_LOGV("LocEngUpdateRegistrationMask\n");
1623     }
logLocEngUpdateRegistrationMask1624     virtual void log() const {
1625         locallog();
1626     }
1627 };
1628 
1629 struct LocEngGnssConstellationConfig : public LocMsg {
1630     LocEngAdapter* mAdapter;
LocEngGnssConstellationConfigLocEngGnssConstellationConfig1631     inline LocEngGnssConstellationConfig(LocEngAdapter* adapter) :
1632         LocMsg(), mAdapter(adapter) {
1633         locallog();
1634     }
procLocEngGnssConstellationConfig1635     inline virtual void proc() const {
1636         mAdapter->mGnssInfo.size = sizeof(GnssSystemInfo);
1637         if (mAdapter->gnssConstellationConfig()) {
1638             LOC_LOGV("Modem supports GNSS measurements\n");
1639             gps_conf.CAPABILITIES |= GPS_CAPABILITY_MEASUREMENTS;
1640             mAdapter->mGnssInfo.year_of_hw = 2016;
1641         } else {
1642             mAdapter->mGnssInfo.year_of_hw = 2015;
1643             LOC_LOGV("Modem does not support GNSS measurements\n");
1644         }
1645     }
locallogLocEngGnssConstellationConfig1646     void locallog() const {
1647         LOC_LOGV("LocEngGnssConstellationConfig\n");
1648     }
logLocEngGnssConstellationConfig1649     virtual void log() const {
1650         locallog();
1651     }
1652 };
1653 
1654 //        case LOC_ENG_MSG_REPORT_GNSS_MEASUREMENT:
LocEngReportGnssMeasurement(void * locEng,GnssData & gnssData)1655 LocEngReportGnssMeasurement::LocEngReportGnssMeasurement(void* locEng,
1656                                                        GnssData &gnssData) :
1657     LocMsg(), mLocEng(locEng), mGnssData(gnssData)
1658 {
1659     locallog();
1660 }
proc() const1661 void LocEngReportGnssMeasurement::proc() const {
1662     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*) mLocEng;
1663     if (locEng->mute_session_state != LOC_MUTE_SESS_IN_SESSION)
1664     {
1665         if (locEng->gnss_measurement_cb != NULL) {
1666             LOC_LOGV("Calling gnss_measurement_cb");
1667             locEng->gnss_measurement_cb((GnssData*)&(mGnssData));
1668         }
1669     }
1670 }
1671 
locallog() const1672 void LocEngReportGnssMeasurement::locallog() const {
1673     IF_LOC_LOGV {
1674         LOC_LOGV("%s:%d]: Received in GPS HAL."
1675                  "GNSS Measurements count: %d \n",
1676                  __func__, __LINE__, mGnssData.measurement_count);
1677         for (int i =0; i< mGnssData.measurement_count && i < GNSS_MAX_SVS; i++) {
1678                 LOC_LOGV(" GNSS measurement data in GPS HAL: \n"
1679                          " GPS_HAL => Measurement ID | svid | time_offset_ns | state |"
1680                          " c_n0_dbhz | pseudorange_rate_mps |"
1681                          " pseudorange_rate_uncertainty_mps |"
1682                          " accumulated_delta_range_state | flags \n"
1683                          " GPS_HAL => %d | %d | %f | %d | %f | %f | %f | %d | %d \n",
1684                          i,
1685                          mGnssData.measurements[i].svid,
1686                          mGnssData.measurements[i].time_offset_ns,
1687                          mGnssData.measurements[i].state,
1688                          mGnssData.measurements[i].c_n0_dbhz,
1689                          mGnssData.measurements[i].pseudorange_rate_mps,
1690                          mGnssData.measurements[i].pseudorange_rate_uncertainty_mps,
1691                          mGnssData.measurements[i].accumulated_delta_range_state,
1692                          mGnssData.measurements[i].flags);
1693         }
1694         LOC_LOGV(" GPS_HAL => Clocks Info: \n"
1695                  " time_ns | full_bias_ns | bias_ns | bias_uncertainty_ns | "
1696                  " drift_nsps | drift_uncertainty_nsps | hw_clock_discontinuity_count | flags"
1697                  " GPS_HAL => Clocks Info: %lld | %lld | %g | %g | %g | %g | %d | 0x%04x\n",
1698             mGnssData.clock.time_ns,
1699             mGnssData.clock.full_bias_ns,
1700             mGnssData.clock.bias_ns,
1701             mGnssData.clock.bias_uncertainty_ns,
1702             mGnssData.clock.drift_nsps,
1703             mGnssData.clock.drift_uncertainty_nsps,
1704             mGnssData.clock.hw_clock_discontinuity_count,
1705             mGnssData.clock.flags);
1706     }
1707 }
1708 
log() const1709 inline void LocEngReportGnssMeasurement::log() const {
1710     locallog();
1711 }
1712 
1713 /*********************************************************************
1714  * Initialization checking macros
1715  *********************************************************************/
1716 #define STATE_CHECK(ctx, x, ret) \
1717     if (!(ctx))                  \
1718   {                              \
1719       /* Not intialized, abort */\
1720       LOC_LOGE("%s: log_eng state error: %s", __func__, x); \
1721       EXIT_LOG(%s, x);                                            \
1722       ret;                                                        \
1723   }
1724 #define INIT_CHECK(ctx, ret) STATE_CHECK(ctx, "instance not initialized", ret)
1725 
1726 /*===========================================================================
1727 FUNCTION    loc_eng_init
1728 
1729 DESCRIPTION
1730    Initialize the location engine, this include setting up global datas
1731    and registers location engien with loc api service.
1732 
1733 DEPENDENCIES
1734    None
1735 
1736 RETURN VALUE
1737    0: success
1738 
1739 SIDE EFFECTS
1740    N/A
1741 
1742 ===========================================================================*/
loc_eng_init(loc_eng_data_s_type & loc_eng_data,LocCallbacks * callbacks,LOC_API_ADAPTER_EVENT_MASK_T event,ContextBase * context)1743 int loc_eng_init(loc_eng_data_s_type &loc_eng_data, LocCallbacks* callbacks,
1744                  LOC_API_ADAPTER_EVENT_MASK_T event, ContextBase* context)
1745 
1746 {
1747     int ret_val = 0;
1748 
1749     ENTRY_LOG_CALLFLOW();
1750     if (NULL == callbacks || 0 == event) {
1751         LOC_LOGE("loc_eng_init: bad parameters cb %p eMask %d", callbacks, event);
1752         ret_val = -1;
1753         EXIT_LOG(%d, ret_val);
1754         return ret_val;
1755     }
1756 
1757     STATE_CHECK((NULL == loc_eng_data.adapter),
1758                 "instance already initialized", return 0);
1759 
1760     memset(&loc_eng_data, 0, sizeof (loc_eng_data));
1761 
1762     // Save callbacks
1763     loc_eng_data.location_cb  = callbacks->location_cb;
1764     loc_eng_data.sv_status_cb = callbacks->sv_status_cb;
1765     loc_eng_data.status_cb    = callbacks->status_cb;
1766     loc_eng_data.nmea_cb      = callbacks->nmea_cb;
1767     loc_eng_data.set_capabilities_cb = callbacks->set_capabilities_cb;
1768     loc_eng_data.acquire_wakelock_cb = callbacks->acquire_wakelock_cb;
1769     loc_eng_data.release_wakelock_cb = callbacks->release_wakelock_cb;
1770     loc_eng_data.request_utc_time_cb = callbacks->request_utc_time_cb;
1771     loc_eng_data.set_system_info_cb = callbacks->set_system_info_cb;
1772     loc_eng_data.gnss_sv_status_cb = callbacks->gnss_sv_status_cb;
1773     loc_eng_data.location_ext_parser = callbacks->location_ext_parser ?
1774         callbacks->location_ext_parser : noProc;
1775     loc_eng_data.sv_ext_parser = callbacks->sv_ext_parser ?
1776         callbacks->sv_ext_parser : noProc;
1777     loc_eng_data.intermediateFix = gps_conf.INTERMEDIATE_POS;
1778     // initial states taken care of by the memset above
1779     // loc_eng_data.engine_status -- GPS_STATUS_NONE;
1780     // loc_eng_data.fix_session_status -- GPS_STATUS_NONE;
1781     // loc_eng_data.mute_session_state -- LOC_MUTE_SESS_NONE;
1782 
1783     if ((event & LOC_API_ADAPTER_BIT_NMEA_1HZ_REPORT) && (gps_conf.NMEA_PROVIDER == NMEA_PROVIDER_AP))
1784     {
1785         event = event ^ LOC_API_ADAPTER_BIT_NMEA_1HZ_REPORT; // unregister for modem NMEA report
1786         loc_eng_data.generateNmea = true;
1787     }
1788     else
1789     {
1790         loc_eng_data.generateNmea = false;
1791     }
1792 
1793     loc_eng_data.adapter =
1794         new LocEngAdapter(event, &loc_eng_data, context,
1795                           (LocThread::tCreate)callbacks->create_thread_cb);
1796 
1797     loc_eng_data.adapter->mGnssInfo.size = sizeof(GnssSystemInfo);
1798     loc_eng_data.adapter->mGnssInfo.year_of_hw = 2015;
1799     LOC_LOGD("loc_eng_init created client, id = %p\n",
1800              loc_eng_data.adapter);
1801     loc_eng_data.adapter->sendMsg(new LocEngInit(&loc_eng_data));
1802 
1803     EXIT_LOG(%d, ret_val);
1804     return ret_val;
1805 }
1806 
loc_eng_reinit(loc_eng_data_s_type & loc_eng_data)1807 static int loc_eng_reinit(loc_eng_data_s_type &loc_eng_data)
1808 {
1809     ENTRY_LOG();
1810     int ret_val = LOC_API_ADAPTER_ERR_SUCCESS;
1811     LocEngAdapter* adapter = loc_eng_data.adapter;
1812 
1813     adapter->sendMsg(new LocEngGnssConstellationConfig(adapter));
1814     adapter->sendMsg(new LocEngSuplVer(adapter, gps_conf.SUPL_VER));
1815     adapter->sendMsg(new LocEngLppConfig(adapter, gps_conf.LPP_PROFILE));
1816     adapter->sendMsg(new LocEngSensorControlConfig(adapter, sap_conf.SENSOR_USAGE,
1817                                                    sap_conf.SENSOR_PROVIDER));
1818     adapter->sendMsg(new LocEngAGlonassProtocol(adapter, gps_conf.A_GLONASS_POS_PROTOCOL_SELECT));
1819 
1820     /* Make sure at least one of the sensor property is specified by the user in the gps.conf file. */
1821     if( sap_conf.GYRO_BIAS_RANDOM_WALK_VALID ||
1822         sap_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY_VALID ||
1823         sap_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY_VALID ||
1824         sap_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY_VALID ||
1825         sap_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY_VALID ) {
1826         adapter->sendMsg(new LocEngSensorProperties(adapter,
1827                                                     sap_conf.GYRO_BIAS_RANDOM_WALK_VALID,
1828                                                     sap_conf.GYRO_BIAS_RANDOM_WALK,
1829                                                     sap_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
1830                                                     sap_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY,
1831                                                     sap_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
1832                                                     sap_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY,
1833                                                     sap_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
1834                                                     sap_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY,
1835                                                     sap_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
1836                                                     sap_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY));
1837     }
1838 
1839     adapter->sendMsg(new LocEngSensorPerfControlConfig(adapter,
1840                                                        sap_conf.SENSOR_CONTROL_MODE,
1841                                                        sap_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH,
1842                                                        sap_conf.SENSOR_ACCEL_BATCHES_PER_SEC,
1843                                                        sap_conf.SENSOR_GYRO_SAMPLES_PER_BATCH,
1844                                                        sap_conf.SENSOR_GYRO_BATCHES_PER_SEC,
1845                                                        sap_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH_HIGH,
1846                                                        sap_conf.SENSOR_ACCEL_BATCHES_PER_SEC_HIGH,
1847                                                        sap_conf.SENSOR_GYRO_SAMPLES_PER_BATCH_HIGH,
1848                                                        sap_conf.SENSOR_GYRO_BATCHES_PER_SEC_HIGH,
1849                                                        sap_conf.SENSOR_ALGORITHM_CONFIG_MASK));
1850 
1851     adapter->sendMsg(new LocEngEnableData(adapter, NULL, 0, (agpsStatus ? 1:0)));
1852 
1853     loc_eng_xtra_version_check(loc_eng_data, gps_conf.XTRA_VERSION_CHECK);
1854 
1855     LOC_LOGD("loc_eng_reinit reinit() successful");
1856     EXIT_LOG(%d, ret_val);
1857     return ret_val;
1858 }
1859 
1860 /*===========================================================================
1861 FUNCTION    loc_eng_cleanup
1862 
1863 DESCRIPTION
1864    Cleans location engine. The location client handle will be released.
1865 
1866 DEPENDENCIES
1867    None
1868 
1869 RETURN VALUE
1870    None
1871 
1872 SIDE EFFECTS
1873    N/A
1874 
1875 ===========================================================================*/
loc_eng_cleanup(loc_eng_data_s_type & loc_eng_data)1876 void loc_eng_cleanup(loc_eng_data_s_type &loc_eng_data)
1877 {
1878     ENTRY_LOG_CALLFLOW();
1879     INIT_CHECK(loc_eng_data.adapter, return);
1880 
1881     // XTRA has no state, so we are fine with it.
1882 
1883     // we need to check and clear NI
1884 #if 0
1885     // we need to check and clear ATL
1886     if (NULL != loc_eng_data.agnss_nif) {
1887         delete loc_eng_data.agnss_nif;
1888         loc_eng_data.agnss_nif = NULL;
1889     }
1890     if (NULL != loc_eng_data.internet_nif) {
1891         delete loc_eng_data.internet_nif;
1892         loc_eng_data.internet_nif = NULL;
1893     }
1894 #endif
1895     if (loc_eng_data.adapter->isInSession())
1896     {
1897         LOC_LOGD("loc_eng_cleanup: fix not stopped. stop it now.");
1898         loc_eng_stop(loc_eng_data);
1899     }
1900 
1901 #if 0 // can't afford to actually clean up, for many reason.
1902 
1903     LOC_LOGD("loc_eng_init: client opened. close it now.");
1904     delete loc_eng_data.adapter;
1905     loc_eng_data.adapter = NULL;
1906 
1907     loc_eng_dmn_conn_loc_api_server_unblock();
1908     loc_eng_dmn_conn_loc_api_server_join();
1909 
1910 #endif
1911 
1912     EXIT_LOG(%s, VOID_RET);
1913 }
1914 
1915 
1916 /*===========================================================================
1917 FUNCTION    loc_eng_start
1918 
1919 DESCRIPTION
1920    Starts the tracking session
1921 
1922 DEPENDENCIES
1923    None
1924 
1925 RETURN VALUE
1926    0: success
1927 
1928 SIDE EFFECTS
1929    N/A
1930 
1931 ===========================================================================*/
loc_eng_start(loc_eng_data_s_type & loc_eng_data)1932 int loc_eng_start(loc_eng_data_s_type &loc_eng_data)
1933 {
1934    ENTRY_LOG_CALLFLOW();
1935    INIT_CHECK(loc_eng_data.adapter, return -1);
1936 
1937    if(! loc_eng_data.adapter->getUlpProxy()->sendStartFix())
1938    {
1939        loc_eng_data.adapter->sendMsg(new LocEngStartFix(loc_eng_data.adapter));
1940    }
1941 
1942    EXIT_LOG(%d, 0);
1943    return 0;
1944 }
1945 
loc_eng_start_handler(loc_eng_data_s_type & loc_eng_data)1946 static int loc_eng_start_handler(loc_eng_data_s_type &loc_eng_data)
1947 {
1948    ENTRY_LOG();
1949    int ret_val = LOC_API_ADAPTER_ERR_SUCCESS;
1950 
1951    if (!loc_eng_data.adapter->isInSession()) {
1952        ret_val = loc_eng_data.adapter->startFix();
1953 
1954        if (ret_val == LOC_API_ADAPTER_ERR_SUCCESS ||
1955            ret_val == LOC_API_ADAPTER_ERR_ENGINE_DOWN ||
1956            ret_val == LOC_API_ADAPTER_ERR_PHONE_OFFLINE ||
1957            ret_val == LOC_API_ADAPTER_ERR_INTERNAL)
1958        {
1959            loc_eng_data.adapter->setInSession(TRUE);
1960        }
1961    }
1962 
1963    EXIT_LOG(%d, ret_val);
1964    return ret_val;
1965 }
1966 
1967 /*===========================================================================
1968 FUNCTION    loc_eng_stop_wrapper
1969 
1970 DESCRIPTION
1971    Stops the tracking session
1972 
1973 DEPENDENCIES
1974    None
1975 
1976 RETURN VALUE
1977    0: success
1978 
1979 SIDE EFFECTS
1980    N/A
1981 
1982 ===========================================================================*/
loc_eng_stop(loc_eng_data_s_type & loc_eng_data)1983 int loc_eng_stop(loc_eng_data_s_type &loc_eng_data)
1984 {
1985     ENTRY_LOG_CALLFLOW();
1986     INIT_CHECK(loc_eng_data.adapter, return -1);
1987 
1988     if(! loc_eng_data.adapter->getUlpProxy()->sendStopFix())
1989     {
1990         loc_eng_data.adapter->sendMsg(new LocEngStopFix(loc_eng_data.adapter));
1991     }
1992 
1993     EXIT_LOG(%d, 0);
1994     return 0;
1995 }
1996 
loc_eng_stop_handler(loc_eng_data_s_type & loc_eng_data)1997 static int loc_eng_stop_handler(loc_eng_data_s_type &loc_eng_data)
1998 {
1999    ENTRY_LOG();
2000    int ret_val = LOC_API_ADAPTER_ERR_SUCCESS;
2001 
2002    if (loc_eng_data.adapter->isInSession()) {
2003 
2004        ret_val = loc_eng_data.adapter->stopFix();
2005        loc_eng_data.adapter->setInSession(FALSE);
2006    }
2007 
2008     EXIT_LOG(%d, ret_val);
2009     return ret_val;
2010 }
2011 
2012 /*===========================================================================
2013 FUNCTION    loc_eng_mute_one_session
2014 
2015 DESCRIPTION
2016    Mutes one session
2017 
2018 DEPENDENCIES
2019    None
2020 
2021 RETURN VALUE
2022    0: Success
2023 
2024 SIDE EFFECTS
2025    N/A
2026 
2027 ===========================================================================*/
loc_eng_mute_one_session(loc_eng_data_s_type & loc_eng_data)2028 void loc_eng_mute_one_session(loc_eng_data_s_type &loc_eng_data)
2029 {
2030     ENTRY_LOG();
2031     loc_eng_data.mute_session_state = LOC_MUTE_SESS_WAIT;
2032     EXIT_LOG(%s, VOID_RET);
2033 }
2034 
2035 /*===========================================================================
2036 FUNCTION    loc_eng_set_position_mode
2037 
2038 DESCRIPTION
2039    Sets the mode and fix frequency for the tracking session.
2040 
2041 DEPENDENCIES
2042    None
2043 
2044 RETURN VALUE
2045    0: success
2046 
2047 SIDE EFFECTS
2048    N/A
2049 
2050 ===========================================================================*/
loc_eng_set_position_mode(loc_eng_data_s_type & loc_eng_data,LocPosMode & params)2051 int loc_eng_set_position_mode(loc_eng_data_s_type &loc_eng_data,
2052                               LocPosMode &params)
2053 {
2054     ENTRY_LOG_CALLFLOW();
2055     INIT_CHECK(loc_eng_data.adapter, return -1);
2056 
2057     // The position mode for AUTO/GSS/QCA1530 can only be standalone
2058     if (!(gps_conf.CAPABILITIES & GPS_CAPABILITY_MSB) &&
2059         !(gps_conf.CAPABILITIES & GPS_CAPABILITY_MSA) &&
2060         (params.mode != LOC_POSITION_MODE_STANDALONE)) {
2061         params.mode = LOC_POSITION_MODE_STANDALONE;
2062         LOC_LOGD("Position mode changed to standalone for target with AUTO/GSS/qca1530.");
2063     }
2064 
2065     if(! loc_eng_data.adapter->getUlpProxy()->sendFixMode(params))
2066     {
2067         LocEngAdapter* adapter = loc_eng_data.adapter;
2068         adapter->sendMsg(new LocEngPositionMode(adapter, params));
2069     }
2070 
2071     EXIT_LOG(%d, 0);
2072     return 0;
2073 }
2074 
2075 /*===========================================================================
2076 FUNCTION    loc_eng_inject_time
2077 
2078 DESCRIPTION
2079    This is used by Java native function to do time injection.
2080 
2081 DEPENDENCIES
2082    None
2083 
2084 RETURN VALUE
2085    0
2086 
2087 SIDE EFFECTS
2088    N/A
2089 
2090 ===========================================================================*/
loc_eng_inject_time(loc_eng_data_s_type & loc_eng_data,GpsUtcTime time,int64_t timeReference,int uncertainty)2091 int loc_eng_inject_time(loc_eng_data_s_type &loc_eng_data, GpsUtcTime time,
2092                         int64_t timeReference, int uncertainty)
2093 {
2094     ENTRY_LOG_CALLFLOW();
2095     INIT_CHECK(loc_eng_data.adapter, return -1);
2096     LocEngAdapter* adapter = loc_eng_data.adapter;
2097 
2098     adapter->sendMsg(new LocEngSetTime(adapter, time, timeReference,
2099                                        uncertainty));
2100 
2101     EXIT_LOG(%d, 0);
2102     return 0;
2103 }
2104 
2105 
2106 /*===========================================================================
2107 FUNCTION    loc_eng_inject_location
2108 
2109 DESCRIPTION
2110    This is used by Java native function to do location injection.
2111 
2112 DEPENDENCIES
2113    None
2114 
2115 RETURN VALUE
2116    0          : Successful
2117    error code : Failure
2118 
2119 SIDE EFFECTS
2120    N/A
2121 ===========================================================================*/
loc_eng_inject_location(loc_eng_data_s_type & loc_eng_data,double latitude,double longitude,float accuracy)2122 int loc_eng_inject_location(loc_eng_data_s_type &loc_eng_data, double latitude,
2123                             double longitude, float accuracy)
2124 {
2125     ENTRY_LOG_CALLFLOW();
2126     INIT_CHECK(loc_eng_data.adapter, return -1);
2127     LocEngAdapter* adapter = loc_eng_data.adapter;
2128     if(adapter->mSupportsPositionInjection)
2129     {
2130         adapter->sendMsg(new LocEngInjectLocation(adapter, latitude, longitude,
2131                                                   accuracy));
2132     }
2133 
2134     EXIT_LOG(%d, 0);
2135     return 0;
2136 }
2137 
2138 
2139 /*===========================================================================
2140 FUNCTION    loc_eng_delete_aiding_data
2141 
2142 DESCRIPTION
2143    This is used by Java native function to delete the aiding data. The function
2144    updates the global variable for the aiding data to be deleted. If the GPS
2145    engine is off, the aiding data will be deleted. Otherwise, the actual action
2146    will happen when gps engine is turned off.
2147 
2148 DEPENDENCIES
2149    Assumes the aiding data type specified in GpsAidingData matches with
2150    LOC API specification.
2151 
2152 RETURN VALUE
2153    None
2154 
2155 SIDE EFFECTS
2156    N/A
2157 
2158 ===========================================================================*/
loc_eng_delete_aiding_data(loc_eng_data_s_type & loc_eng_data,GpsAidingData f)2159 void loc_eng_delete_aiding_data(loc_eng_data_s_type &loc_eng_data, GpsAidingData f)
2160 {
2161     ENTRY_LOG_CALLFLOW();
2162     INIT_CHECK(loc_eng_data.adapter, return);
2163 
2164     loc_eng_data.adapter->sendMsg(new LocEngDelAidData(&loc_eng_data, f));
2165 
2166     EXIT_LOG(%s, VOID_RET);
2167 }
2168 
2169 /*===========================================================================
2170 
2171 FUNCTION    loc_inform_gps_state
2172 
2173 DESCRIPTION
2174    Informs the GPS Provider about the GPS status
2175 
2176 DEPENDENCIES
2177    None
2178 
2179 RETURN VALUE
2180    None
2181 
2182 SIDE EFFECTS
2183    N/A
2184 
2185 ===========================================================================*/
loc_inform_gps_status(loc_eng_data_s_type & loc_eng_data,GpsStatusValue status)2186 static void loc_inform_gps_status(loc_eng_data_s_type &loc_eng_data, GpsStatusValue status)
2187 {
2188     ENTRY_LOG();
2189 
2190     if (loc_eng_data.status_cb)
2191     {
2192         GpsStatus gs = { sizeof(gs),status };
2193         CALLBACK_LOG_CALLFLOW("status_cb", %s,
2194                               loc_get_gps_status_name(gs.status));
2195         loc_eng_data.status_cb(&gs);
2196     }
2197 
2198     EXIT_LOG(%s, VOID_RET);
2199 }
2200 
loc_eng_get_zpp_handler(loc_eng_data_s_type & loc_eng_data)2201 static int loc_eng_get_zpp_handler(loc_eng_data_s_type &loc_eng_data)
2202 {
2203    ENTRY_LOG();
2204    int ret_val = LOC_API_ADAPTER_ERR_SUCCESS;
2205    UlpLocation location;
2206    LocPosTechMask tech_mask = LOC_POS_TECH_MASK_DEFAULT;
2207    GpsLocationExtended locationExtended;
2208    memset(&locationExtended, 0, sizeof (GpsLocationExtended));
2209    locationExtended.size = sizeof(locationExtended);
2210 
2211    ret_val = loc_eng_data.adapter->getZpp(location.gpsLocation, tech_mask);
2212   //Mark the location source as from ZPP
2213   location.gpsLocation.flags |= LOCATION_HAS_SOURCE_INFO;
2214   location.position_source = ULP_LOCATION_IS_FROM_ZPP;
2215 
2216   loc_eng_data.adapter->getUlpProxy()->reportPosition(location,
2217                                      locationExtended,
2218                                      NULL,
2219                                      LOC_SESS_SUCCESS,
2220                                      tech_mask);
2221 
2222   EXIT_LOG(%d, ret_val);
2223   return ret_val;
2224 }
2225 
2226 /*
2227   Callback function passed to Data Services State Machine
2228   This becomes part of the state machine's servicer and
2229   is used to send requests to the data services client
2230 */
dataCallCb(void * cb_data)2231 static int dataCallCb(void *cb_data)
2232 {
2233     LOC_LOGD("Enter dataCallCb\n");
2234     int ret=0;
2235     if(cb_data != NULL) {
2236         dsCbData *cbData = (dsCbData *)cb_data;
2237         LocEngAdapter *locAdapter = (LocEngAdapter *)cbData->mAdapter;
2238         if(cbData->action == GPS_REQUEST_AGPS_DATA_CONN) {
2239             LOC_LOGD("dataCallCb GPS_REQUEST_AGPS_DATA_CONN\n");
2240             ret =  locAdapter->openAndStartDataCall();
2241         }
2242         else if(cbData->action == GPS_RELEASE_AGPS_DATA_CONN) {
2243             LOC_LOGD("dataCallCb GPS_RELEASE_AGPS_DATA_CONN\n");
2244             locAdapter->stopDataCall();
2245         }
2246     }
2247     else {
2248         LOC_LOGE("NULL argument received. Failing.\n");
2249         ret = -1;
2250         goto err;
2251     }
2252 
2253 err:
2254     LOC_LOGD("Exit dataCallCb ret = %d\n", ret);
2255     return ret;
2256 }
2257 
2258 /*===========================================================================
2259 FUNCTION    loc_eng_agps_reinit
2260 
2261 DESCRIPTION
2262    2nd half of loc_eng_agps_init(), singled out for modem restart to use.
2263 
2264 DEPENDENCIES
2265    NONE
2266 
2267 RETURN VALUE
2268    0
2269 
2270 SIDE EFFECTS
2271    N/A
2272 
2273 ===========================================================================*/
loc_eng_agps_reinit(loc_eng_data_s_type & loc_eng_data)2274 static void loc_eng_agps_reinit(loc_eng_data_s_type &loc_eng_data)
2275 {
2276     ENTRY_LOG();
2277 
2278     // Set server addresses which came before init
2279     if (loc_eng_data.supl_host_set)
2280     {
2281         loc_eng_set_server(loc_eng_data, LOC_AGPS_SUPL_SERVER,
2282                            loc_eng_data.supl_host_buf,
2283                            loc_eng_data.supl_port_buf);
2284     }
2285 
2286     if (loc_eng_data.c2k_host_set)
2287     {
2288         loc_eng_set_server(loc_eng_data, LOC_AGPS_CDMA_PDE_SERVER,
2289                            loc_eng_data.c2k_host_buf,
2290                            loc_eng_data.c2k_port_buf);
2291     }
2292     EXIT_LOG(%s, VOID_RET);
2293 }
2294 /*===========================================================================
2295 FUNCTION    loc_eng_agps_init
2296 
2297 DESCRIPTION
2298    Initialize the AGps interface.
2299 
2300 DEPENDENCIES
2301    NONE
2302 
2303 RETURN VALUE
2304    0
2305 
2306 SIDE EFFECTS
2307    N/A
2308 
2309 ===========================================================================*/
loc_eng_agps_init(loc_eng_data_s_type & loc_eng_data,AGpsExtCallbacks * callbacks)2310 void loc_eng_agps_init(loc_eng_data_s_type &loc_eng_data, AGpsExtCallbacks* callbacks)
2311 {
2312     ENTRY_LOG_CALLFLOW();
2313     INIT_CHECK(loc_eng_data.adapter, return);
2314     STATE_CHECK((NULL == loc_eng_data.agps_status_cb),
2315                 "agps instance already initialized",
2316                 return);
2317     if (callbacks == NULL) {
2318         LOC_LOGE("loc_eng_agps_init: bad parameters cb %p", callbacks);
2319         EXIT_LOG(%s, VOID_RET);
2320         return;
2321     }
2322     LocEngAdapter* adapter = loc_eng_data.adapter;
2323     loc_eng_data.agps_status_cb = callbacks->status_cb;
2324 
2325     loc_eng_data.internet_nif = new AgpsStateMachine(servicerTypeAgps,
2326                                                      (void *)loc_eng_data.agps_status_cb,
2327                                                      AGPS_TYPE_WWAN_ANY,
2328                                                      false);
2329     loc_eng_data.wifi_nif = new AgpsStateMachine(servicerTypeAgps,
2330                                                  (void *)loc_eng_data.agps_status_cb,
2331                                                  AGPS_TYPE_WIFI,
2332                                                  true);
2333 
2334     if ((gps_conf.CAPABILITIES & GPS_CAPABILITY_MSA) ||
2335         (gps_conf.CAPABILITIES & GPS_CAPABILITY_MSB)) {
2336         loc_eng_data.agnss_nif = new AgpsStateMachine(servicerTypeAgps,
2337                                                       (void *)loc_eng_data.agps_status_cb,
2338                                                       AGPS_TYPE_SUPL,
2339                                                       false);
2340 
2341         if (adapter->mSupportsAgpsRequests) {
2342             if(gps_conf.USE_EMERGENCY_PDN_FOR_EMERGENCY_SUPL) {
2343                 loc_eng_data.adapter->sendMsg(new LocEngDataClientInit(&loc_eng_data));
2344             }
2345             loc_eng_dmn_conn_loc_api_server_launch(callbacks->create_thread_cb,
2346                                                    NULL, NULL, &loc_eng_data);
2347         }
2348         loc_eng_agps_reinit(loc_eng_data);
2349     }
2350 
2351     EXIT_LOG(%s, VOID_RET);
2352 }
2353 
deleteAidingData(loc_eng_data_s_type & logEng)2354 static void deleteAidingData(loc_eng_data_s_type &logEng) {
2355     if (logEng.engine_status != GPS_STATUS_ENGINE_ON &&
2356         logEng.aiding_data_for_deletion != 0) {
2357         logEng.adapter->deleteAidingData(logEng.aiding_data_for_deletion);
2358         logEng.aiding_data_for_deletion = 0;
2359     }
2360 }
2361 
2362 static AgpsStateMachine*
getAgpsStateMachine(loc_eng_data_s_type & locEng,AGpsExtType agpsType)2363 getAgpsStateMachine(loc_eng_data_s_type &locEng, AGpsExtType agpsType) {
2364     AgpsStateMachine* stateMachine;
2365     switch (agpsType) {
2366     case AGPS_TYPE_WIFI: {
2367         stateMachine = locEng.wifi_nif;
2368         break;
2369     }
2370     case AGPS_TYPE_INVALID:
2371     case AGPS_TYPE_SUPL: {
2372         stateMachine = locEng.agnss_nif;
2373         break;
2374     }
2375     case AGPS_TYPE_SUPL_ES: {
2376         locEng.ds_nif ?
2377             stateMachine = locEng.ds_nif:
2378             stateMachine = locEng.agnss_nif;
2379         break;
2380     }
2381     default:
2382         stateMachine  = locEng.internet_nif;
2383     }
2384     return stateMachine;
2385 }
2386 
2387 /*===========================================================================
2388 FUNCTION    loc_eng_agps_open
2389 
2390 DESCRIPTION
2391    This function is called when on-demand data connection opening is successful.
2392 It should inform engine about the data open result.
2393 
2394 DEPENDENCIES
2395    NONE
2396 
2397 RETURN VALUE
2398    0
2399 
2400 SIDE EFFECTS
2401    N/A
2402 
2403 ===========================================================================*/
loc_eng_agps_open(loc_eng_data_s_type & loc_eng_data,AGpsExtType agpsType,const char * apn,AGpsBearerType bearerType)2404 int loc_eng_agps_open(loc_eng_data_s_type &loc_eng_data, AGpsExtType agpsType,
2405                      const char* apn, AGpsBearerType bearerType)
2406 {
2407     ENTRY_LOG_CALLFLOW();
2408     INIT_CHECK(loc_eng_data.adapter && loc_eng_data.agps_status_cb,
2409                return -1);
2410 
2411     if (apn == NULL)
2412     {
2413         LOC_LOGE("APN Name NULL\n");
2414         return 0;
2415     }
2416 
2417     LOC_LOGD("loc_eng_agps_open APN name = [%s]", apn);
2418 
2419     int apn_len = smaller_of(strlen (apn), MAX_APN_LEN);
2420     AgpsStateMachine* sm = getAgpsStateMachine(loc_eng_data, agpsType);
2421 
2422     loc_eng_data.adapter->sendMsg(
2423         new LocEngAtlOpenSuccess(sm, apn, apn_len, bearerType));
2424 
2425     EXIT_LOG(%d, 0);
2426     return 0;
2427 }
2428 
2429 /*===========================================================================
2430 FUNCTION    loc_eng_agps_closed
2431 
2432 DESCRIPTION
2433    This function is called when on-demand data connection closing is done.
2434 It should inform engine about the data close result.
2435 
2436 DEPENDENCIES
2437    NONE
2438 
2439 RETURN VALUE
2440    0
2441 
2442 SIDE EFFECTS
2443    N/A
2444 
2445 ===========================================================================*/
loc_eng_agps_closed(loc_eng_data_s_type & loc_eng_data,AGpsExtType agpsType)2446 int loc_eng_agps_closed(loc_eng_data_s_type &loc_eng_data, AGpsExtType agpsType)
2447 {
2448     ENTRY_LOG_CALLFLOW();
2449     INIT_CHECK(loc_eng_data.adapter && loc_eng_data.agps_status_cb,
2450                return -1);
2451 
2452     AgpsStateMachine* sm = getAgpsStateMachine(loc_eng_data, agpsType);
2453     loc_eng_data.adapter->sendMsg(new LocEngAtlClosed(sm));
2454 
2455     EXIT_LOG(%d, 0);
2456     return 0;
2457 }
2458 
2459 /*===========================================================================
2460 FUNCTION    loc_eng_agps_open_failed
2461 
2462 DESCRIPTION
2463    This function is called when on-demand data connection opening has failed.
2464 It should inform engine about the data open result.
2465 
2466 DEPENDENCIES
2467    NONE
2468 
2469 RETURN VALUE
2470    0
2471 
2472 SIDE EFFECTS
2473    N/A
2474 
2475 ===========================================================================*/
loc_eng_agps_open_failed(loc_eng_data_s_type & loc_eng_data,AGpsExtType agpsType)2476 int loc_eng_agps_open_failed(loc_eng_data_s_type &loc_eng_data, AGpsExtType agpsType)
2477 {
2478     ENTRY_LOG_CALLFLOW();
2479     INIT_CHECK(loc_eng_data.adapter && loc_eng_data.agps_status_cb,
2480                return -1);
2481 
2482     AgpsStateMachine* sm = getAgpsStateMachine(loc_eng_data, agpsType);
2483     loc_eng_data.adapter->sendMsg(new LocEngAtlOpenFailed(sm));
2484 
2485     EXIT_LOG(%d, 0);
2486     return 0;
2487 }
2488 
2489 /*===========================================================================
2490 
2491 FUNCTION resolve_in_addr
2492 
2493 DESCRIPTION
2494    Translates a hostname to in_addr struct
2495 
2496 DEPENDENCIES
2497    n/a
2498 
2499 RETURN VALUE
2500    TRUE if successful
2501 
2502 SIDE EFFECTS
2503    n/a
2504 
2505 ===========================================================================*/
resolve_in_addr(const char * host_addr,struct in_addr * in_addr_ptr)2506 static boolean resolve_in_addr(const char *host_addr, struct in_addr *in_addr_ptr)
2507 {
2508     ENTRY_LOG();
2509     boolean ret_val = TRUE;
2510 
2511     struct hostent             *hp;
2512     hp = gethostbyname(host_addr);
2513     if (hp != NULL) /* DNS OK */
2514     {
2515         memcpy(in_addr_ptr, hp->h_addr_list[0], hp->h_length);
2516     }
2517     else
2518     {
2519         /* Try IP representation */
2520         if (inet_aton(host_addr, in_addr_ptr) == 0)
2521         {
2522             /* IP not valid */
2523             LOC_LOGE("DNS query on '%s' failed\n", host_addr);
2524             ret_val = FALSE;
2525         }
2526     }
2527 
2528     EXIT_LOG(%s, loc_logger_boolStr[ret_val!=0]);
2529     return ret_val;
2530 }
2531 
2532 /*===========================================================================
2533 FUNCTION    loc_eng_set_server
2534 
2535 DESCRIPTION
2536    This is used to set the default AGPS server. Server address is obtained
2537    from gps.conf.
2538 
2539 DEPENDENCIES
2540    NONE
2541 
2542 RETURN VALUE
2543    0
2544 
2545 SIDE EFFECTS
2546    N/A
2547 
2548 ===========================================================================*/
loc_eng_set_server(loc_eng_data_s_type & loc_eng_data,LocServerType type,const char * hostname,int port)2549 static int loc_eng_set_server(loc_eng_data_s_type &loc_eng_data,
2550                               LocServerType type, const char* hostname, int port)
2551 {
2552     ENTRY_LOG();
2553     int ret = 0;
2554     LocEngAdapter* adapter = loc_eng_data.adapter;
2555 
2556     if (LOC_AGPS_SUPL_SERVER == type) {
2557         char url[MAX_URL_LEN];
2558         unsigned int len = 0;
2559         const char nohost[] = "NONE";
2560         if (hostname == NULL ||
2561             strncasecmp(nohost, hostname, sizeof(nohost)) == 0) {
2562             url[0] = NULL;
2563         } else {
2564             len = snprintf(url, sizeof(url), "%s:%u", hostname, (unsigned) port);
2565         }
2566 
2567         if (sizeof(url) > len) {
2568             adapter->sendMsg(new LocEngSetServerUrl(adapter, url, len));
2569         }
2570     } else if (LOC_AGPS_CDMA_PDE_SERVER == type ||
2571                LOC_AGPS_CUSTOM_PDE_SERVER == type ||
2572                LOC_AGPS_MPC_SERVER == type) {
2573         struct in_addr addr;
2574         if (!resolve_in_addr(hostname, &addr))
2575         {
2576             LOC_LOGE("loc_eng_set_server, hostname %s cannot be resolved.\n", hostname);
2577             ret = -2;
2578         } else {
2579             unsigned int ip = htonl(addr.s_addr);
2580             adapter->sendMsg(new LocEngSetServerIpv4(adapter, ip, port, type));
2581         }
2582     } else {
2583         LOC_LOGE("loc_eng_set_server, type %d cannot be resolved.\n", type);
2584     }
2585 
2586     EXIT_LOG(%d, ret);
2587     return ret;
2588 }
2589 
2590 /*===========================================================================
2591 FUNCTION    loc_eng_set_server_proxy
2592 
2593 DESCRIPTION
2594    If loc_eng_set_server is called before loc_eng_init, it doesn't work. This
2595    proxy buffers server settings and calls loc_eng_set_server when the client is
2596    open.
2597 
2598 DEPENDENCIES
2599    NONE
2600 
2601 RETURN VALUE
2602    0
2603 
2604 SIDE EFFECTS
2605    N/A
2606 
2607 ===========================================================================*/
loc_eng_set_server_proxy(loc_eng_data_s_type & loc_eng_data,LocServerType type,const char * hostname,int port)2608 int loc_eng_set_server_proxy(loc_eng_data_s_type &loc_eng_data,
2609                              LocServerType type,
2610                              const char* hostname, int port)
2611 {
2612     ENTRY_LOG_CALLFLOW();
2613     int ret_val = 0;
2614 
2615     LOC_LOGV("save the address, type: %d, hostname: %s, port: %d",
2616              (int) type, hostname, port);
2617     switch (type)
2618     {
2619     case LOC_AGPS_SUPL_SERVER:
2620         strlcpy(loc_eng_data.supl_host_buf, hostname,
2621                 sizeof(loc_eng_data.supl_host_buf));
2622         loc_eng_data.supl_port_buf = port;
2623         loc_eng_data.supl_host_set = 1;
2624         break;
2625     case LOC_AGPS_CDMA_PDE_SERVER:
2626         strlcpy(loc_eng_data.c2k_host_buf, hostname,
2627                 sizeof(loc_eng_data.c2k_host_buf));
2628         loc_eng_data.c2k_port_buf = port;
2629         loc_eng_data.c2k_host_set = 1;
2630         break;
2631     default:
2632         LOC_LOGE("loc_eng_set_server_proxy, unknown server type = %d", (int) type);
2633     }
2634 
2635     if (NULL != loc_eng_data.adapter)
2636     {
2637         ret_val = loc_eng_set_server(loc_eng_data, type, hostname, port);
2638     }
2639 
2640     EXIT_LOG(%d, ret_val);
2641     return ret_val;
2642 }
2643 
2644 /*===========================================================================
2645 FUNCTION    loc_eng_agps_ril_update_network_availability
2646 
2647 DESCRIPTION
2648    Sets data call allow vs disallow flag to modem
2649    This is the only member of sLocEngAGpsRilInterface implemented.
2650 
2651 DEPENDENCIES
2652    None
2653 
2654 RETURN VALUE
2655    0: success
2656 
2657 SIDE EFFECTS
2658    N/A
2659 
2660 ===========================================================================*/
loc_eng_agps_ril_update_network_availability(loc_eng_data_s_type & loc_eng_data,int available,const char * apn)2661 void loc_eng_agps_ril_update_network_availability(loc_eng_data_s_type &loc_eng_data,
2662                                                   int available, const char* apn)
2663 {
2664     ENTRY_LOG_CALLFLOW();
2665 
2666     //This is to store the status of data availability over the network.
2667     //If GPS is not enabled, the INIT_CHECK will fail and the modem will
2668     //not be updated with the network's availability. Since the data status
2669     //can change before GPS is enabled the, storing the status will enable
2670     //us to inform the modem after GPS is enabled
2671     agpsStatus = available;
2672 
2673     INIT_CHECK(loc_eng_data.adapter, return);
2674     if (apn != NULL)
2675     {
2676         LOC_LOGD("loc_eng_agps_ril_update_network_availability: APN Name = [%s]\n", apn);
2677         int apn_len = smaller_of(strlen (apn), MAX_APN_LEN);
2678         LocEngAdapter* adapter = loc_eng_data.adapter;
2679         adapter->sendMsg(new LocEngEnableData(adapter, apn,  apn_len, available));
2680     }
2681     EXIT_LOG(%s, VOID_RET);
2682 }
2683 
loc_eng_agps_install_certificates(loc_eng_data_s_type & loc_eng_data,const DerEncodedCertificate * certificates,size_t numberOfCerts)2684 int loc_eng_agps_install_certificates(loc_eng_data_s_type &loc_eng_data,
2685                                       const DerEncodedCertificate* certificates,
2686                                       size_t numberOfCerts)
2687 {
2688     ENTRY_LOG_CALLFLOW();
2689     int ret_val = AGPS_CERTIFICATE_OPERATION_SUCCESS;
2690 
2691     uint32_t slotBitMask = gps_conf.AGPS_CERT_WRITABLE_MASK;
2692     uint32_t slotCount = 0;
2693     for (uint32_t slotBitMaskCounter=slotBitMask; slotBitMaskCounter; slotCount++) {
2694         slotBitMaskCounter &= slotBitMaskCounter - 1;
2695     }
2696     LOC_LOGD("SlotBitMask=%u SlotCount=%u NumberOfCerts=%u",
2697              slotBitMask, slotCount, numberOfCerts);
2698 
2699     LocEngAdapter* adapter = loc_eng_data.adapter;
2700 
2701     if (numberOfCerts == 0) {
2702         LOC_LOGE("No certs to install, since numberOfCerts is zero");
2703         ret_val = AGPS_CERTIFICATE_OPERATION_SUCCESS;
2704     } else if (!adapter) {
2705         LOC_LOGE("adapter is null!");
2706         ret_val = AGPS_CERTIFICATE_ERROR_GENERIC;
2707     } else if (slotCount < numberOfCerts) {
2708         LOC_LOGE("Not enough cert slots (%u) to install %u certs!",
2709                  slotCount, numberOfCerts);
2710         ret_val = AGPS_CERTIFICATE_ERROR_TOO_MANY_CERTIFICATES;
2711     } else {
2712         for (int i=0; i < numberOfCerts; ++i)
2713         {
2714             if (certificates[i].length > AGPS_CERTIFICATE_MAX_LENGTH) {
2715                 LOC_LOGE("cert#(%u) length of %u is too big! greater than %u",
2716                         certificates[i].length, AGPS_CERTIFICATE_MAX_LENGTH);
2717                 ret_val = AGPS_CERTIFICATE_ERROR_GENERIC;
2718                 break;
2719             }
2720         }
2721 
2722         if (ret_val == AGPS_CERTIFICATE_OPERATION_SUCCESS) {
2723             adapter->sendMsg(new LocEngInstallAGpsCert(adapter,
2724                                                        certificates,
2725                                                        numberOfCerts,
2726                                                        slotBitMask));
2727         }
2728     }
2729 
2730     EXIT_LOG(%d, ret_val);
2731     return ret_val;
2732 }
2733 
loc_eng_configuration_update(loc_eng_data_s_type & loc_eng_data,const char * config_data,int32_t length)2734 void loc_eng_configuration_update (loc_eng_data_s_type &loc_eng_data,
2735                                    const char* config_data, int32_t length)
2736 {
2737     ENTRY_LOG_CALLFLOW();
2738 
2739     if (config_data && length > 0) {
2740         loc_gps_cfg_s_type gps_conf_tmp = gps_conf;
2741         UTIL_UPDATE_CONF(config_data, length, gps_conf_table);
2742         LocEngAdapter* adapter = loc_eng_data.adapter;
2743 
2744         // it is possible that HAL is not init'ed at this time
2745         if (adapter) {
2746             if (gps_conf_tmp.SUPL_VER != gps_conf.SUPL_VER) {
2747                 adapter->sendMsg(new LocEngSuplVer(adapter, gps_conf.SUPL_VER));
2748             }
2749             if (gps_conf_tmp.LPP_PROFILE != gps_conf.LPP_PROFILE) {
2750                 adapter->sendMsg(new LocEngLppConfig(adapter, gps_conf.LPP_PROFILE));
2751             }
2752             if (gps_conf_tmp.A_GLONASS_POS_PROTOCOL_SELECT != gps_conf.A_GLONASS_POS_PROTOCOL_SELECT) {
2753                 adapter->sendMsg(new LocEngAGlonassProtocol(adapter,
2754                                                             gps_conf.A_GLONASS_POS_PROTOCOL_SELECT));
2755             }
2756             if (gps_conf_tmp.SUPL_MODE != gps_conf.SUPL_MODE) {
2757                 adapter->sendMsg(new LocEngSuplMode(adapter->getUlpProxy()));
2758             }
2759         }
2760 
2761         gps_conf_tmp.SUPL_VER = gps_conf.SUPL_VER;
2762         gps_conf_tmp.LPP_PROFILE = gps_conf.LPP_PROFILE;
2763         gps_conf_tmp.A_GLONASS_POS_PROTOCOL_SELECT = gps_conf.A_GLONASS_POS_PROTOCOL_SELECT;
2764         gps_conf_tmp.GPS_LOCK = gps_conf.GPS_LOCK;
2765         gps_conf = gps_conf_tmp;
2766     }
2767 
2768     EXIT_LOG(%s, VOID_RET);
2769 }
2770 
2771 /*===========================================================================
2772 FUNCTION    loc_eng_report_status
2773 
2774 DESCRIPTION
2775    Reports GPS engine state to Java layer.
2776 
2777 DEPENDENCIES
2778    N/A
2779 
2780 RETURN VALUE
2781    N/A
2782 
2783 SIDE EFFECTS
2784    N/A
2785 
2786 ===========================================================================*/
loc_eng_report_status(loc_eng_data_s_type & loc_eng_data,GpsStatusValue status)2787 static void loc_eng_report_status (loc_eng_data_s_type &loc_eng_data, GpsStatusValue status)
2788 {
2789     ENTRY_LOG();
2790     // Switch from WAIT to MUTE, for "engine on" or "session begin" event
2791     if (status == GPS_STATUS_SESSION_BEGIN || status == GPS_STATUS_ENGINE_ON)
2792     {
2793         if (loc_eng_data.mute_session_state == LOC_MUTE_SESS_WAIT)
2794         {
2795             LOC_LOGD("loc_eng_report_status: mute_session_state changed from WAIT to IN SESSION");
2796             loc_eng_data.mute_session_state = LOC_MUTE_SESS_IN_SESSION;
2797         }
2798     }
2799 
2800     // Switch off MUTE session
2801     if (loc_eng_data.mute_session_state == LOC_MUTE_SESS_IN_SESSION &&
2802         (status == GPS_STATUS_SESSION_END || status == GPS_STATUS_ENGINE_OFF))
2803     {
2804         LOC_LOGD("loc_eng_report_status: mute_session_state changed from IN SESSION to NONE");
2805         loc_eng_data.mute_session_state = LOC_MUTE_SESS_NONE;
2806     }
2807 
2808     // Session End is not reported during Android navigating state
2809     boolean navigating = loc_eng_data.adapter->isInSession();
2810     if (status != GPS_STATUS_NONE &&
2811         !(status == GPS_STATUS_SESSION_END && navigating) &&
2812         !(status == GPS_STATUS_SESSION_BEGIN && !navigating))
2813     {
2814         if (loc_eng_data.mute_session_state != LOC_MUTE_SESS_IN_SESSION)
2815         {
2816             // Inform GpsLocationProvider about mNavigating status
2817             loc_inform_gps_status(loc_eng_data, status);
2818         }
2819         else {
2820             LOC_LOGD("loc_eng_report_status: muting the status report.");
2821         }
2822     }
2823 
2824     // Only keeps ENGINE ON/OFF in engine_status
2825     if (status == GPS_STATUS_ENGINE_ON || status == GPS_STATUS_ENGINE_OFF)
2826     {
2827         loc_eng_data.engine_status = status;
2828     }
2829 
2830     // Only keeps SESSION BEGIN/END in fix_session_status
2831     if (status == GPS_STATUS_SESSION_BEGIN || status == GPS_STATUS_SESSION_END)
2832     {
2833         loc_eng_data.fix_session_status = status;
2834     }
2835     EXIT_LOG(%s, VOID_RET);
2836 }
2837 
2838 /*===========================================================================
2839 FUNCTION loc_eng_handle_engine_down
2840          loc_eng_handle_engine_up
2841 
2842 DESCRIPTION
2843    Calls this function when it is detected that modem restart is happening.
2844    Either we detected the modem is down or received modem up event.
2845    This must be called from the deferred thread to avoid race condition.
2846 
2847 DEPENDENCIES
2848    None
2849 
2850 RETURN VALUE
2851    None
2852 
2853 SIDE EFFECTS
2854    N/A
2855 
2856 ===========================================================================*/
loc_eng_handle_engine_down(loc_eng_data_s_type & loc_eng_data)2857 void loc_eng_handle_engine_down(loc_eng_data_s_type &loc_eng_data)
2858 {
2859     ENTRY_LOG();
2860     loc_eng_ni_reset_on_engine_restart(loc_eng_data);
2861     loc_eng_report_status(loc_eng_data, GPS_STATUS_ENGINE_OFF);
2862     EXIT_LOG(%s, VOID_RET);
2863 }
2864 
loc_eng_handle_engine_up(loc_eng_data_s_type & loc_eng_data)2865 void loc_eng_handle_engine_up(loc_eng_data_s_type &loc_eng_data)
2866 {
2867     ENTRY_LOG();
2868     loc_eng_reinit(loc_eng_data);
2869 
2870     loc_eng_data.adapter->requestPowerVote();
2871 
2872     if (loc_eng_data.agps_status_cb != NULL) {
2873         if (loc_eng_data.agnss_nif)
2874             loc_eng_data.agnss_nif->dropAllSubscribers();
2875         if (loc_eng_data.internet_nif)
2876             loc_eng_data.internet_nif->dropAllSubscribers();
2877 
2878         loc_eng_agps_reinit(loc_eng_data);
2879     }
2880 
2881     // modem is back up.  If we crashed in the middle of navigating, we restart.
2882     if (loc_eng_data.adapter->isInSession()) {
2883         // This sets the copy in adapter to modem
2884         loc_eng_data.adapter->setInSession(false);
2885         loc_eng_data.adapter->sendMsg(new LocEngStartFix(loc_eng_data.adapter));
2886     }
2887     EXIT_LOG(%s, VOID_RET);
2888 }
2889 
2890 #ifdef USE_GLIB
2891 /*===========================================================================
2892 FUNCTION set_sched_policy
2893 
2894 DESCRIPTION
2895    Local copy of this function which bypasses android set_sched_policy
2896 
2897 DEPENDENCIES
2898    None
2899 
2900 RETURN VALUE
2901    0
2902 
2903 SIDE EFFECTS
2904    N/A
2905 
2906 ===========================================================================*/
set_sched_policy(int tid,SchedPolicy policy)2907 static int set_sched_policy(int tid, SchedPolicy policy)
2908 {
2909     return 0;
2910 }
2911 #endif /* USE_GLIB */
2912 
2913 /*===========================================================================
2914 FUNCTION    loc_eng_read_config
2915 
2916 DESCRIPTION
2917    Initiates the reading of the gps config file stored in /etc dir
2918 
2919 DEPENDENCIES
2920    None
2921 
2922 RETURN VALUE
2923    0: success
2924 
2925 SIDE EFFECTS
2926    N/A
2927 
2928 ===========================================================================*/
loc_eng_read_config(void)2929 int loc_eng_read_config(void)
2930 {
2931     ENTRY_LOG_CALLFLOW();
2932     if(configAlreadyRead == false)
2933     {
2934       // Initialize our defaults before reading of configuration file overwrites them.
2935       loc_default_parameters();
2936       // We only want to parse the conf file once. This is a good place to ensure that.
2937       // In fact one day the conf file should go into context.
2938       UTIL_READ_CONF(GPS_CONF_FILE, gps_conf_table);
2939       UTIL_READ_CONF(SAP_CONF_FILE, sap_conf_table);
2940       configAlreadyRead = true;
2941     } else {
2942       LOC_LOGV("GPS Config file has already been read\n");
2943     }
2944 
2945     EXIT_LOG(%d, 0);
2946     return 0;
2947 }
2948 
2949 /*===========================================================================
2950 FUNCTION    loc_eng_gps_measurement_init
2951 
2952 DESCRIPTION
2953    Initialize gps measurement module.
2954 
2955 DEPENDENCIES
2956    N/A
2957 
2958 RETURN VALUE
2959    0: success
2960 
2961 SIDE EFFECTS
2962    N/A
2963 
2964 ===========================================================================*/
loc_eng_gps_measurement_init(loc_eng_data_s_type & loc_eng_data,GpsMeasurementCallbacks * callbacks)2965 int loc_eng_gps_measurement_init(loc_eng_data_s_type &loc_eng_data,
2966                                  GpsMeasurementCallbacks* callbacks)
2967 {
2968     ENTRY_LOG_CALLFLOW();
2969 
2970     STATE_CHECK((NULL == loc_eng_data.gnss_measurement_cb),
2971                 "gnss measurement already initialized",
2972                 return GPS_MEASUREMENT_ERROR_ALREADY_INIT);
2973     STATE_CHECK((callbacks != NULL),
2974                 "callbacks can not be NULL",
2975                 return GPS_MEASUREMENT_ERROR_GENERIC);
2976     STATE_CHECK(loc_eng_data.adapter,
2977                 "GpsInterface must be initialized first",
2978                 return GPS_MEASUREMENT_ERROR_GENERIC);
2979 
2980     // updated the mask
2981     LOC_API_ADAPTER_EVENT_MASK_T event = LOC_API_ADAPTER_BIT_GNSS_MEASUREMENT;
2982     loc_eng_data.adapter->sendMsg(new LocEngUpdateRegistrationMask(
2983                                                         &loc_eng_data,
2984                                                         event,
2985                                                         LOC_REGISTRATION_MASK_ENABLED));
2986     // set up the callback
2987     loc_eng_data.gnss_measurement_cb = callbacks->gnss_measurement_callback;
2988     LOC_LOGD ("%s, event masks updated successfully", __func__);
2989 
2990     return GPS_MEASUREMENT_OPERATION_SUCCESS;
2991 }
2992 
2993 /*===========================================================================
2994 FUNCTION    loc_eng_gps_measurement_close
2995 
2996 DESCRIPTION
2997    Close gps measurement module.
2998 
2999 DEPENDENCIES
3000    N/A
3001 
3002 RETURN VALUE
3003    N/A
3004 
3005 SIDE EFFECTS
3006    N/A
3007 
3008 ===========================================================================*/
loc_eng_gps_measurement_close(loc_eng_data_s_type & loc_eng_data)3009 void loc_eng_gps_measurement_close(loc_eng_data_s_type &loc_eng_data)
3010 {
3011     ENTRY_LOG_CALLFLOW();
3012 
3013     INIT_CHECK(loc_eng_data.adapter, return);
3014 
3015     // updated the mask
3016     LOC_API_ADAPTER_EVENT_MASK_T event = LOC_API_ADAPTER_BIT_GNSS_MEASUREMENT;
3017     loc_eng_data.adapter->sendMsg(new LocEngUpdateRegistrationMask(
3018                                                           &loc_eng_data,
3019                                                           event,
3020                                                           LOC_REGISTRATION_MASK_DISABLED));
3021     // set up the callback
3022     loc_eng_data.gnss_measurement_cb = NULL;
3023     EXIT_LOG(%d, 0);
3024 }
3025