1/* Copyright (c) 2011-2014, The Linux Foundation. All rights reserved.
2 *
3 * Redistribution and use in source and binary forms, with or without
4 * modification, are permitted provided that the following conditions are
5 * met:
6 *     * Redistributions of source code must retain the above copyright
7 *       notice, this list of conditions and the following disclaimer.
8 *     * Redistributions in binary form must reproduce the above
9 *       copyright notice, this list of conditions and the following
10 *       disclaimer in the documentation and/or other materials provided
11 *       with the distribution.
12 *     * Neither the name of The Linux Foundation, nor the names of its
13 *       contributors may be used to endorse or promote products derived
14 *       from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
20 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
23 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
24 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
25 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
26 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 */
29#define LOG_NDDEBUG 0
30#define LOG_TAG "LocSvc_LocApiBase"
31
32#include <dlfcn.h>
33#include <LocApiBase.h>
34#include <LocAdapterBase.h>
35#include <log_util.h>
36#include <LocDualContext.h>
37
38namespace loc_core {
39
40#define TO_ALL_LOCADAPTERS(call) TO_ALL_ADAPTERS(mLocAdapters, (call))
41#define TO_1ST_HANDLING_LOCADAPTERS(call) TO_1ST_HANDLING_ADAPTER(mLocAdapters, (call))
42
43int hexcode(char *hexstring, int string_size,
44            const char *data, int data_size)
45{
46   int i;
47   for (i = 0; i < data_size; i++)
48   {
49      char ch = data[i];
50      if (i*2 + 3 <= string_size)
51      {
52         snprintf(&hexstring[i*2], 3, "%02X", ch);
53      }
54      else {
55         break;
56      }
57   }
58   return i;
59}
60
61int decodeAddress(char *addr_string, int string_size,
62                   const char *data, int data_size)
63{
64    const char addr_prefix = 0x91;
65    int i, idxOutput = 0;
66
67    if (!data || !addr_string) { return 0; }
68
69    if (data[0] != addr_prefix)
70    {
71        LOC_LOGW("decodeAddress: address prefix is not 0x%x but 0x%x", addr_prefix, data[0]);
72        addr_string[0] = '\0';
73        return 0; // prefix not correct
74    }
75
76    for (i = 1; i < data_size; i++)
77    {
78        unsigned char ch = data[i], low = ch & 0x0F, hi = ch >> 4;
79        if (low <= 9 && idxOutput < string_size - 1) { addr_string[idxOutput++] = low + '0'; }
80        if (hi <= 9 && idxOutput < string_size - 1) { addr_string[idxOutput++] = hi + '0'; }
81    }
82
83    addr_string[idxOutput] = '\0'; // Terminates the string
84
85    return idxOutput;
86}
87
88struct LocSsrMsg : public LocMsg {
89    LocApiBase* mLocApi;
90    inline LocSsrMsg(LocApiBase* locApi) :
91        LocMsg(), mLocApi(locApi)
92    {
93        locallog();
94    }
95    inline virtual void proc() const {
96        mLocApi->close();
97        mLocApi->open(mLocApi->getEvtMask());
98    }
99    inline void locallog() {
100        LOC_LOGV("LocSsrMsg");
101    }
102    inline virtual void log() {
103        locallog();
104    }
105};
106
107struct LocOpenMsg : public LocMsg {
108    LocApiBase* mLocApi;
109    LOC_API_ADAPTER_EVENT_MASK_T mMask;
110    inline LocOpenMsg(LocApiBase* locApi,
111                      LOC_API_ADAPTER_EVENT_MASK_T mask) :
112        LocMsg(), mLocApi(locApi), mMask(mask)
113    {
114        locallog();
115    }
116    inline virtual void proc() const {
117        mLocApi->open(mMask);
118    }
119    inline void locallog() {
120        LOC_LOGV("%s:%d]: LocOpen Mask: %x\n",
121                 __func__, __LINE__, mMask);
122    }
123    inline virtual void log() {
124        locallog();
125    }
126};
127
128LocApiBase::LocApiBase(const MsgTask* msgTask,
129                       LOC_API_ADAPTER_EVENT_MASK_T excludedMask,
130                       ContextBase* context) :
131    mExcludedMask(excludedMask), mMsgTask(msgTask),
132    mMask(0), mSupportedMsg(0), mContext(context)
133{
134    memset(mLocAdapters, 0, sizeof(mLocAdapters));
135}
136
137LOC_API_ADAPTER_EVENT_MASK_T LocApiBase::getEvtMask()
138{
139    LOC_API_ADAPTER_EVENT_MASK_T mask = 0;
140
141    TO_ALL_LOCADAPTERS(mask |= mLocAdapters[i]->getEvtMask());
142
143    return mask & ~mExcludedMask;
144}
145
146bool LocApiBase::isInSession()
147{
148    bool inSession = false;
149
150    for (int i = 0;
151         !inSession && i < MAX_ADAPTERS && NULL != mLocAdapters[i];
152         i++) {
153        inSession = mLocAdapters[i]->isInSession();
154    }
155
156    return inSession;
157}
158
159void LocApiBase::addAdapter(LocAdapterBase* adapter)
160{
161    for (int i = 0; i < MAX_ADAPTERS && mLocAdapters[i] != adapter; i++) {
162        if (mLocAdapters[i] == NULL) {
163            mLocAdapters[i] = adapter;
164            mMsgTask->sendMsg(new LocOpenMsg(this,
165                                             (adapter->getEvtMask())));
166            break;
167        }
168    }
169}
170
171void LocApiBase::removeAdapter(LocAdapterBase* adapter)
172{
173    for (int i = 0;
174         i < MAX_ADAPTERS && NULL != mLocAdapters[i];
175         i++) {
176        if (mLocAdapters[i] == adapter) {
177            mLocAdapters[i] = NULL;
178
179            // shift the rest of the adapters up so that the pointers
180            // in the array do not have holes.  This should be more
181            // performant, because the array maintenance is much much
182            // less frequent than event handlings, which need to linear
183            // search all the adapters
184            int j = i;
185            while (++i < MAX_ADAPTERS && mLocAdapters[i] != NULL);
186
187            // i would be MAX_ADAPTERS or point to a NULL
188            i--;
189            // i now should point to a none NULL adapter within valid
190            // range although i could be equal to j, but it won't hurt.
191            // No need to check it, as it gains nothing.
192            mLocAdapters[j] = mLocAdapters[i];
193            // this makes sure that we exit the for loop
194            mLocAdapters[i] = NULL;
195
196            // if we have an empty list of adapters
197            if (0 == i) {
198                close();
199            } else {
200                // else we need to remove the bit
201                mMsgTask->sendMsg(new LocOpenMsg(this, getEvtMask()));
202            }
203        }
204    }
205}
206
207void LocApiBase::updateEvtMask()
208{
209    mMsgTask->sendMsg(new LocOpenMsg(this, getEvtMask()));
210}
211
212void LocApiBase::handleEngineUpEvent()
213{
214    // This will take care of renegotiating the loc handle
215    mMsgTask->sendMsg(new LocSsrMsg(this));
216
217    LocDualContext::injectFeatureConfig(mContext);
218
219    // loop through adapters, and deliver to all adapters.
220    TO_ALL_LOCADAPTERS(mLocAdapters[i]->handleEngineUpEvent());
221}
222
223void LocApiBase::handleEngineDownEvent()
224{
225    // loop through adapters, and deliver to all adapters.
226    TO_ALL_LOCADAPTERS(mLocAdapters[i]->handleEngineDownEvent());
227}
228
229void LocApiBase::reportPosition(UlpLocation &location,
230                                GpsLocationExtended &locationExtended,
231                                void* locationExt,
232                                enum loc_sess_status status,
233                                LocPosTechMask loc_technology_mask)
234{
235    // print the location info before delivering
236    LOC_LOGV("flags: %d\n  source: %d\n  latitude: %f\n  longitude: %f\n  "
237             "altitude: %f\n  speed: %f\n  bearing: %f\n  accuracy: %f\n  "
238             "timestamp: %lld\n  rawDataSize: %d\n  rawData: %p\n  "
239             "Session status: %d\n Technology mask: %u",
240             location.gpsLocation.flags, location.position_source,
241             location.gpsLocation.latitude, location.gpsLocation.longitude,
242             location.gpsLocation.altitude, location.gpsLocation.speed,
243             location.gpsLocation.bearing, location.gpsLocation.accuracy,
244             location.gpsLocation.timestamp, location.rawDataSize,
245             location.rawData, status, loc_technology_mask);
246    // loop through adapters, and deliver to all adapters.
247    TO_ALL_LOCADAPTERS(
248        mLocAdapters[i]->reportPosition(location,
249                                        locationExtended,
250                                        locationExt,
251                                        status,
252                                        loc_technology_mask)
253    );
254}
255
256void LocApiBase::reportSv(GnssSvStatus &svStatus,
257                  GpsLocationExtended &locationExtended,
258                  void* svExt)
259{
260    // print the SV info before delivering
261    LOC_LOGV("num sv: %d", svStatus.num_svs);
262    for (int i = 0; i < svStatus.num_svs && i < GNSS_MAX_SVS; i++) {
263        LOC_LOGV("   %03d:   %02d    %d    %f    %f    %f   0x%02X",
264                 i,
265                 svStatus.gnss_sv_list[i].svid,
266                 svStatus.gnss_sv_list[i].constellation,
267                 svStatus.gnss_sv_list[i].c_n0_dbhz,
268                 svStatus.gnss_sv_list[i].elevation,
269                 svStatus.gnss_sv_list[i].azimuth,
270                 svStatus.gnss_sv_list[i].flags);
271    }
272    // loop through adapters, and deliver to all adapters.
273    TO_ALL_LOCADAPTERS(
274        mLocAdapters[i]->reportSv(svStatus,
275                                     locationExtended,
276                                     svExt)
277    );
278}
279
280void LocApiBase::reportStatus(GpsStatusValue status)
281{
282    // loop through adapters, and deliver to all adapters.
283    TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportStatus(status));
284}
285
286void LocApiBase::reportNmea(const char* nmea, int length)
287{
288    // loop through adapters, and deliver to all adapters.
289    TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportNmea(nmea, length));
290}
291
292void LocApiBase::reportXtraServer(const char* url1, const char* url2,
293                                  const char* url3, const int maxlength)
294{
295    // loop through adapters, and deliver to the first handling adapter.
296    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->reportXtraServer(url1, url2, url3, maxlength));
297
298}
299
300void LocApiBase::requestXtraData()
301{
302    // loop through adapters, and deliver to the first handling adapter.
303    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestXtraData());
304}
305
306void LocApiBase::requestTime()
307{
308    // loop through adapters, and deliver to the first handling adapter.
309    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestTime());
310}
311
312void LocApiBase::requestLocation()
313{
314    // loop through adapters, and deliver to the first handling adapter.
315    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestLocation());
316}
317
318void LocApiBase::requestATL(int connHandle, AGpsType agps_type)
319{
320    // loop through adapters, and deliver to the first handling adapter.
321    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestATL(connHandle, agps_type));
322}
323
324void LocApiBase::releaseATL(int connHandle)
325{
326    // loop through adapters, and deliver to the first handling adapter.
327    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->releaseATL(connHandle));
328}
329
330void LocApiBase::requestSuplES(int connHandle)
331{
332    // loop through adapters, and deliver to the first handling adapter.
333    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestSuplES(connHandle));
334}
335
336void LocApiBase::reportDataCallOpened()
337{
338    // loop through adapters, and deliver to the first handling adapter.
339    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->reportDataCallOpened());
340}
341
342void LocApiBase::reportDataCallClosed()
343{
344    // loop through adapters, and deliver to the first handling adapter.
345    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->reportDataCallClosed());
346}
347
348void LocApiBase::requestNiNotify(GpsNiNotification &notify, const void* data)
349{
350    // loop through adapters, and deliver to the first handling adapter.
351    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestNiNotify(notify, data));
352}
353
354void LocApiBase::saveSupportedMsgList(uint64_t supportedMsgList)
355{
356    mSupportedMsg = supportedMsgList;
357}
358
359void* LocApiBase :: getSibling()
360    DEFAULT_IMPL(NULL)
361
362LocApiProxyBase* LocApiBase :: getLocApiProxy()
363    DEFAULT_IMPL(NULL)
364
365void LocApiBase::reportGnssMeasurementData(GnssData &gnssMeasurementData)
366{
367    // loop through adapters, and deliver to all adapters.
368    TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportGnssMeasurementData(gnssMeasurementData));
369}
370
371enum loc_api_adapter_err LocApiBase::
372   open(LOC_API_ADAPTER_EVENT_MASK_T mask)
373DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
374
375enum loc_api_adapter_err LocApiBase::
376    close()
377DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
378
379enum loc_api_adapter_err LocApiBase::
380    startFix(const LocPosMode& posMode)
381DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
382
383enum loc_api_adapter_err LocApiBase::
384    stopFix()
385DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
386
387enum loc_api_adapter_err LocApiBase::
388    deleteAidingData(GpsAidingData f)
389DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
390
391enum loc_api_adapter_err LocApiBase::
392    enableData(int enable)
393DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
394
395enum loc_api_adapter_err LocApiBase::
396    setAPN(char* apn, int len)
397DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
398
399enum loc_api_adapter_err LocApiBase::
400    injectPosition(double latitude, double longitude, float accuracy)
401DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
402
403enum loc_api_adapter_err LocApiBase::
404    setTime(GpsUtcTime time, int64_t timeReference, int uncertainty)
405DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
406
407enum loc_api_adapter_err LocApiBase::
408    setXtraData(char* data, int length)
409DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
410
411enum loc_api_adapter_err LocApiBase::
412    requestXtraServer()
413DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
414
415enum loc_api_adapter_err LocApiBase::
416   atlOpenStatus(int handle, int is_succ, char* apn,
417                 AGpsBearerType bear, AGpsType agpsType)
418DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
419
420enum loc_api_adapter_err LocApiBase::
421    atlCloseStatus(int handle, int is_succ)
422DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
423
424enum loc_api_adapter_err LocApiBase::
425    setPositionMode(const LocPosMode& posMode)
426DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
427
428enum loc_api_adapter_err LocApiBase::
429    setServer(const char* url, int len)
430DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
431
432enum loc_api_adapter_err LocApiBase::
433    setServer(unsigned int ip, int port,
434              LocServerType type)
435DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
436
437enum loc_api_adapter_err LocApiBase::
438    informNiResponse(GpsUserResponseType userResponse,
439                     const void* passThroughData)
440DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
441
442enum loc_api_adapter_err LocApiBase::
443    setSUPLVersion(uint32_t version)
444DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
445
446enum loc_api_adapter_err LocApiBase::
447    setLPPConfig(uint32_t profile)
448DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
449
450enum loc_api_adapter_err LocApiBase::
451    setSensorControlConfig(int sensorUsage,
452                           int sensorProvider)
453DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
454
455enum loc_api_adapter_err LocApiBase::
456    setSensorProperties(bool gyroBiasVarianceRandomWalk_valid,
457                        float gyroBiasVarianceRandomWalk,
458                        bool accelBiasVarianceRandomWalk_valid,
459                        float accelBiasVarianceRandomWalk,
460                        bool angleBiasVarianceRandomWalk_valid,
461                        float angleBiasVarianceRandomWalk,
462                        bool rateBiasVarianceRandomWalk_valid,
463                        float rateBiasVarianceRandomWalk,
464                        bool velocityBiasVarianceRandomWalk_valid,
465                        float velocityBiasVarianceRandomWalk)
466DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
467
468enum loc_api_adapter_err LocApiBase::
469    setSensorPerfControlConfig(int controlMode,
470                               int accelSamplesPerBatch,
471                               int accelBatchesPerSec,
472                               int gyroSamplesPerBatch,
473                               int gyroBatchesPerSec,
474                               int accelSamplesPerBatchHigh,
475                               int accelBatchesPerSecHigh,
476                               int gyroSamplesPerBatchHigh,
477                               int gyroBatchesPerSecHigh,
478                               int algorithmConfig)
479DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
480
481enum loc_api_adapter_err LocApiBase::
482    setExtPowerConfig(int isBatteryCharging)
483DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
484
485enum loc_api_adapter_err LocApiBase::
486    setAGLONASSProtocol(unsigned long aGlonassProtocol)
487DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
488
489enum loc_api_adapter_err LocApiBase::
490   getWwanZppFix(GpsLocation& zppLoc)
491DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
492
493enum loc_api_adapter_err LocApiBase::
494   getBestAvailableZppFix(GpsLocation& zppLoc)
495{
496   memset(&zppLoc, 0, sizeof(zppLoc));
497   DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
498}
499
500enum loc_api_adapter_err LocApiBase::
501   getBestAvailableZppFix(GpsLocation & zppLoc, LocPosTechMask & tech_mask)
502{
503   memset(&zppLoc, 0, sizeof(zppLoc));
504   memset(&tech_mask, 0, sizeof(tech_mask));
505   DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
506}
507
508int LocApiBase::
509    initDataServiceClient()
510DEFAULT_IMPL(-1)
511
512int LocApiBase::
513    openAndStartDataCall()
514DEFAULT_IMPL(-1)
515
516void LocApiBase::
517    stopDataCall()
518DEFAULT_IMPL()
519
520void LocApiBase::
521    closeDataCall()
522DEFAULT_IMPL()
523
524int LocApiBase::
525    setGpsLock(LOC_GPS_LOCK_MASK lock)
526DEFAULT_IMPL(-1)
527
528void LocApiBase::
529    installAGpsCert(const DerEncodedCertificate* pData,
530                    size_t length,
531                    uint32_t slotBitMask)
532DEFAULT_IMPL()
533
534int LocApiBase::
535    getGpsLock()
536DEFAULT_IMPL(-1)
537
538enum loc_api_adapter_err LocApiBase::
539    setXtraVersionCheck(enum xtra_version_check check)
540DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
541
542int LocApiBase::
543    updateRegistrationMask(LOC_API_ADAPTER_EVENT_MASK_T event,
544                           loc_registration_mask_status isEnabled)
545DEFAULT_IMPL(-1)
546
547bool LocApiBase::
548    gnssConstellationConfig()
549DEFAULT_IMPL(false)
550
551} // namespace loc_core
552