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(GpsSvStatus &svStatus,
257                  GpsLocationExtended &locationExtended,
258                  void* svExt)
259{
260    // print the SV info before delivering
261    LOC_LOGV("num sv: %d\n  ephemeris mask: %dxn  almanac mask: %x\n  used"
262             " in fix mask: %x\n      sv: prn         snr       elevation      azimuth",
263             svStatus.num_svs, svStatus.ephemeris_mask,
264             svStatus.almanac_mask, svStatus.used_in_fix_mask);
265    for (int i = 0; i < svStatus.num_svs && i < GPS_MAX_SVS; i++) {
266        LOC_LOGV("   %d:   %d    %f    %f    %f",
267                 i,
268                 svStatus.sv_list[i].prn,
269                 svStatus.sv_list[i].snr,
270                 svStatus.sv_list[i].elevation,
271                 svStatus.sv_list[i].azimuth);
272    }
273    // loop through adapters, and deliver to all adapters.
274    TO_ALL_LOCADAPTERS(
275        mLocAdapters[i]->reportSv(svStatus,
276                                     locationExtended,
277                                     svExt)
278    );
279}
280
281void LocApiBase::reportStatus(GpsStatusValue status)
282{
283    // loop through adapters, and deliver to all adapters.
284    TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportStatus(status));
285}
286
287void LocApiBase::reportNmea(const char* nmea, int length)
288{
289    // loop through adapters, and deliver to all adapters.
290    TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportNmea(nmea, length));
291}
292
293void LocApiBase::reportXtraServer(const char* url1, const char* url2,
294                                  const char* url3, const int maxlength)
295{
296    // loop through adapters, and deliver to the first handling adapter.
297    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->reportXtraServer(url1, url2, url3, maxlength));
298
299}
300
301void LocApiBase::requestXtraData()
302{
303    // loop through adapters, and deliver to the first handling adapter.
304    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestXtraData());
305}
306
307void LocApiBase::requestTime()
308{
309    // loop through adapters, and deliver to the first handling adapter.
310    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestTime());
311}
312
313void LocApiBase::requestLocation()
314{
315    // loop through adapters, and deliver to the first handling adapter.
316    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestLocation());
317}
318
319void LocApiBase::requestATL(int connHandle, AGpsType agps_type)
320{
321    // loop through adapters, and deliver to the first handling adapter.
322    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestATL(connHandle, agps_type));
323}
324
325void LocApiBase::releaseATL(int connHandle)
326{
327    // loop through adapters, and deliver to the first handling adapter.
328    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->releaseATL(connHandle));
329}
330
331void LocApiBase::requestSuplES(int connHandle)
332{
333    // loop through adapters, and deliver to the first handling adapter.
334    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestSuplES(connHandle));
335}
336
337void LocApiBase::reportDataCallOpened()
338{
339    // loop through adapters, and deliver to the first handling adapter.
340    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->reportDataCallOpened());
341}
342
343void LocApiBase::reportDataCallClosed()
344{
345    // loop through adapters, and deliver to the first handling adapter.
346    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->reportDataCallClosed());
347}
348
349void LocApiBase::requestNiNotify(GpsNiNotification &notify, const void* data)
350{
351    // loop through adapters, and deliver to the first handling adapter.
352    TO_1ST_HANDLING_LOCADAPTERS(mLocAdapters[i]->requestNiNotify(notify, data));
353}
354
355void LocApiBase::saveSupportedMsgList(uint64_t supportedMsgList)
356{
357    mSupportedMsg = supportedMsgList;
358}
359
360void* LocApiBase :: getSibling()
361    DEFAULT_IMPL(NULL)
362
363LocApiProxyBase* LocApiBase :: getLocApiProxy()
364    DEFAULT_IMPL(NULL)
365
366void LocApiBase::reportGpsMeasurementData(GpsData &gpsMeasurementData)
367{
368    // loop through adapters, and deliver to all adapters.
369    TO_ALL_LOCADAPTERS(mLocAdapters[i]->reportGpsMeasurementData(gpsMeasurementData));
370}
371
372enum loc_api_adapter_err LocApiBase::
373   open(LOC_API_ADAPTER_EVENT_MASK_T mask)
374DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
375
376enum loc_api_adapter_err LocApiBase::
377    close()
378DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
379
380enum loc_api_adapter_err LocApiBase::
381    startFix(const LocPosMode& posMode)
382DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
383
384enum loc_api_adapter_err LocApiBase::
385    stopFix()
386DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
387
388enum loc_api_adapter_err LocApiBase::
389    deleteAidingData(GpsAidingData f)
390DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
391
392enum loc_api_adapter_err LocApiBase::
393    enableData(int enable)
394DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
395
396enum loc_api_adapter_err LocApiBase::
397    setAPN(char* apn, int len)
398DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
399
400enum loc_api_adapter_err LocApiBase::
401    injectPosition(double latitude, double longitude, float accuracy)
402DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
403
404enum loc_api_adapter_err LocApiBase::
405    setTime(GpsUtcTime time, int64_t timeReference, int uncertainty)
406DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
407
408enum loc_api_adapter_err LocApiBase::
409    setXtraData(char* data, int length)
410DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
411
412enum loc_api_adapter_err LocApiBase::
413    requestXtraServer()
414DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
415
416enum loc_api_adapter_err LocApiBase::
417   atlOpenStatus(int handle, int is_succ, char* apn,
418                 AGpsBearerType bear, AGpsType agpsType)
419DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
420
421enum loc_api_adapter_err LocApiBase::
422    atlCloseStatus(int handle, int is_succ)
423DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
424
425enum loc_api_adapter_err LocApiBase::
426    setPositionMode(const LocPosMode& posMode)
427DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
428
429enum loc_api_adapter_err LocApiBase::
430    setServer(const char* url, int len)
431DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
432
433enum loc_api_adapter_err LocApiBase::
434    setServer(unsigned int ip, int port,
435              LocServerType type)
436DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
437
438enum loc_api_adapter_err LocApiBase::
439    informNiResponse(GpsUserResponseType userResponse,
440                     const void* passThroughData)
441DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
442
443enum loc_api_adapter_err LocApiBase::
444    setSUPLVersion(uint32_t version)
445DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
446
447enum loc_api_adapter_err LocApiBase::
448    setLPPConfig(uint32_t profile)
449DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
450
451enum loc_api_adapter_err LocApiBase::
452    setSensorControlConfig(int sensorUsage,
453                           int sensorProvider)
454DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
455
456enum loc_api_adapter_err LocApiBase::
457    setSensorProperties(bool gyroBiasVarianceRandomWalk_valid,
458                        float gyroBiasVarianceRandomWalk,
459                        bool accelBiasVarianceRandomWalk_valid,
460                        float accelBiasVarianceRandomWalk,
461                        bool angleBiasVarianceRandomWalk_valid,
462                        float angleBiasVarianceRandomWalk,
463                        bool rateBiasVarianceRandomWalk_valid,
464                        float rateBiasVarianceRandomWalk,
465                        bool velocityBiasVarianceRandomWalk_valid,
466                        float velocityBiasVarianceRandomWalk)
467DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
468
469enum loc_api_adapter_err LocApiBase::
470    setSensorPerfControlConfig(int controlMode,
471                               int accelSamplesPerBatch,
472                               int accelBatchesPerSec,
473                               int gyroSamplesPerBatch,
474                               int gyroBatchesPerSec,
475                               int accelSamplesPerBatchHigh,
476                               int accelBatchesPerSecHigh,
477                               int gyroSamplesPerBatchHigh,
478                               int gyroBatchesPerSecHigh,
479                               int algorithmConfig)
480DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
481
482enum loc_api_adapter_err LocApiBase::
483    setExtPowerConfig(int isBatteryCharging)
484DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
485
486enum loc_api_adapter_err LocApiBase::
487    setAGLONASSProtocol(unsigned long aGlonassProtocol)
488DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
489
490enum loc_api_adapter_err LocApiBase::
491   getWwanZppFix(GpsLocation & zppLoc)
492DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
493
494enum loc_api_adapter_err LocApiBase::
495   getBestAvailableZppFix(GpsLocation & zppLoc)
496DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
497
498enum loc_api_adapter_err LocApiBase::
499   getBestAvailableZppFix(GpsLocation & zppLoc, LocPosTechMask & tech_mask)
500DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
501
502int LocApiBase::
503    initDataServiceClient()
504DEFAULT_IMPL(-1)
505
506int LocApiBase::
507    openAndStartDataCall()
508DEFAULT_IMPL(-1)
509
510void LocApiBase::
511    stopDataCall()
512DEFAULT_IMPL()
513
514void LocApiBase::
515    closeDataCall()
516DEFAULT_IMPL()
517
518int LocApiBase::
519    setGpsLock(LOC_GPS_LOCK_MASK lock)
520DEFAULT_IMPL(-1)
521
522void LocApiBase::
523    installAGpsCert(const DerEncodedCertificate* pData,
524                    size_t length,
525                    uint32_t slotBitMask)
526DEFAULT_IMPL()
527
528int LocApiBase::
529    getGpsLock()
530DEFAULT_IMPL(-1)
531
532enum loc_api_adapter_err LocApiBase::
533    setXtraVersionCheck(enum xtra_version_check check)
534DEFAULT_IMPL(LOC_API_ADAPTER_ERR_SUCCESS)
535
536int LocApiBase::
537    updateRegistrationMask(LOC_API_ADAPTER_EVENT_MASK_T event,
538                           loc_registration_mask_status isEnabled)
539DEFAULT_IMPL(-1)
540
541bool LocApiBase::
542    gnssConstellationConfig()
543DEFAULT_IMPL(false)
544
545} // namespace loc_core
546