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