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