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