Home | History | Annotate | Download | only in libloc_api_50001
      1 /* Copyright (c) 2009-2013, The Linux Foundation. All rights reserved.
      2  *
      3  * Redistribution and use in source and binary forms, with or without
      4  * modification, are permitted provided that the following conditions are
      5  * met:
      6  *     * Redistributions of source code must retain the above copyright
      7  *       notice, this list of conditions and the following disclaimer.
      8  *     * Redistributions in binary form must reproduce the above
      9  *       copyright notice, this list of conditions and the following
     10  *       disclaimer in the documentation and/or other materials provided
     11  *       with the distribution.
     12  *     * Neither the name of The Linux Foundation, nor the names of its
     13  *       contributors may be used to endorse or promote products derived
     14  *       from this software without specific prior written permission.
     15  *
     16  * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
     17  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
     18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
     19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
     20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
     23  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     24  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
     25  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
     26  * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     27  *
     28  */
     29 
     30 #define LOG_NDDEBUG 0
     31 #define LOG_TAG "LocSvc_eng"
     32 
     33 #include <stdint.h>
     34 #include <stdio.h>
     35 #include <stdlib.h>
     36 #include <unistd.h>
     37 #include <dlfcn.h>
     38 #include <ctype.h>
     39 #include <math.h>
     40 #include <pthread.h>
     41 #include <arpa/inet.h>
     42 #include <netinet/in.h>         /* struct sockaddr_in */
     43 #include <sys/socket.h>
     44 #include <sys/time.h>
     45 #include <netdb.h>
     46 #include <time.h>
     47 
     48 #include <LocEngAdapter.h>
     49 
     50 #include <cutils/sched_policy.h>
     51 #ifndef USE_GLIB
     52 #include <utils/SystemClock.h>
     53 #include <utils/Log.h>
     54 #endif /* USE_GLIB */
     55 
     56 #ifdef USE_GLIB
     57 #include <glib.h>
     58 #include <sys/syscall.h>
     59 #endif /* USE_GLIB */
     60 
     61 #include <string.h>
     62 
     63 #include <loc_eng.h>
     64 #include <loc_eng_ni.h>
     65 #include <loc_eng_dmn_conn.h>
     66 #include <loc_eng_dmn_conn_handler.h>
     67 #include <loc_eng_msg.h>
     68 #include <loc_eng_nmea.h>
     69 #include <msg_q.h>
     70 #include <loc.h>
     71 #include "log_util.h"
     72 #include "platform_lib_includes.h"
     73 #include "loc_core_log.h"
     74 #include "loc_eng_log.h"
     75 
     76 #define SUCCESS TRUE
     77 #define FAILURE FALSE
     78 
     79 #ifndef GPS_CONF_FILE
     80 #define GPS_CONF_FILE            "/etc/gps.conf"   //??? platform independent
     81 #endif
     82 
     83 #ifndef SAP_CONF_FILE
     84 #define SAP_CONF_FILE            "/etc/sap.conf"
     85 #endif
     86 
     87 using namespace loc_core;
     88 
     89 boolean configAlreadyRead = false;
     90 unsigned int agpsStatus = 0;
     91 loc_gps_cfg_s_type gps_conf;
     92 loc_sap_cfg_s_type sap_conf;
     93 
     94 /* Parameter spec table */
     95 static loc_param_s_type loc_parameter_table[] =
     96 {
     97   {"INTERMEDIATE_POS",               &gps_conf.INTERMEDIATE_POS,               NULL, 'n'},
     98   {"ACCURACY_THRES",                 &gps_conf.ACCURACY_THRES,                 NULL, 'n'},
     99   {"ENABLE_WIPER",                   &gps_conf.ENABLE_WIPER,                   NULL, 'n'},
    100   {"NMEA_PROVIDER",                  &gps_conf.NMEA_PROVIDER,                  NULL, 'n'},
    101   {"SUPL_VER",                       &gps_conf.SUPL_VER,                       NULL, 'n'},
    102   {"CAPABILITIES",                   &gps_conf.CAPABILITIES,                   NULL, 'n'},
    103   {"GYRO_BIAS_RANDOM_WALK",          &sap_conf.GYRO_BIAS_RANDOM_WALK,          &sap_conf.GYRO_BIAS_RANDOM_WALK_VALID, 'f'},
    104   {"ACCEL_RANDOM_WALK_SPECTRAL_DENSITY",     &sap_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY,    &sap_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY_VALID, 'f'},
    105   {"ANGLE_RANDOM_WALK_SPECTRAL_DENSITY",     &sap_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY,    &sap_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY_VALID, 'f'},
    106   {"RATE_RANDOM_WALK_SPECTRAL_DENSITY",      &sap_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY,     &sap_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY_VALID, 'f'},
    107   {"VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY",  &sap_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY, &sap_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY_VALID, 'f'},
    108   {"SENSOR_ACCEL_BATCHES_PER_SEC",   &sap_conf.SENSOR_ACCEL_BATCHES_PER_SEC,   NULL, 'n'},
    109   {"SENSOR_ACCEL_SAMPLES_PER_BATCH", &sap_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH, NULL, 'n'},
    110   {"SENSOR_GYRO_BATCHES_PER_SEC",    &sap_conf.SENSOR_GYRO_BATCHES_PER_SEC,    NULL, 'n'},
    111   {"SENSOR_GYRO_SAMPLES_PER_BATCH",  &sap_conf.SENSOR_GYRO_SAMPLES_PER_BATCH,  NULL, 'n'},
    112   {"SENSOR_ACCEL_BATCHES_PER_SEC_HIGH",   &sap_conf.SENSOR_ACCEL_BATCHES_PER_SEC_HIGH,   NULL, 'n'},
    113   {"SENSOR_ACCEL_SAMPLES_PER_BATCH_HIGH", &sap_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH_HIGH, NULL, 'n'},
    114   {"SENSOR_GYRO_BATCHES_PER_SEC_HIGH",    &sap_conf.SENSOR_GYRO_BATCHES_PER_SEC_HIGH,    NULL, 'n'},
    115   {"SENSOR_GYRO_SAMPLES_PER_BATCH_HIGH",  &sap_conf.SENSOR_GYRO_SAMPLES_PER_BATCH_HIGH,  NULL, 'n'},
    116   {"SENSOR_CONTROL_MODE",            &sap_conf.SENSOR_CONTROL_MODE,            NULL, 'n'},
    117   {"SENSOR_USAGE",                   &sap_conf.SENSOR_USAGE,                   NULL, 'n'},
    118   {"SENSOR_ALGORITHM_CONFIG_MASK",   &sap_conf.SENSOR_ALGORITHM_CONFIG_MASK,   NULL, 'n'},
    119   {"QUIPC_ENABLED",                  &gps_conf.QUIPC_ENABLED,                  NULL, 'n'},
    120   {"LPP_PROFILE",                    &gps_conf.LPP_PROFILE,                    NULL, 'n'},
    121   {"A_GLONASS_POS_PROTOCOL_SELECT",  &gps_conf.A_GLONASS_POS_PROTOCOL_SELECT,  NULL, 'n'},
    122 };
    123 
    124 static void loc_default_parameters(void)
    125 {
    126    /* defaults */
    127    gps_conf.INTERMEDIATE_POS = 0;
    128    gps_conf.ACCURACY_THRES = 0;
    129    gps_conf.ENABLE_WIPER = 0;
    130    gps_conf.NMEA_PROVIDER = 0;
    131    gps_conf.SUPL_VER = 0x10000;
    132    gps_conf.CAPABILITIES = 0x7;
    133 
    134    sap_conf.GYRO_BIAS_RANDOM_WALK = 0;
    135    sap_conf.SENSOR_ACCEL_BATCHES_PER_SEC = 2;
    136    sap_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH = 5;
    137    sap_conf.SENSOR_GYRO_BATCHES_PER_SEC = 2;
    138    sap_conf.SENSOR_GYRO_SAMPLES_PER_BATCH = 5;
    139    sap_conf.SENSOR_ACCEL_BATCHES_PER_SEC_HIGH = 4;
    140    sap_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH_HIGH = 25;
    141    sap_conf.SENSOR_GYRO_BATCHES_PER_SEC_HIGH = 4;
    142    sap_conf.SENSOR_GYRO_SAMPLES_PER_BATCH_HIGH = 25;
    143    sap_conf.SENSOR_CONTROL_MODE = 0; /* AUTO */
    144    sap_conf.SENSOR_USAGE = 0; /* Enabled */
    145    sap_conf.SENSOR_ALGORITHM_CONFIG_MASK = 0; /* INS Disabled = FALSE*/
    146 
    147    /* Values MUST be set by OEMs in configuration for sensor-assisted
    148       navigation to work. There are NO default values */
    149    sap_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY = 0;
    150    sap_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY = 0;
    151    sap_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY = 0;
    152    sap_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY = 0;
    153 
    154    sap_conf.GYRO_BIAS_RANDOM_WALK_VALID = 0;
    155    sap_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY_VALID = 0;
    156    sap_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY_VALID = 0;
    157    sap_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY_VALID = 0;
    158    sap_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY_VALID = 0;
    159 
    160       /* LTE Positioning Profile configuration is disable by default*/
    161    gps_conf.LPP_PROFILE = 0;
    162 
    163    /*By default no positioning protocol is selected on A-GLONASS system*/
    164    gps_conf.A_GLONASS_POS_PROTOCOL_SELECT = 0;
    165 }
    166 
    167 // 2nd half of init(), singled out for
    168 // modem restart to use.
    169 static int loc_eng_reinit(loc_eng_data_s_type &loc_eng_data);
    170 static void loc_eng_agps_reinit(loc_eng_data_s_type &loc_eng_data);
    171 
    172 static int loc_eng_set_server(loc_eng_data_s_type &loc_eng_data,
    173                               LocServerType type, const char *hostname, int port);
    174 // Internal functions
    175 static void loc_inform_gps_status(loc_eng_data_s_type &loc_eng_data,
    176                                   GpsStatusValue status);
    177 static void loc_eng_report_status(loc_eng_data_s_type &loc_eng_data,
    178                                   GpsStatusValue status);
    179 static void loc_eng_process_conn_request(loc_eng_data_s_type &loc_eng_data,
    180                                          int connHandle, AGpsType agps_type);
    181 static void loc_eng_agps_close_status(loc_eng_data_s_type &loc_eng_data, int is_succ);
    182 static void loc_eng_handle_engine_down(loc_eng_data_s_type &loc_eng_data) ;
    183 static void loc_eng_handle_engine_up(loc_eng_data_s_type &loc_eng_data) ;
    184 
    185 static int loc_eng_start_handler(loc_eng_data_s_type &loc_eng_data);
    186 static int loc_eng_stop_handler(loc_eng_data_s_type &loc_eng_data);
    187 
    188 static void deleteAidingData(loc_eng_data_s_type &logEng);
    189 static AgpsStateMachine*
    190 getAgpsStateMachine(loc_eng_data_s_type& logEng, AGpsExtType agpsType);
    191 
    192 static void update_aiding_data_for_deletion(loc_eng_data_s_type& loc_eng_data) {
    193     if (loc_eng_data.engine_status != GPS_STATUS_ENGINE_ON &&
    194         loc_eng_data.aiding_data_for_deletion != 0)
    195     {
    196         loc_eng_data.adapter->deleteAidingData(loc_eng_data.aiding_data_for_deletion);
    197         loc_eng_data.aiding_data_for_deletion = 0;
    198     }
    199 }
    200 
    201 static void* noProc(void* data)
    202 {
    203     return NULL;
    204 }
    205 
    206 
    207 /*********************************************************************
    208  * definitions of the static messages used in the file
    209  *********************************************************************/
    210 //        case LOC_ENG_MSG_REQUEST_NI:
    211 LocEngRequestNi::LocEngRequestNi(void* locEng,
    212                                  GpsNiNotification &notif,
    213                                  const void* data) :
    214     LocMsg(), mLocEng(locEng), mNotify(notif), mPayload(data) {
    215     locallog();
    216 }
    217 void LocEngRequestNi::proc() const {
    218     loc_eng_ni_request_handler(*((loc_eng_data_s_type*)mLocEng),
    219                                &mNotify, mPayload);
    220 }
    221 void LocEngRequestNi::locallog() const
    222 {
    223     LOC_LOGV("id: %d\n  type: %s\n  flags: %d\n  time out: %d\n  "
    224              "default response: %s\n  requestor id encoding: %s\n"
    225              "  text encoding: %s\n  passThroughData: %p",
    226              mNotify.notification_id,
    227              loc_get_ni_type_name(mNotify.ni_type),
    228              mNotify.notify_flags,
    229              mNotify.timeout,
    230              loc_get_ni_response_name(mNotify.default_response),
    231              loc_get_ni_encoding_name(mNotify.requestor_id_encoding),
    232              loc_get_ni_encoding_name(mNotify.text_encoding),
    233              mPayload);
    234 }
    235 inline void LocEngRequestNi::log() const {
    236     locallog();
    237 }
    238 
    239 //        case LOC_ENG_MSG_INFORM_NI_RESPONSE:
    240 // in loc_eng_ni.cpp
    241 
    242 //        case LOC_ENG_MSG_START_FIX:
    243 LocEngStartFix::LocEngStartFix(LocEngAdapter* adapter) :
    244     LocMsg(), mAdapter(adapter)
    245 {
    246     locallog();
    247 }
    248 inline void LocEngStartFix::proc() const
    249 {
    250     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mAdapter->getOwner();
    251     loc_eng_start_handler(*locEng);
    252 }
    253 inline void LocEngStartFix::locallog() const
    254 {
    255     LOC_LOGV("LocEngStartFix");
    256 }
    257 inline void LocEngStartFix::log() const
    258 {
    259     locallog();
    260 }
    261 void LocEngStartFix::send() const {
    262     mAdapter->sendMsg(this);
    263 }
    264 
    265 //        case LOC_ENG_MSG_STOP_FIX:
    266 LocEngStopFix::LocEngStopFix(LocEngAdapter* adapter) :
    267     LocMsg(), mAdapter(adapter)
    268 {
    269     locallog();
    270 }
    271 inline void LocEngStopFix::proc() const
    272 {
    273     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mAdapter->getOwner();
    274     loc_eng_stop_handler(*locEng);
    275 }
    276 inline void LocEngStopFix::locallog() const
    277 {
    278     LOC_LOGV("LocEngStopFix");
    279 }
    280 inline void LocEngStopFix::log() const
    281 {
    282     locallog();
    283 }
    284 void LocEngStopFix::send() const {
    285     mAdapter->sendMsg(this);
    286 }
    287 
    288 //        case LOC_ENG_MSG_SET_POSITION_MODE:
    289 LocEngPositionMode::LocEngPositionMode(LocEngAdapter* adapter,
    290                                        LocPosMode &mode) :
    291     LocMsg(), mAdapter(adapter), mPosMode(mode)
    292 {
    293     mPosMode.logv();
    294 }
    295 inline void LocEngPositionMode::proc() const {
    296     mAdapter->setPositionMode(&mPosMode);
    297 }
    298 inline void LocEngPositionMode::log() const {
    299     mPosMode.logv();
    300 }
    301 void LocEngPositionMode::send() const {
    302     mAdapter->sendMsg(this);
    303 }
    304 
    305 //        case LOC_ENG_MSG_SET_TIME:
    306 struct LocEngSetTime : public LocMsg {
    307     LocEngAdapter* mAdapter;
    308     const GpsUtcTime mTime;
    309     const int64_t mTimeReference;
    310     const int mUncertainty;
    311     inline LocEngSetTime(LocEngAdapter* adapter,
    312                          GpsUtcTime t, int64_t tf, int unc) :
    313         LocMsg(), mAdapter(adapter),
    314         mTime(t), mTimeReference(tf), mUncertainty(unc)
    315     {
    316         locallog();
    317     }
    318     inline virtual void proc() const {
    319         mAdapter->setTime(mTime, mTimeReference, mUncertainty);
    320     }
    321     inline void locallog() const {
    322         LOC_LOGV("time: %lld\n  timeReference: %lld\n  uncertainty: %d",
    323                  mTime, mTimeReference, mUncertainty);
    324     }
    325     inline virtual void log() const {
    326         locallog();
    327     }
    328 };
    329 
    330  //       case LOC_ENG_MSG_INJECT_LOCATION:
    331 struct LocEngInjectLocation : public LocMsg {
    332     LocEngAdapter* mAdapter;
    333     const double mLatitude;
    334     const double mLongitude;
    335     const float mAccuracy;
    336     inline LocEngInjectLocation(LocEngAdapter* adapter,
    337                                 double lat, double lon, float accur) :
    338         LocMsg(), mAdapter(adapter),
    339         mLatitude(lat), mLongitude(lon), mAccuracy(accur)
    340     {
    341         locallog();
    342     }
    343     inline virtual void proc() const {
    344         mAdapter->injectPosition(mLatitude, mLongitude, mAccuracy);
    345     }
    346     inline void locallog() const {
    347         LOC_LOGV("latitude: %f\n  longitude: %f\n  accuracy: %f",
    348                  mLatitude, mLongitude, mAccuracy);
    349     }
    350     inline virtual void log() const {
    351         locallog();
    352     }
    353 };
    354 
    355 //        case LOC_ENG_MSG_SET_SERVER_IPV4:
    356 struct LocEngSetServerIpv4 : public LocMsg {
    357     LocEngAdapter* mAdapter;
    358     const unsigned int mNlAddr;
    359     const int mPort;
    360     const LocServerType mServerType;
    361     inline LocEngSetServerIpv4(LocEngAdapter* adapter,
    362                                unsigned int ip,
    363                                int port,
    364                                LocServerType type) :
    365         LocMsg(), mAdapter(adapter),
    366         mNlAddr(ip), mPort(port), mServerType(type)
    367     {
    368         locallog();
    369     }
    370     inline virtual void proc() const {
    371         mAdapter->setServer(mNlAddr, mPort, mServerType);
    372     }
    373     inline void locallog() const {
    374         LOC_LOGV("LocEngSetServerIpv4 - addr: %x, port: %d, type: %s",
    375                  mNlAddr, mPort, loc_get_server_type_name(mServerType));
    376     }
    377     inline virtual void log() const {
    378         locallog();
    379     }
    380 };
    381 
    382 //        case LOC_ENG_MSG_SET_SERVER_URL:
    383 struct LocEngSetServerUrl : public LocMsg {
    384     LocEngAdapter* mAdapter;
    385     const int mLen;
    386     char* mUrl;
    387     inline LocEngSetServerUrl(LocEngAdapter* adapter,
    388                               char* urlString,
    389                               int url_len) :
    390         LocMsg(), mAdapter(adapter),
    391         mLen(url_len), mUrl(new char[mLen+1])
    392     {
    393         memcpy((void*)mUrl, (void*)urlString, url_len);
    394         mUrl[mLen] = 0;
    395         locallog();
    396     }
    397     inline ~LocEngSetServerUrl()
    398     {
    399         delete[] mUrl;
    400     }
    401     inline virtual void proc() const {
    402         mAdapter->setServer(mUrl, mLen);
    403     }
    404     inline void locallog() const {
    405         LOC_LOGV("LocEngSetServerUrl - url: %s", mUrl);
    406     }
    407     inline virtual void log() const {
    408         locallog();
    409     }
    410 };
    411 
    412 //        case LOC_ENG_MSG_A_GLONASS_PROTOCOL:
    413 struct LocEngAGlonassProtocol : public LocMsg {
    414     LocEngAdapter* mAdapter;
    415     const unsigned long mAGlonassProtocl;
    416     inline LocEngAGlonassProtocol(LocEngAdapter* adapter,
    417                                   unsigned long protocol) :
    418         LocMsg(), mAdapter(adapter), mAGlonassProtocl(protocol)
    419     {
    420         locallog();
    421     }
    422     inline virtual void proc() const {
    423         mAdapter->setAGLONASSProtocol(mAGlonassProtocl);
    424     }
    425     inline  void locallog() const {
    426         LOC_LOGV("A-GLONASS protocol: 0x%lx", mAGlonassProtocl);
    427     }
    428     inline virtual void log() const {
    429         locallog();
    430     }
    431 };
    432 
    433 //        case LOC_ENG_MSG_SUPL_VERSION:
    434 struct LocEngSuplVer : public LocMsg {
    435     LocEngAdapter* mAdapter;
    436     const int mSuplVer;
    437     inline LocEngSuplVer(LocEngAdapter* adapter,
    438                          int suplVer) :
    439         LocMsg(), mAdapter(adapter), mSuplVer(suplVer)
    440     {
    441         locallog();
    442     }
    443     inline virtual void proc() const {
    444         mAdapter->setSUPLVersion(mSuplVer);
    445     }
    446     inline  void locallog() const {
    447         LOC_LOGV("SUPL Version: %d", mSuplVer);
    448     }
    449     inline virtual void log() const {
    450         locallog();
    451     }
    452 };
    453 
    454 //        case LOC_ENG_MSG_LPP_CONFIG:
    455 struct LocEngLppConfig : public LocMsg {
    456     LocEngAdapter* mAdapter;
    457     const int mLppConfig;
    458     inline LocEngLppConfig(LocEngAdapter* adapter,
    459                            int lppConfig) :
    460         LocMsg(), mAdapter(adapter), mLppConfig(lppConfig)
    461     {
    462         locallog();
    463     }
    464     inline virtual void proc() const {
    465         mAdapter->setLPPConfig(mLppConfig);
    466     }
    467     inline void locallog() const {
    468         LOC_LOGV("LocEngLppConfig - profile: %d", mLppConfig);
    469     }
    470     inline virtual void log() const {
    471         locallog();
    472     }
    473 };
    474 
    475 //        case LOC_ENG_MSG_SET_SENSOR_CONTROL_CONFIG:
    476 struct LocEngSensorControlConfig : public LocMsg {
    477     LocEngAdapter* mAdapter;
    478     const int mSensorsDisabled;
    479     inline LocEngSensorControlConfig(LocEngAdapter* adapter,
    480                                      int sensorsDisabled) :
    481         LocMsg(), mAdapter(adapter), mSensorsDisabled(sensorsDisabled)
    482     {
    483         locallog();
    484     }
    485     inline virtual void proc() const {
    486         mAdapter->setSensorControlConfig(mSensorsDisabled);
    487     }
    488     inline  void locallog() const {
    489         LOC_LOGV("LocEngSensorControlConfig - Sensors Disabled: %d",
    490                  mSensorsDisabled);
    491     }
    492     inline virtual void log() const {
    493         locallog();
    494     }
    495 };
    496 
    497 //        case LOC_ENG_MSG_SET_SENSOR_PROPERTIES:
    498 struct LocEngSensorProperties : public LocMsg {
    499     LocEngAdapter* mAdapter;
    500     const bool mGyroBiasVarianceRandomWalkValid;
    501     const float mGyroBiasVarianceRandomWalk;
    502     const bool mAccelRandomWalkValid;
    503     const float mAccelRandomWalk;
    504     const bool mAngleRandomWalkValid;
    505     const float mAngleRandomWalk;
    506     const bool mRateRandomWalkValid;
    507     const float mRateRandomWalk;
    508     const bool mVelocityRandomWalkValid;
    509     const float mVelocityRandomWalk;
    510     inline LocEngSensorProperties(LocEngAdapter* adapter,
    511                                   bool gyroBiasRandomWalk_valid,
    512                                   float gyroBiasRandomWalk,
    513                                   bool accelRandomWalk_valid,
    514                                   float accelRandomWalk,
    515                                   bool angleRandomWalk_valid,
    516                                   float angleRandomWalk,
    517                                   bool rateRandomWalk_valid,
    518                                   float rateRandomWalk,
    519                                   bool velocityRandomWalk_valid,
    520                                   float velocityRandomWalk) :
    521         LocMsg(), mAdapter(adapter),
    522         mGyroBiasVarianceRandomWalkValid(gyroBiasRandomWalk_valid),
    523         mGyroBiasVarianceRandomWalk(gyroBiasRandomWalk),
    524         mAccelRandomWalkValid(accelRandomWalk_valid),
    525         mAccelRandomWalk(accelRandomWalk),
    526         mAngleRandomWalkValid(angleRandomWalk_valid),
    527         mAngleRandomWalk(angleRandomWalk),
    528         mRateRandomWalkValid(rateRandomWalk_valid),
    529         mRateRandomWalk(rateRandomWalk),
    530         mVelocityRandomWalkValid(velocityRandomWalk_valid),
    531         mVelocityRandomWalk(velocityRandomWalk)
    532     {
    533         locallog();
    534     }
    535     inline virtual void proc() const {
    536         mAdapter->setSensorProperties(mGyroBiasVarianceRandomWalkValid,
    537                                       mGyroBiasVarianceRandomWalk,
    538                                       mAccelRandomWalkValid,
    539                                       mAccelRandomWalk,
    540                                       mAngleRandomWalkValid,
    541                                       mAngleRandomWalk,
    542                                       mRateRandomWalkValid,
    543                                       mRateRandomWalk,
    544                                       mVelocityRandomWalkValid,
    545                                       mVelocityRandomWalk);
    546     }
    547     inline  void locallog() const {
    548         LOC_LOGV("Sensor properties validity, Gyro Random walk: %d "
    549                  "Accel Random Walk: %d "
    550                  "Angle Random Walk: %d Rate Random Walk: %d "
    551                  "Velocity Random Walk: %d\n"
    552                  "Sensor properties, Gyro Random walk: %f "
    553                  "Accel Random Walk: %f "
    554                  "Angle Random Walk: %f Rate Random Walk: %f "
    555                  "Velocity Random Walk: %f",
    556                  mGyroBiasVarianceRandomWalkValid,
    557                  mAccelRandomWalkValid,
    558                  mAngleRandomWalkValid,
    559                  mRateRandomWalkValid,
    560                  mVelocityRandomWalkValid,
    561                  mGyroBiasVarianceRandomWalk,
    562                  mAccelRandomWalk,
    563                  mAngleRandomWalk,
    564                  mRateRandomWalk,
    565                  mVelocityRandomWalk
    566             );
    567     }
    568     inline virtual void log() const {
    569         locallog();
    570     }
    571 };
    572 
    573 //        case LOC_ENG_MSG_SET_SENSOR_PERF_CONTROL_CONFIG:
    574 struct LocEngSensorPerfControlConfig : public LocMsg {
    575     LocEngAdapter* mAdapter;
    576     const int mControlMode;
    577     const int mAccelSamplesPerBatch;
    578     const int mAccelBatchesPerSec;
    579     const int mGyroSamplesPerBatch;
    580     const int mGyroBatchesPerSec;
    581     const int mAccelSamplesPerBatchHigh;
    582     const int mAccelBatchesPerSecHigh;
    583     const int mGyroSamplesPerBatchHigh;
    584     const int mGyroBatchesPerSecHigh;
    585     const int mAlgorithmConfig;
    586     inline LocEngSensorPerfControlConfig(LocEngAdapter* adapter,
    587                                          int controlMode,
    588                                          int accelSamplesPerBatch,
    589                                          int accelBatchesPerSec,
    590                                          int gyroSamplesPerBatch,
    591                                          int gyroBatchesPerSec,
    592                                          int accelSamplesPerBatchHigh,
    593                                          int accelBatchesPerSecHigh,
    594                                          int gyroSamplesPerBatchHigh,
    595                                          int gyroBatchesPerSecHigh,
    596                                          int algorithmConfig) :
    597         LocMsg(), mAdapter(adapter),
    598         mControlMode(controlMode),
    599         mAccelSamplesPerBatch(accelSamplesPerBatch),
    600         mAccelBatchesPerSec(accelBatchesPerSec),
    601         mGyroSamplesPerBatch(gyroSamplesPerBatch),
    602         mGyroBatchesPerSec(gyroBatchesPerSec),
    603         mAccelSamplesPerBatchHigh(accelSamplesPerBatchHigh),
    604         mAccelBatchesPerSecHigh(accelBatchesPerSecHigh),
    605         mGyroSamplesPerBatchHigh(gyroSamplesPerBatchHigh),
    606         mGyroBatchesPerSecHigh(gyroBatchesPerSecHigh),
    607         mAlgorithmConfig(algorithmConfig)
    608     {
    609         locallog();
    610     }
    611     inline virtual void proc() const {
    612         mAdapter->setSensorPerfControlConfig(mControlMode,
    613                                              mAccelSamplesPerBatch,
    614                                              mAccelBatchesPerSec,
    615                                              mGyroSamplesPerBatch,
    616                                              mGyroBatchesPerSec,
    617                                              mAccelSamplesPerBatchHigh,
    618                                              mAccelBatchesPerSecHigh,
    619                                              mGyroSamplesPerBatchHigh,
    620                                              mGyroBatchesPerSecHigh,
    621                                              mAlgorithmConfig);
    622     }
    623     inline void locallog() const {
    624         LOC_LOGV("Sensor Perf Control Config (performanceControlMode)(%u) "
    625                  "accel(#smp,#batches) (%u,%u) "
    626                  "gyro(#smp,#batches) (%u,%u), "
    627                  "accel_high(#smp,#batches) (%u,%u) "
    628                  "gyro_high(#smp,#batches) (%u,%u), "
    629                  "algorithmConfig(%u)\n",
    630                  mControlMode,
    631                  mAccelSamplesPerBatch, mAccelBatchesPerSec,
    632                  mGyroSamplesPerBatch, mGyroBatchesPerSec,
    633                  mAccelSamplesPerBatchHigh, mAccelBatchesPerSecHigh,
    634                  mGyroSamplesPerBatchHigh, mGyroBatchesPerSecHigh,
    635                  mAlgorithmConfig);
    636     }
    637     inline virtual void log() const {
    638         locallog();
    639     }
    640 };
    641 
    642 //        case LOC_ENG_MSG_EXT_POWER_CONFIG:
    643 struct LocEngExtPowerConfig : public LocMsg {
    644     LocEngAdapter* mAdapter;
    645     const int mIsBatteryCharging;
    646     inline LocEngExtPowerConfig(LocEngAdapter* adapter,
    647                                 int isBatteryCharging) :
    648         LocMsg(), mAdapter(adapter),
    649         mIsBatteryCharging(isBatteryCharging)
    650     {
    651         locallog();
    652     }
    653     inline virtual void proc() const {
    654         mAdapter->setExtPowerConfig(mIsBatteryCharging);
    655     }
    656     inline void locallog() const {
    657         LOC_LOGV("LocEngExtPowerConfig - isBatteryCharging: %d",
    658                  mIsBatteryCharging);
    659     }
    660     inline virtual void log() const {
    661         locallog();
    662     }
    663 };
    664 
    665 //        case LOC_ENG_MSG_REPORT_POSITION:
    666 LocEngReportPosition::LocEngReportPosition(LocAdapterBase* adapter,
    667                                            UlpLocation &loc,
    668                                            GpsLocationExtended &locExtended,
    669                                            void* locExt,
    670                                            enum loc_sess_status st,
    671                                            LocPosTechMask technology) :
    672     LocMsg(), mAdapter(adapter), mLocation(loc),
    673     mLocationExtended(locExtended),
    674     mLocationExt(((loc_eng_data_s_type*)
    675                   ((LocEngAdapter*)
    676                    (mAdapter))->getOwner())->location_ext_parser(locExt)),
    677     mStatus(st), mTechMask(technology)
    678 {
    679     locallog();
    680 }
    681 void LocEngReportPosition::proc() const {
    682     LocEngAdapter* adapter = (LocEngAdapter*)mAdapter;
    683     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)adapter->getOwner();
    684 
    685     if (locEng->mute_session_state != LOC_MUTE_SESS_IN_SESSION) {
    686         bool reported = false;
    687         if (locEng->location_cb != NULL) {
    688             if (LOC_SESS_FAILURE == mStatus) {
    689                 // in case we want to handle the failure case
    690                 locEng->location_cb(NULL, NULL);
    691                 reported = true;
    692             }
    693             // what's in the else if is... (line by line)
    694             // 1. this is a final fix; and
    695             //   1.1 it is a Satellite fix; or
    696             //   1.2 it is a sensor fix
    697             // 2. (must be intermediate fix... implicit)
    698             //   2.1 we accepte intermediate; and
    699             //   2.2 it is NOT the case that
    700             //   2.2.1 there is inaccuracy; and
    701             //   2.2.2 we care about inaccuracy; and
    702             //   2.2.3 the inaccuracy exceeds our tolerance
    703             else if ((LOC_SESS_SUCCESS == mStatus &&
    704                       ((LOC_POS_TECH_MASK_SATELLITE |
    705                         LOC_POS_TECH_MASK_SENSORS) &
    706                        mTechMask)) ||
    707                      (LOC_SESS_INTERMEDIATE == locEng->intermediateFix &&
    708                       !((mLocation.gpsLocation.flags &
    709                          GPS_LOCATION_HAS_ACCURACY) &&
    710                         (gps_conf.ACCURACY_THRES != 0) &&
    711                         (mLocation.gpsLocation.accuracy >
    712                          gps_conf.ACCURACY_THRES)))) {
    713                 locEng->location_cb((UlpLocation*)&(mLocation),
    714                                     (void*)mLocationExt);
    715                 reported = true;
    716             }
    717         }
    718 
    719         // if we have reported this fix
    720         if (reported &&
    721             // and if this is a singleshot
    722             GPS_POSITION_RECURRENCE_SINGLE ==
    723             locEng->adapter->getPositionMode().recurrence) {
    724             if (LOC_SESS_INTERMEDIATE == mStatus) {
    725                 // modem could be still working for a final fix,
    726                 // although we no longer need it.  So stopFix().
    727                 locEng->adapter->stopFix();
    728             }
    729             // turn off the session flag.
    730             locEng->adapter->setInSession(false);
    731         }
    732 
    733         if (locEng->generateNmea &&
    734             mLocation.position_source == ULP_LOCATION_IS_FROM_GNSS)
    735         {
    736             unsigned char generate_nmea = reported &&
    737                                           (mStatus != LOC_SESS_FAILURE);
    738             loc_eng_nmea_generate_pos(locEng, mLocation, mLocationExtended,
    739                                       generate_nmea);
    740         }
    741 
    742         // Free the allocated memory for rawData
    743         UlpLocation* gp = (UlpLocation*)&(mLocation);
    744         if (gp != NULL && gp->rawData != NULL)
    745         {
    746             delete (char*)gp->rawData;
    747             gp->rawData = NULL;
    748             gp->rawDataSize = 0;
    749         }
    750     }
    751 }
    752 void LocEngReportPosition::locallog() const {
    753     LOC_LOGV("flags: %d\n  source: %d\n  latitude: %f\n  longitude: %f\n  "
    754              "altitude: %f\n  speed: %f\n  bearing: %f\n  accuracy: %f\n  "
    755              "timestamp: %lld\n  rawDataSize: %d\n  rawData: %p\n  Session"
    756              " status: %d\n Technology mask: %u",
    757              mLocation.gpsLocation.flags, mLocation.position_source,
    758              mLocation.gpsLocation.latitude, mLocation.gpsLocation.longitude,
    759              mLocation.gpsLocation.altitude, mLocation.gpsLocation.speed,
    760              mLocation.gpsLocation.bearing, mLocation.gpsLocation.accuracy,
    761              mLocation.gpsLocation.timestamp, mLocation.rawDataSize,
    762              mLocation.rawData, mStatus, mTechMask);
    763 }
    764 void LocEngReportPosition::log() const {
    765     locallog();
    766 }
    767 void LocEngReportPosition::send() const {
    768     mAdapter->sendMsg(this);
    769 }
    770 
    771 
    772 //        case LOC_ENG_MSG_REPORT_SV:
    773 LocEngReportSv::LocEngReportSv(LocAdapterBase* adapter,
    774                                GpsSvStatus &sv,
    775                                GpsLocationExtended &locExtended,
    776                                void* svExt) :
    777     LocMsg(), mAdapter(adapter), mSvStatus(sv),
    778     mLocationExtended(locExtended),
    779     mSvExt(((loc_eng_data_s_type*)
    780             ((LocEngAdapter*)
    781              (mAdapter))->getOwner())->sv_ext_parser(svExt))
    782 {
    783     locallog();
    784 }
    785 void LocEngReportSv::proc() const {
    786     LocEngAdapter* adapter = (LocEngAdapter*)mAdapter;
    787     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)adapter->getOwner();
    788 
    789     if (locEng->mute_session_state != LOC_MUTE_SESS_IN_SESSION)
    790     {
    791         if (locEng->sv_status_cb != NULL) {
    792             locEng->sv_status_cb((GpsSvStatus*)&(mSvStatus),
    793                                  (void*)mSvExt);
    794         }
    795 
    796         if (locEng->generateNmea)
    797         {
    798             loc_eng_nmea_generate_sv(locEng, mSvStatus, mLocationExtended);
    799         }
    800     }
    801 }
    802 void LocEngReportSv::locallog() const {
    803     LOC_LOGV("num sv: %d\n  ephemeris mask: %dxn  almanac mask: %x\n  "
    804              "used in fix mask: %x\n      sv: prn         snr       "
    805              "elevation      azimuth",
    806              mSvStatus.num_svs, mSvStatus.ephemeris_mask,
    807              mSvStatus.almanac_mask, mSvStatus.used_in_fix_mask);
    808     for (int i = 0; i < mSvStatus.num_svs && i < GPS_MAX_SVS; i++) {
    809         LOC_LOGV("   %d:   %d    %f    %f    %f\n  ",
    810                  i,
    811                  mSvStatus.sv_list[i].prn,
    812                  mSvStatus.sv_list[i].snr,
    813                  mSvStatus.sv_list[i].elevation,
    814                  mSvStatus.sv_list[i].azimuth);
    815     }
    816 }
    817 inline void LocEngReportSv::log() const {
    818     locallog();
    819 }
    820 void LocEngReportSv::send() const {
    821     mAdapter->sendMsg(this);
    822 }
    823 
    824 //        case LOC_ENG_MSG_REPORT_STATUS:
    825 LocEngReportStatus::LocEngReportStatus(void* locEng,
    826                                        GpsStatusValue engineStatus) :
    827     LocMsg(),  mLocEng(locEng), mStatus(engineStatus)
    828 {
    829     locallog();
    830 }
    831 inline void LocEngReportStatus::proc() const
    832 {
    833     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*) mLocEng;
    834 
    835     loc_eng_report_status(*locEng, mStatus);
    836     update_aiding_data_for_deletion(*locEng);
    837 }
    838 inline void LocEngReportStatus::locallog() const {
    839     LOC_LOGV("LocEngReportStatus");
    840 }
    841 inline void LocEngReportStatus::log() const {
    842     locallog();
    843 }
    844 
    845 //        case LOC_ENG_MSG_REPORT_NMEA:
    846 LocEngReportNmea::LocEngReportNmea(void* locEng,
    847                                    const char* data, int len) :
    848     LocMsg(), mLocEng(locEng), mNmea(new char[len]), mLen(len)
    849 {
    850     memcpy((void*)mNmea, (void*)data, len);
    851     locallog();
    852 }
    853 void LocEngReportNmea::proc() const {
    854     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*) mLocEng;
    855 
    856     struct timeval tv;
    857     gettimeofday(&tv, (struct timezone *) NULL);
    858     int64_t now = tv.tv_sec * 1000LL + tv.tv_usec / 1000;
    859     CALLBACK_LOG_CALLFLOW("nmea_cb", %d, mLen);
    860     locEng->nmea_cb(now, mNmea, mLen);
    861 }
    862 inline void LocEngReportNmea::locallog() const {
    863     LOC_LOGV("LocEngReportNmea");
    864 }
    865 inline void LocEngReportNmea::log() const {
    866     locallog();
    867 }
    868 
    869 //        case LOC_ENG_MSG_REPORT_XTRA_SERVER:
    870 LocEngReportXtraServer::LocEngReportXtraServer(void* locEng,
    871                                                const char *url1,
    872                                                const char *url2,
    873                                                const char *url3,
    874                                                const int maxlength) :
    875     LocMsg(), mLocEng(locEng), mMaxLen(maxlength),
    876     mServers(new char[3*(mMaxLen+1)])
    877 {
    878     strlcpy(mServers, url1, mMaxLen);
    879     strlcpy(&(mServers[mMaxLen+1]), url2, mMaxLen);
    880     strlcpy(&(mServers[(mMaxLen+1)<<1]), url3, mMaxLen);
    881     locallog();
    882 }
    883 void LocEngReportXtraServer::proc() const {
    884     loc_eng_xtra_data_s_type* locEngXtra =
    885         &(((loc_eng_data_s_type*)mLocEng)->xtra_module_data);
    886 
    887     if (locEngXtra->report_xtra_server_cb != NULL) {
    888         CALLBACK_LOG_CALLFLOW("report_xtra_server_cb", %s, mServers);
    889         locEngXtra->report_xtra_server_cb(mServers,
    890                                           &(mServers[mMaxLen+1]),
    891                                           &(mServers[(mMaxLen+1)<<1]));
    892     } else {
    893         LOC_LOGE("Callback function for request xtra is NULL");
    894     }
    895 }
    896 inline void LocEngReportXtraServer::locallog() const {
    897     LOC_LOGV("LocEngReportXtraServers: server1: %s\n  server2: %s\n"
    898              "  server3: %s\n",
    899              mServers, &mServers[mMaxLen], &mServers[mMaxLen<<1]);
    900 }
    901 inline void LocEngReportXtraServer::log() const {
    902     locallog();
    903 }
    904 
    905 //        case LOC_ENG_MSG_REQUEST_BIT:
    906 //        case LOC_ENG_MSG_RELEASE_BIT:
    907 LocEngReqRelBIT::LocEngReqRelBIT(void* locEng, AGpsExtType type,
    908                                  int ipv4, char* ipv6, bool isReq) :
    909     LocMsg(), mLocEng(locEng), mType(type), mIPv4Addr(ipv4),
    910     mIPv6Addr(ipv6 ? new char[16] : NULL), mIsReq(isReq) {
    911     if (NULL != ipv6)
    912         memcpy(mIPv6Addr, ipv6, 16);
    913     locallog();
    914 }
    915 inline LocEngReqRelBIT::~LocEngReqRelBIT() {
    916     if (mIPv6Addr) {
    917         delete[] mIPv6Addr;
    918     }
    919 }
    920 void LocEngReqRelBIT::proc() const {
    921     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
    922     BITSubscriber s(getAgpsStateMachine(*locEng, mType),
    923                     mIPv4Addr, mIPv6Addr);
    924     AgpsStateMachine* sm = (AgpsStateMachine*)s.mStateMachine;
    925 
    926     if (mIsReq) {
    927         sm->subscribeRsrc((Subscriber*)&s);
    928     } else {
    929         sm->unsubscribeRsrc((Subscriber*)&s);
    930     }
    931 }
    932 inline void LocEngReqRelBIT::locallog() const {
    933     LOC_LOGV("LocEngRequestBIT - ipv4: %d.%d.%d.%d, ipv6: %s",
    934              (unsigned char)(mIPv4Addr>>24),
    935              (unsigned char)(mIPv4Addr>>16),
    936              (unsigned char)(mIPv4Addr>>8),
    937              (unsigned char)mIPv4Addr,
    938              NULL != mIPv6Addr ? mIPv6Addr : "");
    939 }
    940 inline void LocEngReqRelBIT::log() const {
    941     locallog();
    942 }
    943 void LocEngReqRelBIT::send() const {
    944     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
    945     locEng->adapter->sendMsg(this);
    946 }
    947 
    948 //        case LOC_ENG_MSG_RELEASE_BIT:
    949 struct LocEngReleaseBIT : public LocMsg {
    950     const BITSubscriber mSubscriber;
    951     inline LocEngReleaseBIT(const AgpsStateMachine* stateMachine,
    952                             unsigned int ipv4, char* ipv6) :
    953         LocMsg(),
    954         mSubscriber(stateMachine, ipv4, ipv6)
    955     {
    956         locallog();
    957     }
    958     inline virtual void proc() const
    959     {
    960         AgpsStateMachine* sm = (AgpsStateMachine*)mSubscriber.mStateMachine;
    961         sm->unsubscribeRsrc((Subscriber*)&mSubscriber);
    962     }
    963     inline void locallog() const {
    964         LOC_LOGV("LocEngReleaseBIT - ipv4: %d.%d.%d.%d, ipv6: %s",
    965                  (unsigned char)(mSubscriber.ID>>24),
    966                  (unsigned char)(mSubscriber.ID>>16),
    967                  (unsigned char)(mSubscriber.ID>>8),
    968                  (unsigned char)mSubscriber.ID,
    969                  NULL != mSubscriber.mIPv6Addr ? mSubscriber.mIPv6Addr : "");
    970     }
    971     virtual void log() const {
    972         locallog();
    973     }
    974 };
    975 
    976 //        LocEngSuplEsOpened
    977 LocEngSuplEsOpened::LocEngSuplEsOpened(void* locEng) :
    978     LocMsg(), mLocEng(locEng) {
    979     locallog();
    980 }
    981 void LocEngSuplEsOpened::proc() const {
    982     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
    983     AgpsStateMachine* sm = locEng->ds_nif;
    984     sm->onRsrcEvent(RSRC_GRANTED);
    985 }
    986 void LocEngSuplEsOpened::locallog() const {
    987     LOC_LOGV("LocEngSuplEsOpened");
    988 }
    989 void LocEngSuplEsOpened::log() const {
    990     locallog();
    991 }
    992 
    993 //        LocEngSuplEsClosed
    994 LocEngSuplEsClosed::LocEngSuplEsClosed(void* locEng) :
    995     LocMsg(), mLocEng(locEng) {
    996     locallog();
    997 }
    998 void LocEngSuplEsClosed::proc() const {
    999     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
   1000     AgpsStateMachine* sm = locEng->ds_nif;
   1001     sm->onRsrcEvent(RSRC_RELEASED);
   1002 }
   1003 void LocEngSuplEsClosed::locallog() const {
   1004     LOC_LOGV("LocEngSuplEsClosed");
   1005 }
   1006 void LocEngSuplEsClosed::log() const {
   1007     locallog();
   1008 }
   1009 
   1010 
   1011 //        case LOC_ENG_MSG_REQUEST_SUPL_ES:
   1012 LocEngRequestSuplEs::LocEngRequestSuplEs(void* locEng, int id) :
   1013     LocMsg(), mLocEng(locEng), mID(id) {
   1014     locallog();
   1015 }
   1016 void LocEngRequestSuplEs::proc() const {
   1017     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
   1018     AgpsStateMachine* sm = locEng->ds_nif;
   1019     DSSubscriber s(sm, mID);
   1020     sm->subscribeRsrc((Subscriber*)&s);
   1021 }
   1022 inline void LocEngRequestSuplEs::locallog() const {
   1023     LOC_LOGV("LocEngRequestSuplEs");
   1024 }
   1025 inline void LocEngRequestSuplEs::log() const {
   1026     locallog();
   1027 }
   1028 
   1029 //        case LOC_ENG_MSG_REQUEST_ATL:
   1030 LocEngRequestATL::LocEngRequestATL(void* locEng, int id,
   1031                                    AGpsExtType agps_type) :
   1032     LocMsg(), mLocEng(locEng), mID(id), mType(agps_type) {
   1033     locallog();
   1034 }
   1035 void LocEngRequestATL::proc() const {
   1036     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
   1037     AgpsStateMachine* sm = (AgpsStateMachine*)
   1038                            getAgpsStateMachine(*locEng, mType);
   1039     ATLSubscriber s(mID,
   1040                     sm,
   1041                     locEng->adapter,
   1042                     AGPS_TYPE_INVALID == mType);
   1043     sm->subscribeRsrc((Subscriber*)&s);
   1044 }
   1045 inline void LocEngRequestATL::locallog() const {
   1046     LOC_LOGV("LocEngRequestATL");
   1047 }
   1048 inline void LocEngRequestATL::log() const {
   1049     locallog();
   1050 }
   1051 
   1052 //        case LOC_ENG_MSG_RELEASE_ATL:
   1053 LocEngReleaseATL::LocEngReleaseATL(void* locEng, int id) :
   1054     LocMsg(), mLocEng(locEng), mID(id) {
   1055     locallog();
   1056 }
   1057 void LocEngReleaseATL::proc() const {
   1058     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
   1059     ATLSubscriber s1(mID, locEng->agnss_nif, locEng->adapter, false);
   1060     if (locEng->agnss_nif->unsubscribeRsrc((Subscriber*)&s1)) {
   1061         LOC_LOGD("%s:%d]: Unsubscribed from agnss_nif",
   1062                  __func__, __LINE__);
   1063     } else {
   1064         ATLSubscriber s2(mID, locEng->internet_nif, locEng->adapter, false);
   1065         if (locEng->internet_nif->unsubscribeRsrc((Subscriber*)&s2)) {
   1066             LOC_LOGD("%s:%d]: Unsubscribed from internet_nif",
   1067                      __func__, __LINE__);
   1068         } else {
   1069             DSSubscriber s3(locEng->ds_nif, mID);
   1070             if(locEng->ds_nif->unsubscribeRsrc((Subscriber*)&s3)) {
   1071                 LOC_LOGD("%s:%d]: Unsubscribed from ds_nif",
   1072                          __func__, __LINE__);
   1073             } else {
   1074                 LOC_LOGW("%s:%d]: Could not release ATL. "
   1075                          "No subscribers found\n",
   1076                          __func__, __LINE__);
   1077                 locEng->adapter->atlCloseStatus(mID, 0);
   1078             }
   1079         }
   1080     }
   1081 }
   1082 inline void LocEngReleaseATL::locallog() const {
   1083     LOC_LOGV("LocEngReleaseATL");
   1084 }
   1085 inline void LocEngReleaseATL::log() const {
   1086     locallog();
   1087 }
   1088 
   1089 //        case LOC_ENG_MSG_REQUEST_WIFI:
   1090 //        case LOC_ENG_MSG_RELEASE_WIFI:
   1091 LocEngReqRelWifi::LocEngReqRelWifi(void* locEng, AGpsExtType type,
   1092                                    loc_if_req_sender_id_e_type sender_id,
   1093                                    char* s, char* p, bool isReq) :
   1094     LocMsg(), mLocEng(locEng), mType(type), mSenderId(sender_id),
   1095     mSSID(NULL == s ? NULL : new char[SSID_BUF_SIZE]),
   1096     mPassword(NULL == p ? NULL : new char[SSID_BUF_SIZE]),
   1097     mIsReq(isReq) {
   1098     if (NULL != s)
   1099         strlcpy(mSSID, s, SSID_BUF_SIZE);
   1100     if (NULL != p)
   1101         strlcpy(mPassword, p, SSID_BUF_SIZE);
   1102     locallog();
   1103 }
   1104 LocEngReqRelWifi::~LocEngReqRelWifi() {
   1105     if (NULL != mSSID) {
   1106         delete[] mSSID;
   1107     }
   1108     if (NULL != mPassword) {
   1109         delete[] mPassword;
   1110     }
   1111 }
   1112 void LocEngReqRelWifi::proc() const {
   1113     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
   1114     WIFISubscriber s(locEng->wifi_nif, mSSID, mPassword, mSenderId);
   1115     if (mIsReq) {
   1116         locEng->wifi_nif->subscribeRsrc((Subscriber*)&s);
   1117     } else {
   1118         locEng->wifi_nif->unsubscribeRsrc((Subscriber*)&s);
   1119     }
   1120 }
   1121 inline void LocEngReqRelWifi::locallog() const {
   1122     LOC_LOGV("%s - senderId: %d, ssid: %s, password: %s",
   1123              mIsReq ? "LocEngRequestWifi" : "LocEngReleaseWifi",
   1124              mSenderId,
   1125              NULL != mSSID ? mSSID : "",
   1126              NULL != mPassword ? mPassword : "");
   1127 }
   1128 inline void LocEngReqRelWifi::log() const {
   1129     locallog();
   1130 }
   1131 void LocEngReqRelWifi::send() const {
   1132     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
   1133     locEng->adapter->sendMsg(this);
   1134 }
   1135 
   1136 //        case LOC_ENG_MSG_REQUEST_XTRA_DATA:
   1137 LocEngRequestXtra::LocEngRequestXtra(void* locEng) :
   1138     mLocEng(locEng) {
   1139     locallog();
   1140 }
   1141 void LocEngRequestXtra::proc() const
   1142 {
   1143     loc_eng_xtra_data_s_type* locEngXtra =
   1144         &(((loc_eng_data_s_type*)mLocEng)->xtra_module_data);
   1145 
   1146     if (locEngXtra->download_request_cb != NULL) {
   1147         CALLBACK_LOG_CALLFLOW("download_request_cb", %p, mLocEng);
   1148         locEngXtra->download_request_cb();
   1149     } else {
   1150         LOC_LOGE("Callback function for request xtra is NULL");
   1151     }
   1152 }
   1153 inline void LocEngRequestXtra::locallog() const {
   1154     LOC_LOGV("LocEngReqXtra");
   1155 }
   1156 inline void LocEngRequestXtra::log() const {
   1157     locallog();
   1158 }
   1159 
   1160 //        case LOC_ENG_MSG_REQUEST_TIME:
   1161 LocEngRequestTime::LocEngRequestTime(void* locEng) :
   1162     LocMsg(), mLocEng(locEng)
   1163 {
   1164     locallog();
   1165 }
   1166 void LocEngRequestTime::proc() const {
   1167     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
   1168     if (locEng->request_utc_time_cb != NULL) {
   1169         locEng->request_utc_time_cb();
   1170     } else {
   1171         LOC_LOGE("Callback function for request time is NULL");
   1172     }
   1173 }
   1174 inline void LocEngRequestTime::locallog() const {
   1175     LOC_LOGV("LocEngReqTime");
   1176 }
   1177 inline void LocEngRequestTime::log() const {
   1178     locallog();
   1179 }
   1180 
   1181 //        case LOC_ENG_MSG_DELETE_AIDING_DATA:
   1182 struct LocEngDelAidData : public LocMsg {
   1183     loc_eng_data_s_type* mLocEng;
   1184     const GpsAidingData mType;
   1185     inline LocEngDelAidData(loc_eng_data_s_type* locEng,
   1186                             GpsAidingData f) :
   1187         LocMsg(), mLocEng(locEng), mType(f)
   1188     {
   1189         locallog();
   1190     }
   1191     inline virtual void proc() const {
   1192         mLocEng->aiding_data_for_deletion = mType;
   1193         update_aiding_data_for_deletion(*mLocEng);
   1194     }
   1195     inline void locallog() const {
   1196         LOC_LOGV("aiding data msak %d", mType);
   1197     }
   1198     virtual void log() const {
   1199         locallog();
   1200     }
   1201 };
   1202 
   1203 //        case LOC_ENG_MSG_ENABLE_DATA:
   1204 struct LocEngEnableData : public LocMsg {
   1205     LocEngAdapter* mAdapter;
   1206     const int mEnable;
   1207     char* mAPN;
   1208     const int mLen;
   1209     inline LocEngEnableData(LocEngAdapter* adapter,
   1210                             const char* name, int len, int enable) :
   1211         LocMsg(), mAdapter(adapter),
   1212         mEnable(enable), mAPN(NULL), mLen(len)
   1213     {
   1214         if (NULL != name) {
   1215             mAPN = new char[len+1];
   1216             memcpy((void*)mAPN, (void*)name, len);
   1217             mAPN[len] = 0;
   1218         }
   1219         locallog();
   1220     }
   1221     inline ~LocEngEnableData() {
   1222         if (NULL != mAPN) {
   1223             delete[] mAPN;
   1224         }
   1225     }
   1226     inline virtual void proc() const {
   1227         mAdapter->enableData(mEnable);
   1228         if (NULL != mAPN) {
   1229             mAdapter->setAPN(mAPN, mLen);
   1230         }
   1231     }
   1232     inline void locallog() const {
   1233         LOC_LOGV("apn: %s\n  enable: %d",
   1234                  (NULL == mAPN) ? "NULL" : mAPN, mEnable);
   1235     }
   1236     inline virtual void log() const {
   1237         locallog();
   1238     }
   1239 };
   1240 
   1241 //        case LOC_ENG_MSG_INJECT_XTRA_DATA:
   1242 // loc_eng_xtra.cpp
   1243 
   1244 //        case LOC_ENG_MSG_LOC_INIT:
   1245 struct LocEngInit : public LocMsg {
   1246     loc_eng_data_s_type* mLocEng;
   1247     inline LocEngInit(loc_eng_data_s_type* locEng) :
   1248         LocMsg(), mLocEng(locEng)
   1249     {
   1250         locallog();
   1251     }
   1252     inline virtual void proc() const {
   1253         loc_eng_reinit(*mLocEng);
   1254     }
   1255     inline void locallog() const
   1256     {
   1257         LOC_LOGV("LocEngInit");
   1258     }
   1259     inline virtual void log() const
   1260     {
   1261         locallog();
   1262     }
   1263 };
   1264 
   1265 //        case LOC_ENG_MSG_REQUEST_XTRA_SERVER:
   1266 // loc_eng_xtra.cpp
   1267 
   1268 //        case LOC_ENG_MSG_ATL_OPEN_SUCCESS:
   1269 struct LocEngAtlOpenSuccess : public LocMsg {
   1270     AgpsStateMachine* mStateMachine;
   1271     const int mLen;
   1272     char* mAPN;
   1273     const AGpsBearerType mBearerType;
   1274     inline LocEngAtlOpenSuccess(AgpsStateMachine* statemachine,
   1275                                 const char* name,
   1276                                 int len,
   1277                                 AGpsBearerType btype) :
   1278         LocMsg(),
   1279         mStateMachine(statemachine), mLen(len),
   1280         mAPN(new char[len+1]), mBearerType(btype)
   1281     {
   1282         memcpy((void*)mAPN, (void*)name, len);
   1283         mAPN[len] = 0;
   1284         locallog();
   1285     }
   1286     inline ~LocEngAtlOpenSuccess()
   1287     {
   1288         delete[] mAPN;
   1289     }
   1290     inline virtual void proc() const {
   1291         mStateMachine->setBearer(mBearerType);
   1292         mStateMachine->setAPN(mAPN, mLen);
   1293         mStateMachine->onRsrcEvent(RSRC_GRANTED);
   1294     }
   1295     inline void locallog() const {
   1296         LOC_LOGV("LocEngAtlClosed agps type: %s\n  apn: %s\n"
   1297                  "  bearer type: %s",
   1298                  loc_get_agps_type_name(mStateMachine->getType()),
   1299                  mAPN,
   1300                  loc_get_agps_bear_name(mBearerType));
   1301     }
   1302     inline virtual void log() const {
   1303         locallog();
   1304     }
   1305 };
   1306 
   1307 //        case LOC_ENG_MSG_ATL_CLOSED:
   1308 struct LocEngAtlClosed : public LocMsg {
   1309     AgpsStateMachine* mStateMachine;
   1310     inline LocEngAtlClosed(AgpsStateMachine* statemachine) :
   1311         LocMsg(), mStateMachine(statemachine) {
   1312         locallog();
   1313     }
   1314     inline virtual void proc() const {
   1315         mStateMachine->onRsrcEvent(RSRC_RELEASED);
   1316     }
   1317     inline void locallog() const {
   1318         LOC_LOGV("LocEngAtlClosed");
   1319     }
   1320     inline virtual void log() const {
   1321         locallog();
   1322     }
   1323 };
   1324 
   1325 //        case LOC_ENG_MSG_ATL_OPEN_FAILED:
   1326 struct LocEngAtlOpenFailed : public LocMsg {
   1327     AgpsStateMachine* mStateMachine;
   1328     inline LocEngAtlOpenFailed(AgpsStateMachine* statemachine) :
   1329         LocMsg(), mStateMachine(statemachine) {
   1330         locallog();
   1331     }
   1332     inline virtual void proc() const {
   1333         mStateMachine->onRsrcEvent(RSRC_DENIED);
   1334     }
   1335     inline void locallog() const {
   1336         LOC_LOGV("LocEngAtlOpenFailed");
   1337     }
   1338     inline virtual void log() const {
   1339         locallog();
   1340     }
   1341 };
   1342 
   1343 //        case LOC_ENG_MSG_ENGINE_DOWN:
   1344 LocEngDown::LocEngDown(void* locEng) :
   1345     LocMsg(), mLocEng(locEng) {
   1346     locallog();
   1347 }
   1348 inline void LocEngDown::proc() const {
   1349     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
   1350     loc_eng_handle_engine_down(*locEng);
   1351 }
   1352 inline void LocEngDown::locallog() const {
   1353     LOC_LOGV("LocEngDown");
   1354 }
   1355 inline void LocEngDown::log() const {
   1356     locallog();
   1357 }
   1358 
   1359 //        case LOC_ENG_MSG_ENGINE_UP:
   1360 LocEngUp::LocEngUp(void* locEng) :
   1361     LocMsg(), mLocEng(locEng) {
   1362     locallog();
   1363 }
   1364 inline void LocEngUp::proc() const {
   1365     loc_eng_data_s_type* locEng = (loc_eng_data_s_type*)mLocEng;
   1366     loc_eng_handle_engine_up(*locEng);
   1367 }
   1368 inline void LocEngUp::locallog() const {
   1369     LOC_LOGV("LocEngUp");
   1370 }
   1371 inline void LocEngUp::log() const {
   1372     locallog();
   1373 }
   1374 
   1375 /*********************************************************************
   1376  * Initialization checking macros
   1377  *********************************************************************/
   1378 #define STATE_CHECK(ctx, x, ret) \
   1379     if (!(ctx))                  \
   1380   {                              \
   1381       /* Not intialized, abort */\
   1382       LOC_LOGE("%s: log_eng state error: %s", __func__, x); \
   1383       EXIT_LOG(%s, x);                                            \
   1384       ret;                                                        \
   1385   }
   1386 #define INIT_CHECK(ctx, ret) STATE_CHECK(ctx, "instance not initialized", ret)
   1387 
   1388 /*===========================================================================
   1389 FUNCTION    loc_eng_init
   1390 
   1391 DESCRIPTION
   1392    Initialize the location engine, this include setting up global datas
   1393    and registers location engien with loc api service.
   1394 
   1395 DEPENDENCIES
   1396    None
   1397 
   1398 RETURN VALUE
   1399    0: success
   1400 
   1401 SIDE EFFECTS
   1402    N/A
   1403 
   1404 ===========================================================================*/
   1405 int loc_eng_init(loc_eng_data_s_type &loc_eng_data, LocCallbacks* callbacks,
   1406                  LOC_API_ADAPTER_EVENT_MASK_T event)
   1407 
   1408 {
   1409     int ret_val = 0;
   1410 
   1411     ENTRY_LOG_CALLFLOW();
   1412     if (NULL == callbacks || 0 == event) {
   1413         LOC_LOGE("loc_eng_init: bad parameters cb %p eMask %d", callbacks, event);
   1414         ret_val = -1;
   1415         EXIT_LOG(%d, ret_val);
   1416         return ret_val;
   1417     }
   1418 
   1419     STATE_CHECK((NULL == loc_eng_data.adapter),
   1420                 "instance already initialized", return 0);
   1421 
   1422     memset(&loc_eng_data, 0, sizeof (loc_eng_data));
   1423 
   1424     if (NULL != callbacks->set_capabilities_cb) {
   1425         callbacks->set_capabilities_cb(gps_conf.CAPABILITIES);
   1426     }
   1427 
   1428     // Save callbacks
   1429     loc_eng_data.location_cb  = callbacks->location_cb;
   1430     loc_eng_data.sv_status_cb = callbacks->sv_status_cb;
   1431     loc_eng_data.status_cb    = callbacks->status_cb;
   1432     loc_eng_data.nmea_cb      = callbacks->nmea_cb;
   1433     loc_eng_data.acquire_wakelock_cb = callbacks->acquire_wakelock_cb;
   1434     loc_eng_data.release_wakelock_cb = callbacks->release_wakelock_cb;
   1435     loc_eng_data.request_utc_time_cb = callbacks->request_utc_time_cb;
   1436     loc_eng_data.location_ext_parser = callbacks->location_ext_parser ?
   1437         callbacks->location_ext_parser : noProc;
   1438     loc_eng_data.sv_ext_parser = callbacks->sv_ext_parser ?
   1439         callbacks->sv_ext_parser : noProc;
   1440     loc_eng_data.intermediateFix = gps_conf.INTERMEDIATE_POS;
   1441 
   1442     // initial states taken care of by the memset above
   1443     // loc_eng_data.engine_status -- GPS_STATUS_NONE;
   1444     // loc_eng_data.fix_session_status -- GPS_STATUS_NONE;
   1445     // loc_eng_data.mute_session_state -- LOC_MUTE_SESS_NONE;
   1446 
   1447     if ((event & LOC_API_ADAPTER_BIT_NMEA_1HZ_REPORT) && (gps_conf.NMEA_PROVIDER == NMEA_PROVIDER_AP))
   1448     {
   1449         event = event ^ LOC_API_ADAPTER_BIT_NMEA_1HZ_REPORT; // unregister for modem NMEA report
   1450         loc_eng_data.generateNmea = true;
   1451     }
   1452     else
   1453     {
   1454         loc_eng_data.generateNmea = false;
   1455     }
   1456 
   1457     //Disable AGPS if capabilities are not present
   1458     if(!(gps_conf.CAPABILITIES & GPS_CAPABILITY_MSA) &&
   1459        !(gps_conf.CAPABILITIES & GPS_CAPABILITY_MSB)) {
   1460         event &= ~(LOC_API_ADAPTER_BIT_LOCATION_SERVER_REQUEST |
   1461                    LOC_API_ADAPTER_BIT_NI_NOTIFY_VERIFY_REQUEST);
   1462     }
   1463 
   1464     loc_eng_data.adapter =
   1465         new LocEngAdapter(event, &loc_eng_data,
   1466                           (MsgTask::tCreate)callbacks->create_thread_cb);
   1467 
   1468     LOC_LOGD("loc_eng_init created client, id = %p\n",
   1469              loc_eng_data.adapter);
   1470 
   1471     loc_eng_data.adapter->sendMsg(new LocEngInit(&loc_eng_data));
   1472 
   1473     EXIT_LOG(%d, ret_val);
   1474     return ret_val;
   1475 }
   1476 
   1477 static int loc_eng_reinit(loc_eng_data_s_type &loc_eng_data)
   1478 {
   1479     ENTRY_LOG();
   1480     int ret_val = LOC_API_ADAPTER_ERR_SUCCESS;
   1481 
   1482     if (LOC_API_ADAPTER_ERR_SUCCESS == ret_val) {
   1483         LOC_LOGD("loc_eng_reinit reinit() successful");
   1484 
   1485         LocEngAdapter* adapter = loc_eng_data.adapter;
   1486         adapter->sendMsg(new LocEngSuplVer(adapter, gps_conf.SUPL_VER));
   1487         adapter->sendMsg(new LocEngLppConfig(adapter, gps_conf.LPP_PROFILE));
   1488         adapter->sendMsg(new LocEngSensorControlConfig(adapter, sap_conf.SENSOR_USAGE));
   1489         adapter->sendMsg(new LocEngAGlonassProtocol(adapter, gps_conf.A_GLONASS_POS_PROTOCOL_SELECT));
   1490 
   1491         /* Make sure at least one of the sensor property is specified by the user in the gps.conf file. */
   1492         if( sap_conf.GYRO_BIAS_RANDOM_WALK_VALID ||
   1493             sap_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY_VALID ||
   1494             sap_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY_VALID ||
   1495             sap_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY_VALID ||
   1496             sap_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY_VALID )
   1497         {
   1498             adapter->sendMsg(new LocEngSensorProperties(adapter,
   1499                                                         sap_conf.GYRO_BIAS_RANDOM_WALK_VALID,
   1500                                                         sap_conf.GYRO_BIAS_RANDOM_WALK,
   1501                                                         sap_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
   1502                                                         sap_conf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY,
   1503                                                         sap_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
   1504                                                         sap_conf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY,
   1505                                                         sap_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
   1506                                                         sap_conf.RATE_RANDOM_WALK_SPECTRAL_DENSITY,
   1507                                                         sap_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
   1508                                                         sap_conf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY));
   1509         }
   1510 
   1511         adapter->sendMsg(new LocEngSensorPerfControlConfig(adapter,
   1512                                                            sap_conf.SENSOR_CONTROL_MODE,
   1513                                                            sap_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH,
   1514                                                            sap_conf.SENSOR_ACCEL_BATCHES_PER_SEC,
   1515                                                            sap_conf.SENSOR_GYRO_SAMPLES_PER_BATCH,
   1516                                                            sap_conf.SENSOR_GYRO_BATCHES_PER_SEC,
   1517                                                            sap_conf.SENSOR_ACCEL_SAMPLES_PER_BATCH_HIGH,
   1518                                                            sap_conf.SENSOR_ACCEL_BATCHES_PER_SEC_HIGH,
   1519                                                            sap_conf.SENSOR_GYRO_SAMPLES_PER_BATCH_HIGH,
   1520                                                            sap_conf.SENSOR_GYRO_BATCHES_PER_SEC_HIGH,
   1521                                                            sap_conf.SENSOR_ALGORITHM_CONFIG_MASK));
   1522 
   1523         adapter->sendMsg(new LocEngEnableData(adapter, NULL, 0, (agpsStatus ? 1:0)));
   1524     }
   1525 
   1526     EXIT_LOG(%d, ret_val);
   1527     return ret_val;
   1528 }
   1529 
   1530 /*===========================================================================
   1531 FUNCTION    loc_eng_cleanup
   1532 
   1533 DESCRIPTION
   1534    Cleans location engine. The location client handle will be released.
   1535 
   1536 DEPENDENCIES
   1537    None
   1538 
   1539 RETURN VALUE
   1540    None
   1541 
   1542 SIDE EFFECTS
   1543    N/A
   1544 
   1545 ===========================================================================*/
   1546 void loc_eng_cleanup(loc_eng_data_s_type &loc_eng_data)
   1547 {
   1548     ENTRY_LOG_CALLFLOW();
   1549     INIT_CHECK(loc_eng_data.adapter, return);
   1550 
   1551     // XTRA has no state, so we are fine with it.
   1552 
   1553     // we need to check and clear NI
   1554 #if 0
   1555     // we need to check and clear ATL
   1556     if (NULL != loc_eng_data.agnss_nif) {
   1557         delete loc_eng_data.agnss_nif;
   1558         loc_eng_data.agnss_nif = NULL;
   1559     }
   1560     if (NULL != loc_eng_data.internet_nif) {
   1561         delete loc_eng_data.internet_nif;
   1562         loc_eng_data.internet_nif = NULL;
   1563     }
   1564 #endif
   1565     if (loc_eng_data.adapter->isInSession())
   1566     {
   1567         LOC_LOGD("loc_eng_cleanup: fix not stopped. stop it now.");
   1568         loc_eng_stop(loc_eng_data);
   1569     }
   1570 
   1571 #if 0 // can't afford to actually clean up, for many reason.
   1572 
   1573     LOC_LOGD("loc_eng_init: client opened. close it now.");
   1574     delete loc_eng_data.adapter;
   1575     loc_eng_data.adapter = NULL;
   1576 
   1577     loc_eng_dmn_conn_loc_api_server_unblock();
   1578     loc_eng_dmn_conn_loc_api_server_join();
   1579 
   1580 #endif
   1581 
   1582     EXIT_LOG(%s, VOID_RET);
   1583 }
   1584 
   1585 
   1586 /*===========================================================================
   1587 FUNCTION    loc_eng_start
   1588 
   1589 DESCRIPTION
   1590    Starts the tracking session
   1591 
   1592 DEPENDENCIES
   1593    None
   1594 
   1595 RETURN VALUE
   1596    0: success
   1597 
   1598 SIDE EFFECTS
   1599    N/A
   1600 
   1601 ===========================================================================*/
   1602 int loc_eng_start(loc_eng_data_s_type &loc_eng_data)
   1603 {
   1604    ENTRY_LOG_CALLFLOW();
   1605    INIT_CHECK(loc_eng_data.adapter, return -1);
   1606 
   1607    if(! loc_eng_data.adapter->getUlpProxy()->sendStartFix())
   1608    {
   1609        loc_eng_data.adapter->sendMsg(new LocEngStartFix(loc_eng_data.adapter));
   1610    }
   1611 
   1612    EXIT_LOG(%d, 0);
   1613    return 0;
   1614 }
   1615 
   1616 static int loc_eng_start_handler(loc_eng_data_s_type &loc_eng_data)
   1617 {
   1618    ENTRY_LOG();
   1619    int ret_val = LOC_API_ADAPTER_ERR_SUCCESS;
   1620 
   1621    if (!loc_eng_data.adapter->isInSession()) {
   1622        ret_val = loc_eng_data.adapter->startFix();
   1623 
   1624        if (ret_val == LOC_API_ADAPTER_ERR_SUCCESS ||
   1625            ret_val == LOC_API_ADAPTER_ERR_ENGINE_DOWN)
   1626        {
   1627            loc_eng_data.adapter->setInSession(TRUE);
   1628            loc_inform_gps_status(loc_eng_data, GPS_STATUS_SESSION_BEGIN);
   1629        }
   1630    }
   1631 
   1632    EXIT_LOG(%d, ret_val);
   1633    return ret_val;
   1634 }
   1635 
   1636 /*===========================================================================
   1637 FUNCTION    loc_eng_stop_wrapper
   1638 
   1639 DESCRIPTION
   1640    Stops the tracking session
   1641 
   1642 DEPENDENCIES
   1643    None
   1644 
   1645 RETURN VALUE
   1646    0: success
   1647 
   1648 SIDE EFFECTS
   1649    N/A
   1650 
   1651 ===========================================================================*/
   1652 int loc_eng_stop(loc_eng_data_s_type &loc_eng_data)
   1653 {
   1654     ENTRY_LOG_CALLFLOW();
   1655     INIT_CHECK(loc_eng_data.adapter, return -1);
   1656 
   1657     if(! loc_eng_data.adapter->getUlpProxy()->sendStopFix())
   1658     {
   1659         loc_eng_data.adapter->sendMsg(new LocEngStopFix(loc_eng_data.adapter));
   1660     }
   1661 
   1662     EXIT_LOG(%d, 0);
   1663     return 0;
   1664 }
   1665 
   1666 static int loc_eng_stop_handler(loc_eng_data_s_type &loc_eng_data)
   1667 {
   1668    ENTRY_LOG();
   1669    int ret_val = LOC_API_ADAPTER_ERR_SUCCESS;
   1670 
   1671    if (loc_eng_data.adapter->isInSession()) {
   1672 
   1673        ret_val = loc_eng_data.adapter->stopFix();
   1674        if (ret_val == LOC_API_ADAPTER_ERR_SUCCESS)
   1675        {
   1676            loc_inform_gps_status(loc_eng_data, GPS_STATUS_SESSION_END);
   1677        }
   1678 
   1679        loc_eng_data.adapter->setInSession(FALSE);
   1680    }
   1681 
   1682     EXIT_LOG(%d, ret_val);
   1683     return ret_val;
   1684 }
   1685 
   1686 /*===========================================================================
   1687 FUNCTION    loc_eng_mute_one_session
   1688 
   1689 DESCRIPTION
   1690    Mutes one session
   1691 
   1692 DEPENDENCIES
   1693    None
   1694 
   1695 RETURN VALUE
   1696    0: Success
   1697 
   1698 SIDE EFFECTS
   1699    N/A
   1700 
   1701 ===========================================================================*/
   1702 void loc_eng_mute_one_session(loc_eng_data_s_type &loc_eng_data)
   1703 {
   1704     ENTRY_LOG();
   1705     loc_eng_data.mute_session_state = LOC_MUTE_SESS_WAIT;
   1706     EXIT_LOG(%s, VOID_RET);
   1707 }
   1708 
   1709 /*===========================================================================
   1710 FUNCTION    loc_eng_set_position_mode
   1711 
   1712 DESCRIPTION
   1713    Sets the mode and fix frequency for the tracking session.
   1714 
   1715 DEPENDENCIES
   1716    None
   1717 
   1718 RETURN VALUE
   1719    0: success
   1720 
   1721 SIDE EFFECTS
   1722    N/A
   1723 
   1724 ===========================================================================*/
   1725 int loc_eng_set_position_mode(loc_eng_data_s_type &loc_eng_data,
   1726                               LocPosMode &params)
   1727 {
   1728     ENTRY_LOG_CALLFLOW();
   1729     INIT_CHECK(loc_eng_data.adapter, return -1);
   1730 
   1731     if(! loc_eng_data.adapter->getUlpProxy()->sendFixMode(params))
   1732     {
   1733         LocEngAdapter* adapter = loc_eng_data.adapter;
   1734         adapter->sendMsg(new LocEngPositionMode(adapter, params));
   1735     }
   1736 
   1737     EXIT_LOG(%d, 0);
   1738     return 0;
   1739 }
   1740 
   1741 /*===========================================================================
   1742 FUNCTION    loc_eng_inject_time
   1743 
   1744 DESCRIPTION
   1745    This is used by Java native function to do time injection.
   1746 
   1747 DEPENDENCIES
   1748    None
   1749 
   1750 RETURN VALUE
   1751    0
   1752 
   1753 SIDE EFFECTS
   1754    N/A
   1755 
   1756 ===========================================================================*/
   1757 int loc_eng_inject_time(loc_eng_data_s_type &loc_eng_data, GpsUtcTime time,
   1758                         int64_t timeReference, int uncertainty)
   1759 {
   1760     ENTRY_LOG_CALLFLOW();
   1761     INIT_CHECK(loc_eng_data.adapter, return -1);
   1762     LocEngAdapter* adapter = loc_eng_data.adapter;
   1763     if (adapter->mAgpsEnabled) {
   1764         adapter->sendMsg(new LocEngSetTime(adapter, time, timeReference,
   1765                                            uncertainty));
   1766     }
   1767     EXIT_LOG(%d, 0);
   1768     return 0;
   1769 }
   1770 
   1771 
   1772 /*===========================================================================
   1773 FUNCTION    loc_eng_inject_location
   1774 
   1775 DESCRIPTION
   1776    This is used by Java native function to do location injection.
   1777 
   1778 DEPENDENCIES
   1779    None
   1780 
   1781 RETURN VALUE
   1782    0          : Successful
   1783    error code : Failure
   1784 
   1785 SIDE EFFECTS
   1786    N/A
   1787 ===========================================================================*/
   1788 int loc_eng_inject_location(loc_eng_data_s_type &loc_eng_data, double latitude,
   1789                             double longitude, float accuracy)
   1790 {
   1791     ENTRY_LOG_CALLFLOW();
   1792     INIT_CHECK(loc_eng_data.adapter, return -1);
   1793     LocEngAdapter* adapter = loc_eng_data.adapter;
   1794     adapter->sendMsg(new LocEngInjectLocation(adapter, latitude, longitude,
   1795                                               accuracy));
   1796 
   1797     EXIT_LOG(%d, 0);
   1798     return 0;
   1799 }
   1800 
   1801 
   1802 /*===========================================================================
   1803 FUNCTION    loc_eng_delete_aiding_data
   1804 
   1805 DESCRIPTION
   1806    This is used by Java native function to delete the aiding data. The function
   1807    updates the global variable for the aiding data to be deleted. If the GPS
   1808    engine is off, the aiding data will be deleted. Otherwise, the actual action
   1809    will happen when gps engine is turned off.
   1810 
   1811 DEPENDENCIES
   1812    Assumes the aiding data type specified in GpsAidingData matches with
   1813    LOC API specification.
   1814 
   1815 RETURN VALUE
   1816    None
   1817 
   1818 SIDE EFFECTS
   1819    N/A
   1820 
   1821 ===========================================================================*/
   1822 void loc_eng_delete_aiding_data(loc_eng_data_s_type &loc_eng_data, GpsAidingData f)
   1823 {
   1824     ENTRY_LOG_CALLFLOW();
   1825     INIT_CHECK(loc_eng_data.adapter, return);
   1826 
   1827     loc_eng_data.adapter->sendMsg(new LocEngDelAidData(&loc_eng_data, f));
   1828 
   1829     EXIT_LOG(%s, VOID_RET);
   1830 }
   1831 
   1832 /*===========================================================================
   1833 
   1834 FUNCTION    loc_inform_gps_state
   1835 
   1836 DESCRIPTION
   1837    Informs the GPS Provider about the GPS status
   1838 
   1839 DEPENDENCIES
   1840    None
   1841 
   1842 RETURN VALUE
   1843    None
   1844 
   1845 SIDE EFFECTS
   1846    N/A
   1847 
   1848 ===========================================================================*/
   1849 static void loc_inform_gps_status(loc_eng_data_s_type &loc_eng_data, GpsStatusValue status)
   1850 {
   1851     ENTRY_LOG();
   1852 
   1853     if (loc_eng_data.status_cb)
   1854     {
   1855         GpsStatus gs = { sizeof(gs),status };
   1856         CALLBACK_LOG_CALLFLOW("status_cb", %s,
   1857                               loc_get_gps_status_name(gs.status));
   1858         loc_eng_data.status_cb(&gs);
   1859     }
   1860 
   1861     EXIT_LOG(%s, VOID_RET);
   1862 }
   1863 
   1864 /*
   1865   Callback function passed to Data Services State Machine
   1866   This becomes part of the state machine's servicer and
   1867   is used to send requests to the data services client
   1868 */
   1869 static int dataCallCb(void *cb_data)
   1870 {
   1871     LOC_LOGD("Enter dataCallCb\n");
   1872     int ret=0;
   1873     if(cb_data != NULL) {
   1874         dsCbData *cbData = (dsCbData *)cb_data;
   1875         LocEngAdapter *locAdapter = (LocEngAdapter *)cbData->mAdapter;
   1876         if(cbData->action == GPS_REQUEST_AGPS_DATA_CONN) {
   1877             LOC_LOGD("dataCallCb GPS_REQUEST_AGPS_DATA_CONN\n");
   1878             ret =  locAdapter->openAndStartDataCall();
   1879         }
   1880         else if(cbData->action == GPS_RELEASE_AGPS_DATA_CONN) {
   1881             LOC_LOGD("dataCallCb GPS_RELEASE_AGPS_DATA_CONN\n");
   1882             locAdapter->stopDataCall();
   1883         }
   1884     }
   1885     else {
   1886         LOC_LOGE("NULL argument received. Failing.\n");
   1887         ret = -1;
   1888         goto err;
   1889     }
   1890 
   1891 err:
   1892     LOC_LOGD("Exit dataCallCb ret = %d\n", ret);
   1893     return ret;
   1894 }
   1895 
   1896 /*===========================================================================
   1897 FUNCTION    loc_eng_agps_reinit
   1898 
   1899 DESCRIPTION
   1900    2nd half of loc_eng_agps_init(), singled out for modem restart to use.
   1901 
   1902 DEPENDENCIES
   1903    NONE
   1904 
   1905 RETURN VALUE
   1906    0
   1907 
   1908 SIDE EFFECTS
   1909    N/A
   1910 
   1911 ===========================================================================*/
   1912 static void loc_eng_agps_reinit(loc_eng_data_s_type &loc_eng_data)
   1913 {
   1914     ENTRY_LOG();
   1915 
   1916     // Set server addresses which came before init
   1917     if (loc_eng_data.supl_host_set)
   1918     {
   1919         loc_eng_set_server(loc_eng_data, LOC_AGPS_SUPL_SERVER,
   1920                            loc_eng_data.supl_host_buf,
   1921                            loc_eng_data.supl_port_buf);
   1922     }
   1923 
   1924     if (loc_eng_data.c2k_host_set)
   1925     {
   1926         loc_eng_set_server(loc_eng_data, LOC_AGPS_CDMA_PDE_SERVER,
   1927                            loc_eng_data.c2k_host_buf,
   1928                            loc_eng_data.c2k_port_buf);
   1929     }
   1930     EXIT_LOG(%s, VOID_RET);
   1931 }
   1932 /*===========================================================================
   1933 FUNCTION    loc_eng_agps_init
   1934 
   1935 DESCRIPTION
   1936    Initialize the AGps interface.
   1937 
   1938 DEPENDENCIES
   1939    NONE
   1940 
   1941 RETURN VALUE
   1942    0
   1943 
   1944 SIDE EFFECTS
   1945    N/A
   1946 
   1947 ===========================================================================*/
   1948 void loc_eng_agps_init(loc_eng_data_s_type &loc_eng_data, AGpsExtCallbacks* callbacks)
   1949 {
   1950     ENTRY_LOG_CALLFLOW();
   1951     INIT_CHECK(loc_eng_data.adapter, return);
   1952     STATE_CHECK((NULL == loc_eng_data.agps_status_cb),
   1953                 "agps instance already initialized",
   1954                 return);
   1955     if(callbacks == NULL) {
   1956         LOC_LOGE("loc_eng_agps_init: bad parameters cb %p", callbacks);
   1957         EXIT_LOG(%s, VOID_RET);
   1958         return;
   1959     }
   1960 
   1961     //Proceed to create AGPS framework only if MSA or MSB capabilities
   1962     //are present. If the target is an APQ, these masks are
   1963     //cleared in get_gps_interface()
   1964     if(!(gps_conf.CAPABILITIES & GPS_CAPABILITY_MSA) &&
   1965        !(gps_conf.CAPABILITIES & GPS_CAPABILITY_MSB) ) {
   1966         LOC_LOGD("%s:%d]: No AGPS capabilities found. Returning\n",
   1967                  __func__, __LINE__);
   1968         return;
   1969     }
   1970 
   1971     loc_eng_data.agps_status_cb = callbacks->status_cb;
   1972 
   1973     loc_eng_data.agnss_nif = new AgpsStateMachine(servicerTypeAgps,
   1974                                                   (void *)loc_eng_data.agps_status_cb,
   1975                                                   AGPS_TYPE_SUPL,
   1976                                                   false);
   1977     loc_eng_data.internet_nif = new AgpsStateMachine(servicerTypeAgps,
   1978                                                      (void *)loc_eng_data.agps_status_cb,
   1979                                                      AGPS_TYPE_WWAN_ANY,
   1980                                                      false);
   1981     loc_eng_data.wifi_nif = new AgpsStateMachine(servicerTypeAgps,
   1982                                                  (void *)loc_eng_data.agps_status_cb,
   1983                                                  AGPS_TYPE_WIFI,
   1984                                                  true);
   1985     if(!loc_eng_data.adapter->initDataServiceClient()) {
   1986         LOC_LOGD("%s:%d]: Creating new ds state machine\n", __func__, __LINE__);
   1987         loc_eng_data.ds_nif = new DSStateMachine(servicerTypeExt,
   1988                                                  (void *)dataCallCb,
   1989                                                  loc_eng_data.adapter);
   1990         LOC_LOGD("%s:%d]: Created new ds state machine\n", __func__, __LINE__);
   1991     }
   1992 
   1993     //loc_eng_dmn_conn_loc_api_server_launch(callbacks->create_thread_cb,
   1994     //                                               NULL, NULL, &loc_eng_data);
   1995 
   1996     loc_eng_agps_reinit(loc_eng_data);
   1997     EXIT_LOG(%s, VOID_RET);
   1998 }
   1999 
   2000 static void deleteAidingData(loc_eng_data_s_type &logEng) {
   2001     if (logEng.engine_status != GPS_STATUS_ENGINE_ON &&
   2002         logEng.aiding_data_for_deletion != 0) {
   2003         logEng.adapter->deleteAidingData(logEng.aiding_data_for_deletion);
   2004         logEng.aiding_data_for_deletion = 0;
   2005     }
   2006 }
   2007 
   2008 static AgpsStateMachine*
   2009 getAgpsStateMachine(loc_eng_data_s_type &locEng, AGpsExtType agpsType) {
   2010     AgpsStateMachine* stateMachine;
   2011     switch (agpsType) {
   2012     case AGPS_TYPE_WIFI: {
   2013         stateMachine = locEng.wifi_nif;
   2014         break;
   2015     }
   2016     case AGPS_TYPE_INVALID:
   2017     case AGPS_TYPE_SUPL: {
   2018         stateMachine = locEng.agnss_nif;
   2019         break;
   2020     }
   2021     case AGPS_TYPE_SUPL_ES: {
   2022         stateMachine = locEng.ds_nif;
   2023         break;
   2024     }
   2025     default:
   2026         stateMachine  = locEng.internet_nif;
   2027     }
   2028     return stateMachine;
   2029 }
   2030 
   2031 /*===========================================================================
   2032 FUNCTION    loc_eng_agps_open
   2033 
   2034 DESCRIPTION
   2035    This function is called when on-demand data connection opening is successful.
   2036 It should inform engine about the data open result.
   2037 
   2038 DEPENDENCIES
   2039    NONE
   2040 
   2041 RETURN VALUE
   2042    0
   2043 
   2044 SIDE EFFECTS
   2045    N/A
   2046 
   2047 ===========================================================================*/
   2048 int loc_eng_agps_open(loc_eng_data_s_type &loc_eng_data, AGpsExtType agpsType,
   2049                      const char* apn, AGpsBearerType bearerType)
   2050 {
   2051     ENTRY_LOG_CALLFLOW();
   2052     INIT_CHECK(loc_eng_data.adapter && loc_eng_data.agps_status_cb,
   2053                return -1);
   2054 
   2055     if (apn == NULL)
   2056     {
   2057         LOC_LOGE("APN Name NULL\n");
   2058         return 0;
   2059     }
   2060 
   2061     LOC_LOGD("loc_eng_agps_open APN name = [%s]", apn);
   2062 
   2063     int apn_len = smaller_of(strlen (apn), MAX_APN_LEN);
   2064     AgpsStateMachine* sm = getAgpsStateMachine(loc_eng_data, agpsType);
   2065 
   2066     loc_eng_data.adapter->sendMsg(
   2067         new LocEngAtlOpenSuccess(sm, apn, apn_len, bearerType));
   2068 
   2069     EXIT_LOG(%d, 0);
   2070     return 0;
   2071 }
   2072 
   2073 /*===========================================================================
   2074 FUNCTION    loc_eng_agps_closed
   2075 
   2076 DESCRIPTION
   2077    This function is called when on-demand data connection closing is done.
   2078 It should inform engine about the data close result.
   2079 
   2080 DEPENDENCIES
   2081    NONE
   2082 
   2083 RETURN VALUE
   2084    0
   2085 
   2086 SIDE EFFECTS
   2087    N/A
   2088 
   2089 ===========================================================================*/
   2090 int loc_eng_agps_closed(loc_eng_data_s_type &loc_eng_data, AGpsExtType agpsType)
   2091 {
   2092     ENTRY_LOG_CALLFLOW();
   2093     INIT_CHECK(loc_eng_data.adapter && loc_eng_data.agps_status_cb,
   2094                return -1);
   2095 
   2096     AgpsStateMachine* sm = getAgpsStateMachine(loc_eng_data, agpsType);
   2097     loc_eng_data.adapter->sendMsg(new LocEngAtlClosed(sm));
   2098 
   2099     EXIT_LOG(%d, 0);
   2100     return 0;
   2101 }
   2102 
   2103 /*===========================================================================
   2104 FUNCTION    loc_eng_agps_open_failed
   2105 
   2106 DESCRIPTION
   2107    This function is called when on-demand data connection opening has failed.
   2108 It should inform engine about the data open result.
   2109 
   2110 DEPENDENCIES
   2111    NONE
   2112 
   2113 RETURN VALUE
   2114    0
   2115 
   2116 SIDE EFFECTS
   2117    N/A
   2118 
   2119 ===========================================================================*/
   2120 int loc_eng_agps_open_failed(loc_eng_data_s_type &loc_eng_data, AGpsExtType agpsType)
   2121 {
   2122     ENTRY_LOG_CALLFLOW();
   2123     INIT_CHECK(loc_eng_data.adapter && loc_eng_data.agps_status_cb,
   2124                return -1);
   2125 
   2126     AgpsStateMachine* sm = getAgpsStateMachine(loc_eng_data, agpsType);
   2127     loc_eng_data.adapter->sendMsg(new LocEngAtlOpenFailed(sm));
   2128 
   2129     EXIT_LOG(%d, 0);
   2130     return 0;
   2131 }
   2132 
   2133 /*===========================================================================
   2134 
   2135 FUNCTION resolve_in_addr
   2136 
   2137 DESCRIPTION
   2138    Translates a hostname to in_addr struct
   2139 
   2140 DEPENDENCIES
   2141    n/a
   2142 
   2143 RETURN VALUE
   2144    TRUE if successful
   2145 
   2146 SIDE EFFECTS
   2147    n/a
   2148 
   2149 ===========================================================================*/
   2150 static boolean resolve_in_addr(const char *host_addr, struct in_addr *in_addr_ptr)
   2151 {
   2152     ENTRY_LOG();
   2153     boolean ret_val = TRUE;
   2154 
   2155     struct hostent             *hp;
   2156     hp = gethostbyname(host_addr);
   2157     if (hp != NULL) /* DNS OK */
   2158     {
   2159         memcpy(in_addr_ptr, hp->h_addr_list[0], hp->h_length);
   2160     }
   2161     else
   2162     {
   2163         /* Try IP representation */
   2164         if (inet_aton(host_addr, in_addr_ptr) == 0)
   2165         {
   2166             /* IP not valid */
   2167             LOC_LOGE("DNS query on '%s' failed\n", host_addr);
   2168             ret_val = FALSE;
   2169         }
   2170     }
   2171 
   2172     EXIT_LOG(%s, loc_logger_boolStr[ret_val!=0]);
   2173     return ret_val;
   2174 }
   2175 
   2176 /*===========================================================================
   2177 FUNCTION    loc_eng_set_server
   2178 
   2179 DESCRIPTION
   2180    This is used to set the default AGPS server. Server address is obtained
   2181    from gps.conf.
   2182 
   2183 DEPENDENCIES
   2184    NONE
   2185 
   2186 RETURN VALUE
   2187    0
   2188 
   2189 SIDE EFFECTS
   2190    N/A
   2191 
   2192 ===========================================================================*/
   2193 static int loc_eng_set_server(loc_eng_data_s_type &loc_eng_data,
   2194                               LocServerType type, const char* hostname, int port)
   2195 {
   2196     ENTRY_LOG();
   2197     int ret = 0;
   2198     LocEngAdapter* adapter = loc_eng_data.adapter;
   2199 
   2200     if (LOC_AGPS_SUPL_SERVER == type) {
   2201         char url[MAX_URL_LEN];
   2202         unsigned int len = snprintf(url, sizeof(url), "%s:%u", hostname, (unsigned) port);
   2203 
   2204         if (sizeof(url) > len) {
   2205             adapter->sendMsg(new LocEngSetServerUrl(adapter, url, len));
   2206         }
   2207     } else if (LOC_AGPS_CDMA_PDE_SERVER == type ||
   2208                LOC_AGPS_CUSTOM_PDE_SERVER == type ||
   2209                LOC_AGPS_MPC_SERVER == type) {
   2210         struct in_addr addr;
   2211         if (!resolve_in_addr(hostname, &addr))
   2212         {
   2213             LOC_LOGE("loc_eng_set_server, hostname %s cannot be resolved.\n", hostname);
   2214             ret = -2;
   2215         } else {
   2216             unsigned int ip = htonl(addr.s_addr);
   2217             adapter->sendMsg(new LocEngSetServerIpv4(adapter, ip, port, type));
   2218         }
   2219     } else {
   2220         LOC_LOGE("loc_eng_set_server, type %d cannot be resolved.\n", type);
   2221     }
   2222 
   2223     EXIT_LOG(%d, ret);
   2224     return ret;
   2225 }
   2226 
   2227 /*===========================================================================
   2228 FUNCTION    loc_eng_set_server_proxy
   2229 
   2230 DESCRIPTION
   2231    If loc_eng_set_server is called before loc_eng_init, it doesn't work. This
   2232    proxy buffers server settings and calls loc_eng_set_server when the client is
   2233    open.
   2234 
   2235 DEPENDENCIES
   2236    NONE
   2237 
   2238 RETURN VALUE
   2239    0
   2240 
   2241 SIDE EFFECTS
   2242    N/A
   2243 
   2244 ===========================================================================*/
   2245 int loc_eng_set_server_proxy(loc_eng_data_s_type &loc_eng_data,
   2246                              LocServerType type,
   2247                              const char* hostname, int port)
   2248 {
   2249     ENTRY_LOG_CALLFLOW();
   2250     int ret_val = 0;
   2251 
   2252     if (NULL != loc_eng_data.adapter)
   2253     {
   2254         ret_val = loc_eng_set_server(loc_eng_data, type, hostname, port);
   2255     } else {
   2256         LOC_LOGW("set_server called before init. save the address, type: %d, hostname: %s, port: %d",
   2257                  (int) type, hostname, port);
   2258         switch (type)
   2259         {
   2260         case LOC_AGPS_SUPL_SERVER:
   2261             strlcpy(loc_eng_data.supl_host_buf, hostname,
   2262                     sizeof(loc_eng_data.supl_host_buf));
   2263             loc_eng_data.supl_port_buf = port;
   2264             loc_eng_data.supl_host_set = 1;
   2265             break;
   2266         case LOC_AGPS_CDMA_PDE_SERVER:
   2267             strlcpy(loc_eng_data.c2k_host_buf, hostname,
   2268                     sizeof(loc_eng_data.c2k_host_buf));
   2269             loc_eng_data.c2k_port_buf = port;
   2270             loc_eng_data.c2k_host_set = 1;
   2271             break;
   2272         default:
   2273             LOC_LOGE("loc_eng_set_server_proxy, unknown server type = %d", (int) type);
   2274         }
   2275     }
   2276 
   2277     EXIT_LOG(%d, ret_val);
   2278     return ret_val;
   2279 }
   2280 
   2281 /*===========================================================================
   2282 FUNCTION    loc_eng_agps_ril_update_network_availability
   2283 
   2284 DESCRIPTION
   2285    Sets data call allow vs disallow flag to modem
   2286    This is the only member of sLocEngAGpsRilInterface implemented.
   2287 
   2288 DEPENDENCIES
   2289    None
   2290 
   2291 RETURN VALUE
   2292    0: success
   2293 
   2294 SIDE EFFECTS
   2295    N/A
   2296 
   2297 ===========================================================================*/
   2298 void loc_eng_agps_ril_update_network_availability(loc_eng_data_s_type &loc_eng_data,
   2299                                                   int available, const char* apn)
   2300 {
   2301     ENTRY_LOG_CALLFLOW();
   2302 
   2303     //This is to store the status of data availability over the network.
   2304     //If GPS is not enabled, the INIT_CHECK will fail and the modem will
   2305     //not be updated with the network's availability. Since the data status
   2306     //can change before GPS is enabled the, storing the status will enable
   2307     //us to inform the modem after GPS is enabled
   2308     agpsStatus = available;
   2309 
   2310     INIT_CHECK(loc_eng_data.adapter, return);
   2311     if (apn != NULL)
   2312     {
   2313         LOC_LOGD("loc_eng_agps_ril_update_network_availability: APN Name = [%s]\n", apn);
   2314         int apn_len = smaller_of(strlen (apn), MAX_APN_LEN);
   2315         LocEngAdapter* adapter = loc_eng_data.adapter;
   2316         adapter->sendMsg(new LocEngEnableData(adapter, apn,  apn_len, available));
   2317     }
   2318     EXIT_LOG(%s, VOID_RET);
   2319 }
   2320 
   2321 /*===========================================================================
   2322 FUNCTION    loc_eng_report_status
   2323 
   2324 DESCRIPTION
   2325    Reports GPS engine state to Java layer.
   2326 
   2327 DEPENDENCIES
   2328    N/A
   2329 
   2330 RETURN VALUE
   2331    N/A
   2332 
   2333 SIDE EFFECTS
   2334    N/A
   2335 
   2336 ===========================================================================*/
   2337 static void loc_eng_report_status (loc_eng_data_s_type &loc_eng_data, GpsStatusValue status)
   2338 {
   2339     ENTRY_LOG();
   2340     // Switch from WAIT to MUTE, for "engine on" or "session begin" event
   2341     if (status == GPS_STATUS_SESSION_BEGIN || status == GPS_STATUS_ENGINE_ON)
   2342     {
   2343         if (loc_eng_data.mute_session_state == LOC_MUTE_SESS_WAIT)
   2344         {
   2345             LOC_LOGD("loc_eng_report_status: mute_session_state changed from WAIT to IN SESSION");
   2346             loc_eng_data.mute_session_state = LOC_MUTE_SESS_IN_SESSION;
   2347         }
   2348     }
   2349 
   2350     // Switch off MUTE session
   2351     if (loc_eng_data.mute_session_state == LOC_MUTE_SESS_IN_SESSION &&
   2352         (status == GPS_STATUS_SESSION_END || status == GPS_STATUS_ENGINE_OFF))
   2353     {
   2354         LOC_LOGD("loc_eng_report_status: mute_session_state changed from IN SESSION to NONE");
   2355         loc_eng_data.mute_session_state = LOC_MUTE_SESS_NONE;
   2356     }
   2357 
   2358     // Session End is not reported during Android navigating state
   2359     boolean navigating = loc_eng_data.adapter->isInSession();
   2360     if (status != GPS_STATUS_NONE &&
   2361         !(status == GPS_STATUS_SESSION_END && navigating) &&
   2362         !(status == GPS_STATUS_SESSION_BEGIN && !navigating))
   2363     {
   2364         if (loc_eng_data.mute_session_state != LOC_MUTE_SESS_IN_SESSION)
   2365         {
   2366             // Inform GpsLocationProvider about mNavigating status
   2367             loc_inform_gps_status(loc_eng_data, status);
   2368         }
   2369         else {
   2370             LOC_LOGD("loc_eng_report_status: muting the status report.");
   2371         }
   2372     }
   2373 
   2374     // Only keeps ENGINE ON/OFF in engine_status
   2375     if (status == GPS_STATUS_ENGINE_ON || status == GPS_STATUS_ENGINE_OFF)
   2376     {
   2377         loc_eng_data.engine_status = status;
   2378     }
   2379 
   2380     // Only keeps SESSION BEGIN/END in fix_session_status
   2381     if (status == GPS_STATUS_SESSION_BEGIN || status == GPS_STATUS_SESSION_END)
   2382     {
   2383         loc_eng_data.fix_session_status = status;
   2384     }
   2385     EXIT_LOG(%s, VOID_RET);
   2386 }
   2387 
   2388 /*===========================================================================
   2389 FUNCTION loc_eng_handle_engine_down
   2390          loc_eng_handle_engine_up
   2391 
   2392 DESCRIPTION
   2393    Calls this function when it is detected that modem restart is happening.
   2394    Either we detected the modem is down or received modem up event.
   2395    This must be called from the deferred thread to avoid race condition.
   2396 
   2397 DEPENDENCIES
   2398    None
   2399 
   2400 RETURN VALUE
   2401    None
   2402 
   2403 SIDE EFFECTS
   2404    N/A
   2405 
   2406 ===========================================================================*/
   2407 void loc_eng_handle_engine_down(loc_eng_data_s_type &loc_eng_data)
   2408 {
   2409     ENTRY_LOG();
   2410     loc_eng_ni_reset_on_engine_restart(loc_eng_data);
   2411     loc_eng_report_status(loc_eng_data, GPS_STATUS_ENGINE_OFF);
   2412     EXIT_LOG(%s, VOID_RET);
   2413 }
   2414 
   2415 void loc_eng_handle_engine_up(loc_eng_data_s_type &loc_eng_data)
   2416 {
   2417     ENTRY_LOG();
   2418     loc_eng_reinit(loc_eng_data);
   2419 
   2420     if (loc_eng_data.agps_status_cb != NULL) {
   2421         loc_eng_data.agnss_nif->dropAllSubscribers();
   2422         loc_eng_data.internet_nif->dropAllSubscribers();
   2423 
   2424         loc_eng_agps_reinit(loc_eng_data);
   2425     }
   2426 
   2427     loc_eng_report_status(loc_eng_data, GPS_STATUS_ENGINE_ON);
   2428 
   2429     // modem is back up.  If we crashed in the middle of navigating, we restart.
   2430     if (loc_eng_data.adapter->isInSession()) {
   2431         // This sets the copy in adapter to modem
   2432         loc_eng_data.adapter->setPositionMode(NULL);
   2433         loc_eng_data.adapter->setInSession(false);
   2434         loc_eng_start_handler(loc_eng_data);
   2435     }
   2436     EXIT_LOG(%s, VOID_RET);
   2437 }
   2438 
   2439 #ifdef USE_GLIB
   2440 /*===========================================================================
   2441 FUNCTION set_sched_policy
   2442 
   2443 DESCRIPTION
   2444    Local copy of this function which bypasses android set_sched_policy
   2445 
   2446 DEPENDENCIES
   2447    None
   2448 
   2449 RETURN VALUE
   2450    0
   2451 
   2452 SIDE EFFECTS
   2453    N/A
   2454 
   2455 ===========================================================================*/
   2456 static int set_sched_policy(int tid, SchedPolicy policy)
   2457 {
   2458     return 0;
   2459 }
   2460 #endif /* USE_GLIB */
   2461 
   2462 /*===========================================================================
   2463 FUNCTION    loc_eng_read_config
   2464 
   2465 DESCRIPTION
   2466    Initiates the reading of the gps config file stored in /etc dir
   2467 
   2468 DEPENDENCIES
   2469    None
   2470 
   2471 RETURN VALUE
   2472    0: success
   2473 
   2474 SIDE EFFECTS
   2475    N/A
   2476 
   2477 ===========================================================================*/
   2478 int loc_eng_read_config(void)
   2479 {
   2480     ENTRY_LOG_CALLFLOW();
   2481     if(configAlreadyRead == false)
   2482     {
   2483       // Initialize our defaults before reading of configuration file overwrites them.
   2484       loc_default_parameters();
   2485       // We only want to parse the conf file once. This is a good place to ensure that.
   2486       // In fact one day the conf file should go into context.
   2487       UTIL_READ_CONF(GPS_CONF_FILE, loc_parameter_table);
   2488       UTIL_READ_CONF(SAP_CONF_FILE, loc_parameter_table);
   2489       configAlreadyRead = true;
   2490     } else {
   2491       LOC_LOGV("GPS Config file has already been read\n");
   2492     }
   2493 
   2494     EXIT_LOG(%d, 0);
   2495     return 0;
   2496 }
   2497