[Feature]add MT2731_MP2_MR2_SVN388 baseline version
Change-Id: Ief04314834b31e27effab435d3ca8ba33b499059
diff --git a/src/connectivity/gps/gps_hal/Android.mk b/src/connectivity/gps/gps_hal/Android.mk
new file mode 100644
index 0000000..9956a5a
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/Android.mk
@@ -0,0 +1,84 @@
+# Copyright Statement:
+#
+# This software/firmware and related documentation ("MediaTek Software") are
+# protected under relevant copyright laws. The information contained herein
+# is confidential and proprietary to MediaTek Inc. and/or its licensors.
+# Without the prior written permission of MediaTek inc. and/or its licensors,
+# any reproduction, modification, use or disclosure of MediaTek Software,
+# and information contained herein, in whole or in part, shall be strictly prohibited.
+#
+# MediaTek Inc. (C) 2016. All rights reserved.
+#
+# BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+# THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
+# RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
+# AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+# NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+# SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+# SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+# THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+# THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+# CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
+# SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+# STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
+# CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
+# AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
+# OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+# MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
+#
+# The following software/firmware and/or related documentation ("MediaTek Software")
+# have been modified by MediaTek Inc. All revisions are subject to any receiver's
+# applicable license agreements with MediaTek Inc.
+
+ifeq ($(BOARD_GPS_LIBRARIES), true)
+LOCAL_PATH := $(call my-dir)
+
+# HAL module implemenation, not prelinked and stored in
+# hw/<OVERLAY_HARDWARE_MODULE_ID>.<ro.product.board>.so
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SHARED_LIBRARIES := \
+ liblog \
+ libcutils \
+ libhardware
+
+LOCAL_HEADER_LIBRARIES := libcutils_headers
+
+LOCAL_C_INCLUDES += \
+ $(LOCAL_PATH)/inc \
+ $(TOP)/hardware/libhardware/include \
+ $(TOP)/system/core/include \
+ $(TOP)/system/core/libcutils/include
+
+LOCAL_SRC_FILES += \
+ src/hal2mnl_interface.c \
+ src/hal_mnl_interface_common.c \
+ src/data_coder.c \
+ src/mtk_lbs_utility.c \
+ src/agpsinf.c \
+ src/gpshal.c \
+ src/gpshal_worker.c \
+ src/gfchal_mnl_interface.c \
+ src/geofenceinf.c \
+ src/mtk_auto_log.c \
+
+ifeq ($(MTK_GPS_CHIP),MTK_GPS_MT3337)
+LOCAL_SRC_FILES += \
+ src/gpsinf3337.c
+else
+LOCAL_SRC_FILES += \
+ src/gpsinf.c
+endif
+
+LOCAL_CFLAGS += -D__ANDROID_OS__
+
+LOCAL_MODULE := gps.$(TARGET_BOARD_PLATFORM)
+LOCAL_PROPRIETARY_MODULE := true
+LOCAL_MODULE_OWNER := mtk
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_SHARED_LIBRARY)
+endif
diff --git a/src/connectivity/gps/gps_hal/LICENSE b/src/connectivity/gps/gps_hal/LICENSE
new file mode 100644
index 0000000..77f59ed
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/LICENSE
@@ -0,0 +1,31 @@
+Copyright Statement:
+
+This software/firmware and related documentation ("MediaTek Software") are
+protected under relevant copyright laws. The information contained herein is
+confidential and proprietary to MediaTek Inc. and/or its licensors. Without
+the prior written permission of MediaTek inc. and/or its licensors, any
+reproduction, modification, use or disclosure of MediaTek Software, and
+information contained herein, in whole or in part, shall be strictly
+prohibited.
+
+MediaTek Inc. (C) 2015. All rights reserved.
+
+BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
+RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
+ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
+WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
+WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
+NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
+RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
+INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
+TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
+RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
+OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
+SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
+RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
+ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
+RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
+MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
+CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
diff --git a/src/connectivity/gps/gps_hal/Makefile.am b/src/connectivity/gps/gps_hal/Makefile.am
new file mode 100644
index 0000000..a7dc7af
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/Makefile.am
@@ -0,0 +1,29 @@
+AUTOMAKE_OPTIONS=foreign subdir-objects
+lib_LTLIBRARIES = libgpshal.la
+
+libgpshal_la_SOURCES = src/hal2mnl_interface.c \
+ src/hal_mnl_interface_common.c \
+ src/data_coder.c \
+ src/mtk_lbs_utility.c \
+ src/agpsinf.c \
+ src/gpshal.c \
+ src/gpshal_worker.c \
+ src/gfchal_mnl_interface.c \
+ src/geofenceinf.c \
+ src/mtk_auto_log.c \
+ src/gpsinf.c
+
+AM_CFLAGS = -Iinc \
+ -Iinc/hardware \
+ -Ihardware
+
+include_HEADERS = hardware/gps.h \
+ inc/hardware/gps_mtk.h \
+ hardware/gps_internal.h \
+ inc/hal_mnl_interface_common.h \
+ inc/mtk_lbs_utility.h \
+ inc/hal2mnl_interface.h
+
+libgpshal_la_LIBADD = -lrt
+
+DEFS+=-D__LINUX_OS__ -DMTK_GPS_DATA_PATH="\"/usr/share/gps/\""
diff --git a/src/connectivity/gps/gps_hal/NOTICE b/src/connectivity/gps/gps_hal/NOTICE
new file mode 100644
index 0000000..7868067
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/NOTICE
@@ -0,0 +1,23 @@
+ * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>.
+ * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>.
+ * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>.
+ * Copyright (C) 1998 - 2008, Daniel Stenberg, <daniel@haxx.se>.
+ * Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>.
+ * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>.
+
+Curl License
+Copyright (c) 1996 - 2003, Daniel Stenberg, <daniel@haxx.se>.
+
+All rights reserved.
+
+Permission to use, copy, modify, and distribute this software for any purposewith or without fee is hereby granted,
+provided that the above copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USEOR OTHER DEALINGS IN THE
+SOFTWARE.
+
+Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to
+promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder.
diff --git a/src/connectivity/gps/gps_hal/README b/src/connectivity/gps/gps_hal/README
new file mode 100644
index 0000000..92f6303
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/README
@@ -0,0 +1,44 @@
+This directory contains GPS HAL layer code.
+
+WHAT IT DOES?
+=============
+It provide GPS interfaces for gps provider on frameworks,which allow init/open/close/cleanup gps
+when mnld daemon is launched.
+
+HOW IT WAS BUILT?
+==================
+
+It needs the following libs from AOSP:
+1. libc.so
+2. libcutils
+3. libnetutils
+4. libhardware
+5. libandroid_runtime
+6. libnativehelper
+7. libcrypto
+8. libssl
+9. libz
+
+and the following libs from MediaTek:
+1. liblog.so
+2. libepos.a
+3. libcurl
+
+All source/dependency modules of this module are already put in
+'vendor/mediatek/libs' folder.
+
+
+HOW TO USE IT?
+==============
+
+Files in this directory is used to
+generate a library which's name is 'gps.mtxxxx.so'
+
+
+gps.mtxxxx
+mtxxxx means chip platform name,
+The lib 'gps.mtxxxx' is loaded by system_server,
+GPS Location provider will call gps_module_methods API, if system_server is launched.
+
+All the source code of this library were written by MediaTek co..
+
diff --git a/src/connectivity/gps/gps_hal/configure.ac b/src/connectivity/gps/gps_hal/configure.ac
new file mode 100644
index 0000000..9334153
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/configure.ac
@@ -0,0 +1,8 @@
+AC_INIT([gpshal], [1.0])
+AM_INIT_AUTOMAKE([foreign])
+AC_CONFIG_HEADER(defines.h)
+AC_PROG_CC
+AC_DISABLE_STATIC
+LT_INIT
+AC_CONFIG_FILES([Makefile])
+AC_OUTPUT
diff --git a/src/connectivity/gps/gps_hal/hardware/gps.h b/src/connectivity/gps/gps_hal/hardware/gps.h
new file mode 100644
index 0000000..11804f3
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/hardware/gps.h
@@ -0,0 +1,2234 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_INCLUDE_HARDWARE_GPS_H
+#define ANDROID_INCLUDE_HARDWARE_GPS_H
+
+#ifdef __LINUX_OS__
+#include <stdint.h>
+#include <sys/cdefs.h>
+#include <sys/types.h>
+#include <pthread.h>
+#include <sys/socket.h>
+#include <stdbool.h>
+
+__BEGIN_DECLS
+
+/*
+ * Enums defined in HIDL in hardware/interfaces are auto-generated and present
+ * in gnss-base.h.
+ */
+
+/* for compatibility */
+
+/*#define GPS_REQUEST_AGPS_DATA_CONN GNSS_REQUEST_AGNSS_DATA_CONN
+#define GPS_RELEASE_AGPS_DATA_CONN GNSS_RELEASE_AGNSS_DATA_CONN
+#define GPS_AGPS_DATA_CONNECTED GNSS_AGNSS_DATA_CONNECTED
+#define GPS_AGPS_DATA_CONN_DONE GNSS_AGNSS_DATA_CONN_DONE
+#define GPS_AGPS_DATA_CONN_FAILED GNSS_AGNSS_DATA_CONN_FAILED
+#define AGPS_RIL_NETWORK_TYPE_MOBILE_MMS AGPS_RIL_NETWORK_TYPE_MMS
+#define AGPS_RIL_NETWORK_TYPE_MOBILE_SUPL AGPS_RIL_NETWORK_TYPE_SUPL
+#define AGPS_RIL_NETWORK_TTYPE_MOBILE_DUN AGPS_RIL_NETWORK_TYPE_DUN
+#define AGPS_RIL_NETWORK_TTYPE_MOBILE_HIPRI AGPS_RIL_NETWORK_TYPE_HIPRI
+#define AGPS_RIL_NETWORK_TTYPE_WIMAX AGPS_RIL_NETWORK_TYPE_WIMAX
+#define GNSS_MULTIPATH_INDICATOR_NOT_PRESENT GNSS_MULTIPATH_INDICATIOR_NOT_PRESENT
+#define AGPS_SETID_TYPE_MSISDN AGPS_SETID_TYPE_MSISDM
+#define GPS_MEASUREMENT_OPERATION_SUCCESS GPS_MEASUREMENT_SUCCESS
+#define GPS_NAVIGATION_MESSAGE_OPERATION_SUCCESS GPS_NAVIGATION_MESSAGE_SUCCESS
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_L1CA GNSS_NAVIGATION_MESSAGE_TYPE_GNSS_L1CA
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_L2CNAV GNSS_NAVIGATION_MESSAGE_TYPE_GNSS_L2CNAV
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_L5CNAV GNSS_NAVIGATION_MESSAGE_TYPE_GNSS_L5CNAV
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_CNAV2 GNSS_NAVIGATION_MESSAGE_TYPE_GNSS_CNAV2
+#define GPS_LOCATION_HAS_ACCURACY GPS_LOCATION_HAS_HORIZONTAL_ACCURACY
+*/
+/**
+ * The id of this module
+ */
+#define GPS_HARDWARE_MODULE_ID "gps"
+
+#define GPS_NAVIGATION_MESSAGE_OPERATION_SUCCESS 0
+#define GPS_NAVIGATION_MESSAGE_ERROR_ALREADY_INIT -100
+#define GPS_NAVIGATION_MESSAGE_ERROR_GENERIC -101
+
+/** Milliseconds since January 1, 1970 */
+typedef int64_t GpsUtcTime;
+
+/** Maximum number of SVs for gps_sv_status_callback(). */
+#define GPS_MAX_SVS 32
+/** Maximum number of SVs for gps_sv_status_callback(). */
+#define GNSS_MAX_SVS 64
+
+/** Maximum number of Measurements in gps_measurement_callback(). */
+#define GPS_MAX_MEASUREMENT 32
+
+/** Maximum number of Measurements in gnss_measurement_callback(). */
+#define GNSS_MAX_MEASUREMENT 64
+
+/** Requested operational mode for GPS operation. */
+typedef uint32_t GpsPositionMode;
+/* IMPORTANT: Note that the following values must match
+ * constants in GpsLocationProvider.java. */
+/** Mode for running GPS standalone (no assistance). */
+#define GPS_POSITION_MODE_STANDALONE 0
+/** AGPS MS-Based mode. */
+#define GPS_POSITION_MODE_MS_BASED 1
+/**
+ * AGPS MS-Assisted mode. This mode is not maintained by the platform anymore.
+ * It is strongly recommended to use GPS_POSITION_MODE_MS_BASED instead.
+ */
+#define GPS_POSITION_MODE_MS_ASSISTED 2
+
+/** Requested recurrence mode for GPS operation. */
+typedef uint32_t GpsPositionRecurrence;
+/* IMPORTANT: Note that the following values must match
+ * constants in GpsLocationProvider.java. */
+/** Receive GPS fixes on a recurring basis at a specified period. */
+#define GPS_POSITION_RECURRENCE_PERIODIC 0
+/** Request a single shot GPS fix. */
+#define GPS_POSITION_RECURRENCE_SINGLE 1
+
+/** GPS status event values. */
+typedef uint16_t GpsStatusValue;
+/* IMPORTANT: Note that the following values must match
+ * constants in GpsLocationProvider.java. */
+/** GPS status unknown. */
+#define GPS_STATUS_NONE 0
+/** GPS has begun navigating. */
+#define GPS_STATUS_SESSION_BEGIN 1
+/** GPS has stopped navigating. */
+#define GPS_STATUS_SESSION_END 2
+/** GPS has powered on but is not navigating. */
+#define GPS_STATUS_ENGINE_ON 3
+/** GPS is powered off. */
+#define GPS_STATUS_ENGINE_OFF 4
+
+/** Flags to indicate which values are valid in a GpsLocation. */
+typedef uint16_t GpsLocationFlags;
+/* IMPORTANT: Note that the following values must match
+ * constants in GpsLocationProvider.java. */
+/** GpsLocation has valid latitude and longitude. */
+#define GPS_LOCATION_HAS_LAT_LONG 0x0001
+/** GpsLocation has valid altitude. */
+#define GPS_LOCATION_HAS_ALTITUDE 0x0002
+/** GpsLocation has valid speed. */
+#define GPS_LOCATION_HAS_SPEED 0x0004
+/** GpsLocation has valid bearing. */
+#define GPS_LOCATION_HAS_BEARING 0x0008
+/** GpsLocation has valid accuracy. */
+#define GPS_LOCATION_HAS_ACCURACY 0x0010
+
+/**
+ * GPS HAL schedules fixes for GPS_POSITION_RECURRENCE_PERIODIC mode. If this is
+ * not set, then the framework will use 1000ms for min_interval and will start
+ * and call start() and stop() to schedule the GPS.
+ */
+#define GPS_CAPABILITY_SCHEDULING (1 << 0)
+/** GPS supports MS-Based AGPS mode */
+#define GPS_CAPABILITY_MSB (1 << 1)
+/** GPS supports MS-Assisted AGPS mode */
+#define GPS_CAPABILITY_MSA (1 << 2)
+/** GPS supports single-shot fixes */
+#define GPS_CAPABILITY_SINGLE_SHOT (1 << 3)
+/** GPS supports on demand time injection */
+#define GPS_CAPABILITY_ON_DEMAND_TIME (1 << 4)
+/** GPS supports Geofencing */
+#define GPS_CAPABILITY_GEOFENCING (1 << 5)
+/** GPS supports Measurements. */
+#define GPS_CAPABILITY_MEASUREMENTS (1 << 6)
+/** GPS supports Navigation Messages */
+#define GPS_CAPABILITY_NAV_MESSAGES (1 << 7)
+
+/**
+ * Flags used to specify which aiding data to delete when calling
+ * delete_aiding_data().
+ */
+typedef uint16_t GpsAidingData;
+/* IMPORTANT: Note that the following values must match
+ * constants in GpsLocationProvider.java. */
+#define GPS_DELETE_EPHEMERIS 0x0001
+#define GPS_DELETE_ALMANAC 0x0002
+#define GPS_DELETE_POSITION 0x0004
+#define GPS_DELETE_TIME 0x0008
+#define GPS_DELETE_IONO 0x0010
+#define GPS_DELETE_UTC 0x0020
+#define GPS_DELETE_HEALTH 0x0040
+#define GPS_DELETE_SVDIR 0x0080
+#define GPS_DELETE_SVSTEER 0x0100
+#define GPS_DELETE_SADATA 0x0200
+#define GPS_DELETE_RTI 0x0400
+#define GPS_DELETE_CELLDB_INFO 0x8000
+#define GPS_DELETE_ALL 0xFFFF
+
+/** AGPS type */
+typedef uint16_t AGpsType;
+#define AGPS_TYPE_SUPL 1
+#define AGPS_TYPE_C2K 2
+
+typedef uint16_t AGpsSetIDType;
+#define AGPS_SETID_TYPE_NONE 0
+#define AGPS_SETID_TYPE_IMSI 1
+#define AGPS_SETID_TYPE_MSISDN 2
+
+typedef uint16_t ApnIpType;
+#define APN_IP_INVALID 0
+#define APN_IP_IPV4 1
+#define APN_IP_IPV6 2
+#define APN_IP_IPV4V6 3
+
+/**
+ * String length constants
+ */
+#define GPS_NI_SHORT_STRING_MAXLEN 256
+#define GPS_NI_LONG_STRING_MAXLEN 2048
+
+/**
+ * GpsNiType constants
+ */
+typedef uint32_t GpsNiType;
+#define GPS_NI_TYPE_VOICE 1
+#define GPS_NI_TYPE_UMTS_SUPL 2
+#define GPS_NI_TYPE_UMTS_CTRL_PLANE 3
+
+/**
+ * GpsNiNotifyFlags constants
+ */
+typedef uint32_t GpsNiNotifyFlags;
+/** NI requires notification */
+#define GPS_NI_NEED_NOTIFY 0x0001
+/** NI requires verification */
+#define GPS_NI_NEED_VERIFY 0x0002
+/** NI requires privacy override, no notification/minimal trace */
+#define GPS_NI_PRIVACY_OVERRIDE 0x0004
+
+/**
+ * GPS NI responses, used to define the response in
+ * NI structures
+ */
+typedef int GpsUserResponseType;
+#define GPS_NI_RESPONSE_ACCEPT 1
+#define GPS_NI_RESPONSE_DENY 2
+#define GPS_NI_RESPONSE_NORESP 3
+
+/**
+ * NI data encoding scheme
+ */
+typedef int GpsNiEncodingType;
+#define GPS_ENC_NONE 0
+#define GPS_ENC_SUPL_GSM_DEFAULT 1
+#define GPS_ENC_SUPL_UTF8 2
+#define GPS_ENC_SUPL_UCS2 3
+#define GPS_ENC_UNKNOWN -1
+
+/** AGPS status event values. */
+typedef uint16_t AGpsStatusValue;
+/** GPS requests data connection for AGPS. */
+#define GPS_REQUEST_AGPS_DATA_CONN 1
+/** GPS releases the AGPS data connection. */
+#define GPS_RELEASE_AGPS_DATA_CONN 2
+/** AGPS data connection initiated */
+#define GPS_AGPS_DATA_CONNECTED 3
+/** AGPS data connection completed */
+#define GPS_AGPS_DATA_CONN_DONE 4
+/** AGPS data connection failed */
+#define GPS_AGPS_DATA_CONN_FAILED 5
+
+typedef uint16_t AGpsRefLocationType;
+#define AGPS_REF_LOCATION_TYPE_GSM_CELLID 1
+#define AGPS_REF_LOCATION_TYPE_UMTS_CELLID 2
+#define AGPS_REF_LOCATION_TYPE_MAC 3
+#define AGPS_REF_LOCATION_TYPE_LTE_CELLID 4
+
+/* Deprecated, to be removed in the next Android release. */
+#define AGPS_REG_LOCATION_TYPE_MAC 3
+
+/** Network types for update_network_state "type" parameter */
+#define AGPS_RIL_NETWORK_TYPE_MOBILE 0
+#define AGPS_RIL_NETWORK_TYPE_WIFI 1
+#define AGPS_RIL_NETWORK_TYPE_MOBILE_MMS 2
+#define AGPS_RIL_NETWORK_TYPE_MOBILE_SUPL 3
+#define AGPS_RIL_NETWORK_TTYPE_MOBILE_DUN 4
+#define AGPS_RIL_NETWORK_TTYPE_MOBILE_HIPRI 5
+#define AGPS_RIL_NETWORK_TTYPE_WIMAX 6
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. */
+typedef uint16_t GpsClockFlags;
+#define GPS_CLOCK_HAS_LEAP_SECOND (1<<0)
+#define GPS_CLOCK_HAS_TIME_UNCERTAINTY (1<<1)
+#define GPS_CLOCK_HAS_FULL_BIAS (1<<2)
+#define GPS_CLOCK_HAS_BIAS (1<<3)
+#define GPS_CLOCK_HAS_BIAS_UNCERTAINTY (1<<4)
+#define GPS_CLOCK_HAS_DRIFT (1<<5)
+#define GPS_CLOCK_HAS_DRIFT_UNCERTAINTY (1<<6)
+
+/**
+ * Flags to indicate what fields in GnssClock are valid.
+ */
+typedef uint16_t GnssClockFlags;
+/** A valid 'leap second' is stored in the data structure. */
+#define GNSS_CLOCK_HAS_LEAP_SECOND (1<<0)
+/** A valid 'time uncertainty' is stored in the data structure. */
+#define GNSS_CLOCK_HAS_TIME_UNCERTAINTY (1<<1)
+/** A valid 'full bias' is stored in the data structure. */
+#define GNSS_CLOCK_HAS_FULL_BIAS (1<<2)
+/** A valid 'bias' is stored in the data structure. */
+#define GNSS_CLOCK_HAS_BIAS (1<<3)
+/** A valid 'bias uncertainty' is stored in the data structure. */
+#define GNSS_CLOCK_HAS_BIAS_UNCERTAINTY (1<<4)
+/** A valid 'drift' is stored in the data structure. */
+#define GNSS_CLOCK_HAS_DRIFT (1<<5)
+/** A valid 'drift uncertainty' is stored in the data structure. */
+#define GNSS_CLOCK_HAS_DRIFT_UNCERTAINTY (1<<6)
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. */
+typedef uint8_t GpsClockType;
+#define GPS_CLOCK_TYPE_UNKNOWN 0
+#define GPS_CLOCK_TYPE_LOCAL_HW_TIME 1
+#define GPS_CLOCK_TYPE_GPS_TIME 2
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. */
+typedef uint32_t GpsMeasurementFlags;
+#define GPS_MEASUREMENT_HAS_SNR (1<<0)
+#define GPS_MEASUREMENT_HAS_ELEVATION (1<<1)
+#define GPS_MEASUREMENT_HAS_ELEVATION_UNCERTAINTY (1<<2)
+#define GPS_MEASUREMENT_HAS_AZIMUTH (1<<3)
+#define GPS_MEASUREMENT_HAS_AZIMUTH_UNCERTAINTY (1<<4)
+#define GPS_MEASUREMENT_HAS_PSEUDORANGE (1<<5)
+#define GPS_MEASUREMENT_HAS_PSEUDORANGE_UNCERTAINTY (1<<6)
+#define GPS_MEASUREMENT_HAS_CODE_PHASE (1<<7)
+#define GPS_MEASUREMENT_HAS_CODE_PHASE_UNCERTAINTY (1<<8)
+#define GPS_MEASUREMENT_HAS_CARRIER_FREQUENCY (1<<9)
+#define GPS_MEASUREMENT_HAS_CARRIER_CYCLES (1<<10)
+#define GPS_MEASUREMENT_HAS_CARRIER_PHASE (1<<11)
+#define GPS_MEASUREMENT_HAS_CARRIER_PHASE_UNCERTAINTY (1<<12)
+#define GPS_MEASUREMENT_HAS_BIT_NUMBER (1<<13)
+#define GPS_MEASUREMENT_HAS_TIME_FROM_LAST_BIT (1<<14)
+#define GPS_MEASUREMENT_HAS_DOPPLER_SHIFT (1<<15)
+#define GPS_MEASUREMENT_HAS_DOPPLER_SHIFT_UNCERTAINTY (1<<16)
+#define GPS_MEASUREMENT_HAS_USED_IN_FIX (1<<17)
+#define GPS_MEASUREMENT_HAS_UNCORRECTED_PSEUDORANGE_RATE (1<<18)
+
+/**
+ * Flags to indicate what fields in GnssMeasurement are valid.
+ */
+typedef uint32_t GnssMeasurementFlags;
+/** A valid 'snr' is stored in the data structure. */
+#define GNSS_MEASUREMENT_HAS_SNR (1<<0)
+/** A valid 'carrier frequency' is stored in the data structure. */
+#define GNSS_MEASUREMENT_HAS_CARRIER_FREQUENCY (1<<9)
+/** A valid 'carrier cycles' is stored in the data structure. */
+#define GNSS_MEASUREMENT_HAS_CARRIER_CYCLES (1<<10)
+/** A valid 'carrier phase' is stored in the data structure. */
+#define GNSS_MEASUREMENT_HAS_CARRIER_PHASE (1<<11)
+/** A valid 'carrier phase uncertainty' is stored in the data structure. */
+#define GNSS_MEASUREMENT_HAS_CARRIER_PHASE_UNCERTAINTY (1<<12)
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. */
+typedef uint8_t GpsLossOfLock;
+#define GPS_LOSS_OF_LOCK_UNKNOWN 0
+#define GPS_LOSS_OF_LOCK_OK 1
+#define GPS_LOSS_OF_LOCK_CYCLE_SLIP 2
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. Use GnssMultipathIndicator instead.
+ */
+typedef uint8_t GpsMultipathIndicator;
+#define GPS_MULTIPATH_INDICATOR_UNKNOWN 0
+#define GPS_MULTIPATH_INDICATOR_DETECTED 1
+#define GPS_MULTIPATH_INDICATOR_NOT_USED 2
+
+/**
+ * Enumeration of available values for the GNSS Measurement's multipath
+ * indicator.
+ */
+typedef uint8_t GnssMultipathIndicator;
+/** The indicator is not available or unknown. */
+#define GNSS_MULTIPATH_INDICATOR_UNKNOWN 0
+/** The measurement is indicated to be affected by multipath. */
+#define GNSS_MULTIPATH_INDICATOR_PRESENT 1
+/** The measurement is indicated to be not affected by multipath. */
+#define GNSS_MULTIPATH_INDICATOR_NOT_PRESENT 2
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. */
+typedef uint16_t GpsMeasurementState;
+#define GPS_MEASUREMENT_STATE_UNKNOWN 0
+#define GPS_MEASUREMENT_STATE_CODE_LOCK (1<<0)
+#define GPS_MEASUREMENT_STATE_BIT_SYNC (1<<1)
+#define GPS_MEASUREMENT_STATE_SUBFRAME_SYNC (1<<2)
+#define GPS_MEASUREMENT_STATE_TOW_DECODED (1<<3)
+#define GPS_MEASUREMENT_STATE_MSEC_AMBIGUOUS (1<<4)
+
+/**
+ * Flags indicating the GNSS measurement state.
+ *
+ * The expected behavior here is for GPS HAL to set all the flags that applies.
+ * For example, if the state for a satellite is only C/A code locked and bit
+ * synchronized, and there is still millisecond ambiguity, the state should be
+ * set as:
+ *
+ * GNSS_MEASUREMENT_STATE_CODE_LOCK | GNSS_MEASUREMENT_STATE_BIT_SYNC |
+ * GNSS_MEASUREMENT_STATE_MSEC_AMBIGUOUS
+ *
+ * If GNSS is still searching for a satellite, the corresponding state should be
+ * set to GNSS_MEASUREMENT_STATE_UNKNOWN(0).
+ */
+typedef uint32_t GnssMeasurementState;
+#define GNSS_MEASUREMENT_STATE_UNKNOWN 0
+#define GNSS_MEASUREMENT_STATE_CODE_LOCK (1<<0)
+#define GNSS_MEASUREMENT_STATE_BIT_SYNC (1<<1)
+#define GNSS_MEASUREMENT_STATE_SUBFRAME_SYNC (1<<2)
+#define GNSS_MEASUREMENT_STATE_TOW_DECODED (1<<3)
+#define GNSS_MEASUREMENT_STATE_MSEC_AMBIGUOUS (1<<4)
+#define GNSS_MEASUREMENT_STATE_SYMBOL_SYNC (1<<5)
+#define GNSS_MEASUREMENT_STATE_GLO_STRING_SYNC (1<<6)
+#define GNSS_MEASUREMENT_STATE_GLO_TOD_DECODED (1<<7)
+#define GNSS_MEASUREMENT_STATE_BDS_D2_BIT_SYNC (1<<8)
+#define GNSS_MEASUREMENT_STATE_BDS_D2_SUBFRAME_SYNC (1<<9)
+#define GNSS_MEASUREMENT_STATE_GAL_E1BC_CODE_LOCK (1<<10)
+#define GNSS_MEASUREMENT_STATE_GAL_E1C_2ND_CODE_LOCK (1<<11)
+#define GNSS_MEASUREMENT_STATE_GAL_E1B_PAGE_SYNC (1<<12)
+#define GNSS_MEASUREMENT_STATE_SBAS_SYNC (1<<13)
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. */
+typedef uint16_t GpsAccumulatedDeltaRangeState;
+#define GPS_ADR_STATE_UNKNOWN 0
+#define GPS_ADR_STATE_VALID (1<<0)
+#define GPS_ADR_STATE_RESET (1<<1)
+#define GPS_ADR_STATE_CYCLE_SLIP (1<<2)
+
+/**
+ * Flags indicating the Accumulated Delta Range's states.
+ */
+typedef uint16_t GnssAccumulatedDeltaRangeState;
+#define GNSS_ADR_STATE_UNKNOWN 0
+#define GNSS_ADR_STATE_VALID (1<<0)
+#define GNSS_ADR_STATE_RESET (1<<1)
+#define GNSS_ADR_STATE_CYCLE_SLIP (1<<2)
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. */
+typedef uint8_t GpsNavigationMessageType;
+#define GPS_NAVIGATION_MESSAGE_TYPE_UNKNOWN 0
+#define GPS_NAVIGATION_MESSAGE_TYPE_L1CA 1
+#define GPS_NAVIGATION_MESSAGE_TYPE_L2CNAV 2
+#define GPS_NAVIGATION_MESSAGE_TYPE_L5CNAV 3
+#define GPS_NAVIGATION_MESSAGE_TYPE_CNAV2 4
+
+/**
+ * Enumeration of available values to indicate the GNSS Navigation message
+ * types.
+ *
+ * For convenience, first byte is the GnssConstellationType on which that signal
+ * is typically transmitted
+ */
+typedef int16_t GnssNavigationMessageType;
+
+#define GNSS_NAVIGATION_MESSAGE_TYPE_UNKNOWN 0
+/** GPS L1 C/A message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_L1CA 0x0101
+/** GPS L2-CNAV message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_L2CNAV 0x0102
+/** GPS L5-CNAV message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_L5CNAV 0x0103
+/** GPS CNAV-2 message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_CNAV2 0x0104
+/** Glonass L1 CA message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GLO_L1CA 0x0301
+/** Beidou D1 message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_BDS_D1 0x0501
+/** Beidou D2 message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_BDS_D2 0x0502
+/** Galileo I/NAV message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GAL_I 0x0601
+/** Galileo F/NAV message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GAL_F 0x0602
+
+/**
+ * Status of Navigation Message
+ * When a message is received properly without any parity error in its navigation words, the
+ * status should be set to NAV_MESSAGE_STATUS_PARITY_PASSED. But if a message is received
+ * with words that failed parity check, but GPS is able to correct those words, the status
+ * should be set to NAV_MESSAGE_STATUS_PARITY_REBUILT.
+ * No need to send any navigation message that contains words with parity error and cannot be
+ * corrected.
+ */
+typedef uint16_t NavigationMessageStatus;
+#define NAV_MESSAGE_STATUS_UNKNOWN 0
+#define NAV_MESSAGE_STATUS_PARITY_PASSED (1<<0)
+#define NAV_MESSAGE_STATUS_PARITY_REBUILT (1<<1)
+
+/* This constant is deprecated, and will be removed in the next release. */
+#define NAV_MESSAGE_STATUS_UNKONW 0
+
+/**
+ * Flags that indicate information about the satellite
+ */
+typedef uint8_t GnssSvFlags;
+#define GNSS_SV_FLAGS_NONE 0
+#define GNSS_SV_FLAGS_HAS_EPHEMERIS_DATA (1 << 0)
+#define GNSS_SV_FLAGS_HAS_ALMANAC_DATA (1 << 1)
+#define GNSS_SV_FLAGS_USED_IN_FIX (1 << 2)
+
+/**
+ * Constellation type of GnssSvInfo
+ */
+typedef uint8_t GnssConstellationType;
+#define GNSS_CONSTELLATION_UNKNOWN 0
+#define GNSS_CONSTELLATION_GPS 1
+#define GNSS_CONSTELLATION_SBAS 2
+#define GNSS_CONSTELLATION_GLONASS 3
+#define GNSS_CONSTELLATION_QZSS 4
+#define GNSS_CONSTELLATION_BEIDOU 5
+#define GNSS_CONSTELLATION_GALILEO 6
+
+/**
+ * Name for the GPS XTRA interface.
+ */
+#define GPS_XTRA_INTERFACE "gps-xtra"
+
+/**
+ * Name for the GPS DEBUG interface.
+ */
+#define GPS_DEBUG_INTERFACE "gps-debug"
+
+/**
+ * Name for the AGPS interface.
+ */
+#define AGPS_INTERFACE "agps"
+
+/**
+ * Name of the Supl Certificate interface.
+ */
+#define SUPL_CERTIFICATE_INTERFACE "supl-certificate"
+
+/**
+ * Name for NI interface
+ */
+#define GPS_NI_INTERFACE "gps-ni"
+
+/**
+ * Name for the AGPS-RIL interface.
+ */
+#define AGPS_RIL_INTERFACE "agps_ril"
+
+/**
+ * Name for the GPS_Geofencing interface.
+ */
+#define GPS_GEOFENCING_INTERFACE "gps_geofencing"
+
+/**
+ * Name of the GPS Measurements interface.
+ */
+#define GPS_MEASUREMENT_INTERFACE "gps_measurement"
+
+/**
+ * Name of the GPS navigation message interface.
+ */
+#define GPS_NAVIGATION_MESSAGE_INTERFACE "gps_navigation_message"
+
+/**
+ * Name of the GNSS/GPS configuration interface.
+ */
+#define GNSS_CONFIGURATION_INTERFACE "gnss_configuration"
+
+/** Represents a location. */
+typedef struct {
+ /** set to sizeof(GpsLocation) */
+ size_t size;
+ /** Contains GpsLocationFlags bits. */
+ uint16_t flags;
+ /** Represents latitude in degrees. */
+ double latitude;
+ /** Represents longitude in degrees. */
+ double longitude;
+ /**
+ * Represents altitude in meters above the WGS 84 reference ellipsoid.
+ */
+ double altitude;
+ /** Represents speed in meters per second. */
+ float speed;
+ /** Represents heading in degrees. */
+ float bearing;
+ /** Represents expected accuracy in meters. */
+ float accuracy;
+ /** Timestamp for the location fix. */
+ GpsUtcTime timestamp;
+} GpsLocation;
+
+/** Represents the status. */
+typedef struct {
+ /** set to sizeof(GpsStatus) */
+ size_t size;
+ GpsStatusValue status;
+} GpsStatus;
+
+/**
+ * Legacy struct to represents SV information.
+ * Deprecated, to be removed in the next Android release.
+ * Use GnssSvInfo instead.
+ */
+typedef struct {
+ /** set to sizeof(GpsSvInfo) */
+ size_t size;
+ /** Pseudo-random number for the SV. */
+ int prn;
+ /** Signal to noise ratio. */
+ float snr;
+ /** Elevation of SV in degrees. */
+ float elevation;
+ /** Azimuth of SV in degrees. */
+ float azimuth;
+} GpsSvInfo;
+
+typedef struct {
+ /** set to sizeof(GnssSvInfo) */
+ size_t size;
+
+ /**
+ * Pseudo-random number for the SV, or FCN/OSN number for Glonass. The
+ * distinction is made by looking at constellation field. Values should be
+ * in the range of:
+ *
+ * - GPS: 1-32
+ * - SBAS: 120-151, 183-192
+ * - GLONASS: 1-24, the orbital slot number (OSN), if known. Or, if not:
+ * 93-106, the frequency channel number (FCN) (-7 to +6) offset by + 100
+ * i.e. report an FCN of -7 as 93, FCN of 0 as 100, and FCN of +6 as 106.
+ * - QZSS: 193-200
+ * - Galileo: 1-36
+ * - Beidou: 1-37
+ */
+ int16_t svid;
+
+ /**
+ * Defines the constellation of the given SV. Value should be one of those
+ * GNSS_CONSTELLATION_* constants
+ */
+ GnssConstellationType constellation;
+
+ /**
+ * Carrier-to-noise density in dB-Hz, typically in the range [0, 63].
+ * It contains the measured C/N0 value for the signal at the antenna port.
+ *
+ * This is a mandatory value.
+ */
+ float c_n0_dbhz;
+
+ /** Elevation of SV in degrees. */
+ float elevation;
+
+ /** Azimuth of SV in degrees. */
+ float azimuth;
+
+ /**
+ * Contains additional data about the given SV. Value should be one of those
+ * GNSS_SV_FLAGS_* constants
+ */
+ GnssSvFlags flags;
+
+} GnssSvInfo;
+
+/**
+ * Legacy struct to represents SV status.
+ * Deprecated, to be removed in the next Android release.
+ * Use GnssSvStatus instead.
+ */
+typedef struct {
+ /** set to sizeof(GpsSvStatus) */
+ size_t size;
+ int num_svs;
+ GpsSvInfo sv_list[GPS_MAX_SVS];
+ uint32_t ephemeris_mask;
+ uint32_t almanac_mask;
+ uint32_t used_in_fix_mask;
+} GpsSvStatus;
+
+/**
+ * Represents SV status.
+ */
+typedef struct {
+ /** set to sizeof(GnssSvStatus) */
+ size_t size;
+
+ /** Number of GPS SVs currently visible, refers to the SVs stored in sv_list */
+ int num_svs;
+ /**
+ * Pointer to an array of SVs information for all GNSS constellations,
+ * except GPS, which is reported using sv_list
+ */
+ GnssSvInfo gnss_sv_list[GNSS_MAX_SVS];
+
+} GnssSvStatus;
+
+/* CellID for 2G, 3G and LTE, used in AGPS. */
+typedef struct {
+ AGpsRefLocationType type;
+ /** Mobile Country Code. */
+ uint16_t mcc;
+ /** Mobile Network Code .*/
+ uint16_t mnc;
+ /** Location Area Code in 2G, 3G and LTE. In 3G lac is discarded. In LTE,
+ * lac is populated with tac, to ensure that we don't break old clients that
+ * might rely in the old (wrong) behavior.
+ */
+ uint16_t lac;
+ /** Cell id in 2G. Utran Cell id in 3G. Cell Global Id EUTRA in LTE. */
+ uint32_t cid;
+ /** Tracking Area Code in LTE. */
+ uint16_t tac;
+ /** Physical Cell id in LTE (not used in 2G and 3G) */
+ uint16_t pcid;
+} AGpsRefLocationCellID;
+
+typedef struct {
+ uint8_t mac[6];
+} AGpsRefLocationMac;
+
+/** Represents ref locations */
+typedef struct {
+ AGpsRefLocationType type;
+ union {
+ AGpsRefLocationCellID cellID;
+ AGpsRefLocationMac mac;
+ } u;
+} AGpsRefLocation;
+
+/**
+ * Callback with location information. Can only be called from a thread created
+ * by create_thread_cb.
+ */
+typedef void (* gps_location_callback)(GpsLocation* location);
+
+/**
+ * Callback with status information. Can only be called from a thread created by
+ * create_thread_cb.
+ */
+typedef void (* gps_status_callback)(GpsStatus* status);
+
+/**
+ * Legacy callback with SV status information.
+ * Can only be called from a thread created by create_thread_cb.
+ *
+ * This callback is deprecated, and will be removed in the next release. Use
+ * gnss_sv_status_callback() instead.
+ */
+typedef void (* gps_sv_status_callback)(GpsSvStatus* sv_info);
+
+/**
+ * Callback with SV status information.
+ * Can only be called from a thread created by create_thread_cb.
+ */
+typedef void (* gnss_sv_status_callback)(GnssSvStatus* sv_info);
+
+/**
+ * Callback for reporting NMEA sentences. Can only be called from a thread
+ * created by create_thread_cb.
+ */
+typedef void (* gps_nmea_callback)(GpsUtcTime timestamp, const char* nmea, int length);
+
+/**
+ * Callback to inform framework of the GPS engine's capabilities. Capability
+ * parameter is a bit field of GPS_CAPABILITY_* flags.
+ */
+typedef void (* gps_set_capabilities)(uint32_t capabilities);
+
+/**
+ * Callback utility for acquiring the GPS wakelock. This can be used to prevent
+ * the CPU from suspending while handling GPS events.
+ */
+typedef void (* gps_acquire_wakelock)();
+
+/** Callback utility for releasing the GPS wakelock. */
+typedef void (* gps_release_wakelock)();
+
+/** Callback for requesting NTP time */
+typedef void (* gps_request_utc_time)();
+
+/**
+ * Callback for creating a thread that can call into the Java framework code.
+ * This must be used to create any threads that report events up to the
+ * framework.
+ */
+typedef pthread_t (* gps_create_thread)(const char* name, void (*start)(void *), void* arg);
+
+/**
+ * Provides information about how new the underlying GPS/GNSS hardware and
+ * software is.
+ *
+ * This information will be available for Android Test Applications. If a GPS
+ * HAL does not provide this information, it will be considered "2015 or
+ * earlier".
+ *
+ * If a GPS HAL does provide this information, then newer years will need to
+ * meet newer CTS standards. E.g. if the date are 2016 or above, then N+ level
+ * GpsMeasurement support will be verified.
+ */
+typedef struct {
+ /** Set to sizeof(GnssSystemInfo) */
+ size_t size;
+ /* year in which the last update was made to the underlying hardware/firmware
+ * used to capture GNSS signals, e.g. 2016 */
+ uint16_t year_of_hw;
+} GnssSystemInfo;
+
+/**
+ * Callback to inform framework of the engine's hardware version information.
+ */
+typedef void (*gnss_set_system_info)(const GnssSystemInfo* info);
+
+/** New GPS callback structure. */
+typedef struct {
+ /** set to sizeof(GpsCallbacks) */
+ size_t size;
+ gps_location_callback location_cb;
+ gps_status_callback status_cb;
+ gps_sv_status_callback sv_status_cb;
+ gps_nmea_callback nmea_cb;
+ gps_set_capabilities set_capabilities_cb;
+ gps_acquire_wakelock acquire_wakelock_cb;
+ gps_release_wakelock release_wakelock_cb;
+ gps_create_thread create_thread_cb;
+ gps_request_utc_time request_utc_time_cb;
+
+ gnss_set_system_info set_system_info_cb;
+ gnss_sv_status_callback gnss_sv_status_cb;
+} GpsCallbacks;
+
+/** Represents the standard GPS interface. */
+typedef struct {
+ /** set to sizeof(GpsInterface) */
+ size_t size;
+ /**
+ * Opens the interface and provides the callback routines
+ * to the implementation of this interface.
+ */
+ int (*init)( GpsCallbacks* callbacks );
+
+ /** Starts navigating. */
+ int (*start)( void );
+
+ /** Stops navigating. */
+ int (*stop)( void );
+
+ /** Closes the interface. */
+ void (*cleanup)( void );
+
+ /** Injects the current time. */
+ int (*inject_time)(GpsUtcTime time, int64_t timeReference,
+ int uncertainty);
+
+ /**
+ * Injects current location from another location provider (typically cell
+ * ID). Latitude and longitude are measured in degrees expected accuracy is
+ * measured in meters
+ */
+ int (*inject_location)(double latitude, double longitude, float accuracy);
+
+ /**
+ * Specifies that the next call to start will not use the
+ * information defined in the flags. GPS_DELETE_ALL is passed for
+ * a cold start.
+ */
+ void (*delete_aiding_data)(GpsAidingData flags);
+
+ /**
+ * min_interval represents the time between fixes in milliseconds.
+ * preferred_accuracy represents the requested fix accuracy in meters.
+ * preferred_time represents the requested time to first fix in milliseconds.
+ *
+ * 'mode' parameter should be one of GPS_POSITION_MODE_MS_BASED
+ * or GPS_POSITION_MODE_STANDALONE.
+ * It is allowed by the platform (and it is recommended) to fallback to
+ * GPS_POSITION_MODE_MS_BASED if GPS_POSITION_MODE_MS_ASSISTED is passed in, and
+ * GPS_POSITION_MODE_MS_BASED is supported.
+ */
+ int (*set_position_mode)(GpsPositionMode mode, GpsPositionRecurrence recurrence,
+ uint32_t min_interval, uint32_t preferred_accuracy, uint32_t preferred_time);
+
+ /** Get a pointer to extension information. */
+ const void* (*get_extension)(const char* name);
+} GpsInterface;
+
+/**
+ * Callback to request the client to download XTRA data. The client should
+ * download XTRA data and inject it by calling inject_xtra_data(). Can only be
+ * called from a thread created by create_thread_cb.
+ */
+typedef void (* gps_xtra_download_request)();
+
+/** Callback structure for the XTRA interface. */
+typedef struct {
+ gps_xtra_download_request download_request_cb;
+ gps_create_thread create_thread_cb;
+} GpsXtraCallbacks;
+
+/** Extended interface for XTRA support. */
+typedef struct {
+ /** set to sizeof(GpsXtraInterface) */
+ size_t size;
+ /**
+ * Opens the XTRA interface and provides the callback routines
+ * to the implementation of this interface.
+ */
+ int (*init)( GpsXtraCallbacks* callbacks );
+ /** Injects XTRA data into the GPS. */
+ int (*inject_xtra_data)( char* data, int length );
+} GpsXtraInterface;
+
+/** Extended interface for DEBUG support. */
+typedef struct {
+ /** set to sizeof(GpsDebugInterface) */
+ size_t size;
+
+ /**
+ * This function should return any information that the native
+ * implementation wishes to include in a bugreport.
+ */
+ size_t (*get_internal_state)(char* buffer, size_t bufferSize);
+} GpsDebugInterface;
+
+/*
+ * Represents the status of AGPS augmented to support IPv4 and IPv6.
+ */
+typedef struct {
+ /** set to sizeof(AGpsStatus) */
+ size_t size;
+
+ AGpsType type;
+ AGpsStatusValue status;
+
+ /**
+ * Must be set to a valid IPv4 address if the field 'addr' contains an IPv4
+ * address, or set to INADDR_NONE otherwise.
+ */
+ uint32_t ipaddr;
+
+ /**
+ * Must contain the IPv4 (AF_INET) or IPv6 (AF_INET6) address to report.
+ * Any other value of addr.ss_family will be rejected.
+ */
+ struct sockaddr_storage addr;
+} AGpsStatus;
+
+/**
+ * Callback with AGPS status information. Can only be called from a thread
+ * created by create_thread_cb.
+ */
+typedef void (* agps_status_callback)(AGpsStatus* status);
+
+/** Callback structure for the AGPS interface. */
+typedef struct {
+ agps_status_callback status_cb;
+ gps_create_thread create_thread_cb;
+} AGpsCallbacks;
+
+/**
+ * Extended interface for AGPS support, it is augmented to enable to pass
+ * extra APN data.
+ */
+typedef struct {
+ /** set to sizeof(AGpsInterface) */
+ size_t size;
+
+ /**
+ * Opens the AGPS interface and provides the callback routines to the
+ * implementation of this interface.
+ */
+ void (*init)(AGpsCallbacks* callbacks);
+ /**
+ * Deprecated.
+ * If the HAL supports AGpsInterface_v2 this API will not be used, see
+ * data_conn_open_with_apn_ip_type for more information.
+ */
+ int (*data_conn_open)(const char* apn);
+ /**
+ * Notifies that the AGPS data connection has been closed.
+ */
+ int (*data_conn_closed)();
+ /**
+ * Notifies that a data connection is not available for AGPS.
+ */
+ int (*data_conn_failed)();
+ /**
+ * Sets the hostname and port for the AGPS server.
+ */
+ int (*set_server)(AGpsType type, const char* hostname, int port);
+
+ /**
+ * Notifies that a data connection is available and sets the name of the
+ * APN, and its IP type, to be used for SUPL connections.
+ */
+ int (*data_conn_open_with_apn_ip_type)(
+ const char* apn,
+ ApnIpType apnIpType);
+} AGpsInterface;
+
+/** Error codes associated with certificate operations */
+#define AGPS_CERTIFICATE_OPERATION_SUCCESS 0
+#define AGPS_CERTIFICATE_ERROR_GENERIC -100
+#define AGPS_CERTIFICATE_ERROR_TOO_MANY_CERTIFICATES -101
+
+/** A data structure that represents an X.509 certificate using DER encoding */
+typedef struct {
+ size_t length;
+ u_char* data;
+} DerEncodedCertificate;
+
+/**
+ * A type definition for SHA1 Fingerprints used to identify X.509 Certificates
+ * The Fingerprint is a digest of the DER Certificate that uniquely identifies it.
+ */
+typedef struct {
+ u_char data[20];
+} Sha1CertificateFingerprint;
+
+/** AGPS Interface to handle SUPL certificate operations */
+typedef struct {
+ /** set to sizeof(SuplCertificateInterface) */
+ size_t size;
+
+ /**
+ * Installs a set of Certificates used for SUPL connections to the AGPS server.
+ * If needed the HAL should find out internally any certificates that need to be removed to
+ * accommodate the certificates to install.
+ * The certificates installed represent a full set of valid certificates needed to connect to
+ * AGPS SUPL servers.
+ * The list of certificates is required, and all must be available at the same time, when trying
+ * to establish a connection with the AGPS Server.
+ *
+ * Parameters:
+ * certificates - A pointer to an array of DER encoded certificates that are need to be
+ * installed in the HAL.
+ * length - The number of certificates to install.
+ * Returns:
+ * AGPS_CERTIFICATE_OPERATION_SUCCESS if the operation is completed successfully
+ * AGPS_CERTIFICATE_ERROR_TOO_MANY_CERTIFICATES if the HAL cannot store the number of
+ * certificates attempted to be installed, the state of the certificates stored should
+ * remain the same as before on this error case.
+ *
+ * IMPORTANT:
+ * If needed the HAL should find out internally the set of certificates that need to be
+ * removed to accommodate the certificates to install.
+ */
+ int (*install_certificates) ( const DerEncodedCertificate* certificates, size_t length );
+
+ /**
+ * Notifies the HAL that a list of certificates used for SUPL connections are revoked. It is
+ * expected that the given set of certificates is removed from the internal store of the HAL.
+ *
+ * Parameters:
+ * fingerprints - A pointer to an array of SHA1 Fingerprints to identify the set of
+ * certificates to revoke.
+ * length - The number of fingerprints provided.
+ * Returns:
+ * AGPS_CERTIFICATE_OPERATION_SUCCESS if the operation is completed successfully.
+ *
+ * IMPORTANT:
+ * If any of the certificates provided (through its fingerprint) is not known by the HAL,
+ * it should be ignored and continue revoking/deleting the rest of them.
+ */
+ int (*revoke_certificates) ( const Sha1CertificateFingerprint* fingerprints, size_t length );
+} SuplCertificateInterface;
+
+/** Represents an NI request */
+typedef struct {
+ /** set to sizeof(GpsNiNotification) */
+ size_t size;
+
+ /**
+ * An ID generated by HAL to associate NI notifications and UI
+ * responses
+ */
+ int notification_id;
+
+ /**
+ * An NI type used to distinguish different categories of NI
+ * events, such as GPS_NI_TYPE_VOICE, GPS_NI_TYPE_UMTS_SUPL, ...
+ */
+ GpsNiType ni_type;
+
+ /**
+ * Notification/verification options, combinations of GpsNiNotifyFlags constants
+ */
+ GpsNiNotifyFlags notify_flags;
+
+ /**
+ * Timeout period to wait for user response.
+ * Set to 0 for no time out limit.
+ */
+ int timeout;
+
+ /**
+ * Default response when time out.
+ */
+ GpsUserResponseType default_response;
+
+ /**
+ * Requestor ID
+ */
+ char requestor_id[GPS_NI_SHORT_STRING_MAXLEN];
+
+ /**
+ * Notification message. It can also be used to store client_id in some cases
+ */
+ char text[GPS_NI_LONG_STRING_MAXLEN];
+
+ /**
+ * Client name decoding scheme
+ */
+ GpsNiEncodingType requestor_id_encoding;
+
+ /**
+ * Client name decoding scheme
+ */
+ GpsNiEncodingType text_encoding;
+
+ /**
+ * A pointer to extra data. Format:
+ * key_1 = value_1
+ * key_2 = value_2
+ */
+ char extras[GPS_NI_LONG_STRING_MAXLEN];
+
+} GpsNiNotification;
+
+/**
+ * Callback with NI notification. Can only be called from a thread created by
+ * create_thread_cb.
+ */
+typedef void (*gps_ni_notify_callback)(GpsNiNotification *notification);
+
+/** GPS NI callback structure. */
+typedef struct
+{
+ /**
+ * Sends the notification request from HAL to GPSLocationProvider.
+ */
+ gps_ni_notify_callback notify_cb;
+ gps_create_thread create_thread_cb;
+} GpsNiCallbacks;
+
+/**
+ * Extended interface for Network-initiated (NI) support.
+ */
+typedef struct
+{
+ /** set to sizeof(GpsNiInterface) */
+ size_t size;
+
+ /** Registers the callbacks for HAL to use. */
+ void (*init) (GpsNiCallbacks *callbacks);
+
+ /** Sends a response to HAL. */
+ void (*respond) (int notif_id, GpsUserResponseType user_response);
+} GpsNiInterface;
+
+#if defined(__ANDROID_OS__)
+struct gps_device_t {
+ struct hw_device_t common;
+
+ /**
+ * Set the provided lights to the provided values.
+ *
+ * Returns: 0 on succes, error code on failure.
+ */
+ const GpsInterface* (*get_gps_interface)(struct gps_device_t* dev);
+};
+#elif defined(__LINUX_OS__)
+struct gps_device_t {
+ const GpsInterface* (*get_gps_interface)(struct gps_device_t* dev);
+};
+#endif
+
+#define AGPS_RIL_REQUEST_REFLOC_CELLID (1<<0L)
+#define AGPS_RIL_REQUEST_REFLOC_MAC (1<<1L)
+
+typedef void (*agps_ril_request_set_id)(uint32_t flags);
+typedef void (*agps_ril_request_ref_loc)(uint32_t flags);
+
+typedef struct {
+ agps_ril_request_set_id request_setid;
+ agps_ril_request_ref_loc request_refloc;
+ gps_create_thread create_thread_cb;
+} AGpsRilCallbacks;
+
+/** Extended interface for AGPS_RIL support. */
+typedef struct {
+ /** set to sizeof(AGpsRilInterface) */
+ size_t size;
+ /**
+ * Opens the AGPS interface and provides the callback routines
+ * to the implementation of this interface.
+ */
+ void (*init)( AGpsRilCallbacks* callbacks );
+
+ /**
+ * Sets the reference location.
+ */
+ void (*set_ref_location) (const AGpsRefLocation *agps_reflocation, size_t sz_struct);
+ /**
+ * Sets the set ID.
+ */
+ void (*set_set_id) (AGpsSetIDType type, const char* setid);
+
+ /**
+ * Send network initiated message.
+ */
+ void (*ni_message) (uint8_t *msg, size_t len);
+
+ /**
+ * Notify GPS of network status changes.
+ * These parameters match values in the android.net.NetworkInfo class.
+ */
+ void (*update_network_state) (int connected, int type, int roaming, const char* extra_info);
+
+ /**
+ * Notify GPS of network status changes.
+ * These parameters match values in the android.net.NetworkInfo class.
+ */
+ void (*update_network_availability) (int avaiable, const char* apn);
+} AGpsRilInterface;
+
+/**
+ * GPS Geofence.
+ * There are 3 states associated with a Geofence: Inside, Outside, Unknown.
+ * There are 3 transitions: ENTERED, EXITED, UNCERTAIN.
+ *
+ * An example state diagram with confidence level: 95% and Unknown time limit
+ * set as 30 secs is shown below. (confidence level and Unknown time limit are
+ * explained latter)
+ * ____________________________
+ * | Unknown (30 secs) |
+ * """"""""""""""""""""""""""""
+ * ^ | | ^
+ * UNCERTAIN| |ENTERED EXITED| |UNCERTAIN
+ * | v v |
+ * ________ EXITED _________
+ * | Inside | -----------> | Outside |
+ * | | <----------- | |
+ * """""""" ENTERED """""""""
+ *
+ * Inside state: We are 95% confident that the user is inside the geofence.
+ * Outside state: We are 95% confident that the user is outside the geofence
+ * Unknown state: Rest of the time.
+ *
+ * The Unknown state is better explained with an example:
+ *
+ * __________
+ * | c|
+ * | ___ | _______
+ * | |a| | | b |
+ * | """ | """""""
+ * | |
+ * """"""""""
+ * In the diagram above, "a" and "b" are 2 geofences and "c" is the accuracy
+ * circle reported by the GPS subsystem. Now with regard to "b", the system is
+ * confident that the user is outside. But with regard to "a" is not confident
+ * whether it is inside or outside the geofence. If the accuracy remains the
+ * same for a sufficient period of time, the UNCERTAIN transition would be
+ * triggered with the state set to Unknown. If the accuracy improves later, an
+ * appropriate transition should be triggered. This "sufficient period of time"
+ * is defined by the parameter in the add_geofence_area API.
+ * In other words, Unknown state can be interpreted as a state in which the
+ * GPS subsystem isn't confident enough that the user is either inside or
+ * outside the Geofence. It moves to Unknown state only after the expiry of the
+ * timeout.
+ *
+ * The geofence callback needs to be triggered for the ENTERED and EXITED
+ * transitions, when the GPS system is confident that the user has entered
+ * (Inside state) or exited (Outside state) the Geofence. An implementation
+ * which uses a value of 95% as the confidence is recommended. The callback
+ * should be triggered only for the transitions requested by the
+ * add_geofence_area call.
+ *
+ * Even though the diagram and explanation talks about states and transitions,
+ * the callee is only interested in the transistions. The states are mentioned
+ * here for illustrative purposes.
+ *
+ * Startup Scenario: When the device boots up, if an application adds geofences,
+ * and then we get an accurate GPS location fix, it needs to trigger the
+ * appropriate (ENTERED or EXITED) transition for every Geofence it knows about.
+ * By default, all the Geofences will be in the Unknown state.
+ *
+ * When the GPS system is unavailable, gps_geofence_status_callback should be
+ * called to inform the upper layers of the same. Similarly, when it becomes
+ * available the callback should be called. This is a global state while the
+ * UNKNOWN transition described above is per geofence.
+ *
+ * An important aspect to note is that users of this API (framework), will use
+ * other subsystems like wifi, sensors, cell to handle Unknown case and
+ * hopefully provide a definitive state transition to the third party
+ * application. GPS Geofence will just be a signal indicating what the GPS
+ * subsystem knows about the Geofence.
+ *
+ */
+#define GPS_GEOFENCE_ENTERED (1<<0L)
+#define GPS_GEOFENCE_EXITED (1<<1L)
+#define GPS_GEOFENCE_UNCERTAIN (1<<2L)
+
+#define GPS_GEOFENCE_UNAVAILABLE (1<<0L)
+#define GPS_GEOFENCE_AVAILABLE (1<<1L)
+
+#define GPS_GEOFENCE_OPERATION_SUCCESS 0
+#define GPS_GEOFENCE_ERROR_TOO_MANY_GEOFENCES -100
+#define GPS_GEOFENCE_ERROR_ID_EXISTS -101
+#define GPS_GEOFENCE_ERROR_ID_UNKNOWN -102
+#define GPS_GEOFENCE_ERROR_INVALID_TRANSITION -103
+#define GPS_GEOFENCE_ERROR_GENERIC -149
+
+/**
+ * The callback associated with the geofence.
+ * Parameters:
+ * geofence_id - The id associated with the add_geofence_area.
+ * location - The current GPS location.
+ * transition - Can be one of GPS_GEOFENCE_ENTERED, GPS_GEOFENCE_EXITED,
+ * GPS_GEOFENCE_UNCERTAIN.
+ * timestamp - Timestamp when the transition was detected.
+ *
+ * The callback should only be called when the caller is interested in that
+ * particular transition. For instance, if the caller is interested only in
+ * ENTERED transition, then the callback should NOT be called with the EXITED
+ * transition.
+ *
+ * IMPORTANT: If a transition is triggered resulting in this callback, the GPS
+ * subsystem will wake up the application processor, if its in suspend state.
+ */
+typedef void (*gps_geofence_transition_callback) (int32_t geofence_id, GpsLocation* location,
+ int32_t transition, GpsUtcTime timestamp);
+
+/**
+ * The callback associated with the availability of the GPS system for geofencing
+ * monitoring. If the GPS system determines that it cannot monitor geofences
+ * because of lack of reliability or unavailability of the GPS signals, it will
+ * call this callback with GPS_GEOFENCE_UNAVAILABLE parameter.
+ *
+ * Parameters:
+ * status - GPS_GEOFENCE_UNAVAILABLE or GPS_GEOFENCE_AVAILABLE.
+ * last_location - Last known location.
+ */
+typedef void (*gps_geofence_status_callback) (int32_t status, GpsLocation* last_location);
+
+/**
+ * The callback associated with the add_geofence call.
+ *
+ * Parameter:
+ * geofence_id - Id of the geofence.
+ * status - GPS_GEOFENCE_OPERATION_SUCCESS
+ * GPS_GEOFENCE_ERROR_TOO_MANY_GEOFENCES - geofence limit has been reached.
+ * GPS_GEOFENCE_ERROR_ID_EXISTS - geofence with id already exists
+ * GPS_GEOFENCE_ERROR_INVALID_TRANSITION - the monitorTransition contains an
+ * invalid transition
+ * GPS_GEOFENCE_ERROR_GENERIC - for other errors.
+ */
+typedef void (*gps_geofence_add_callback) (int32_t geofence_id, int32_t status);
+
+/**
+ * The callback associated with the remove_geofence call.
+ *
+ * Parameter:
+ * geofence_id - Id of the geofence.
+ * status - GPS_GEOFENCE_OPERATION_SUCCESS
+ * GPS_GEOFENCE_ERROR_ID_UNKNOWN - for invalid id
+ * GPS_GEOFENCE_ERROR_GENERIC for others.
+ */
+typedef void (*gps_geofence_remove_callback) (int32_t geofence_id, int32_t status);
+
+
+/**
+ * The callback associated with the pause_geofence call.
+ *
+ * Parameter:
+ * geofence_id - Id of the geofence.
+ * status - GPS_GEOFENCE_OPERATION_SUCCESS
+ * GPS_GEOFENCE_ERROR_ID_UNKNOWN - for invalid id
+ * GPS_GEOFENCE_ERROR_INVALID_TRANSITION -
+ * when monitor_transitions is invalid
+ * GPS_GEOFENCE_ERROR_GENERIC for others.
+ */
+typedef void (*gps_geofence_pause_callback) (int32_t geofence_id, int32_t status);
+
+/**
+ * The callback associated with the resume_geofence call.
+ *
+ * Parameter:
+ * geofence_id - Id of the geofence.
+ * status - GPS_GEOFENCE_OPERATION_SUCCESS
+ * GPS_GEOFENCE_ERROR_ID_UNKNOWN - for invalid id
+ * GPS_GEOFENCE_ERROR_GENERIC for others.
+ */
+typedef void (*gps_geofence_resume_callback) (int32_t geofence_id, int32_t status);
+
+typedef struct {
+ gps_geofence_transition_callback geofence_transition_callback;
+ gps_geofence_status_callback geofence_status_callback;
+ gps_geofence_add_callback geofence_add_callback;
+ gps_geofence_remove_callback geofence_remove_callback;
+ gps_geofence_pause_callback geofence_pause_callback;
+ gps_geofence_resume_callback geofence_resume_callback;
+ gps_create_thread create_thread_cb;
+} GpsGeofenceCallbacks;
+
+/** Extended interface for GPS_Geofencing support */
+typedef struct {
+ /** set to sizeof(GpsGeofencingInterface) */
+ size_t size;
+
+ /**
+ * Opens the geofence interface and provides the callback routines
+ * to the implementation of this interface.
+ */
+ void (*init)( GpsGeofenceCallbacks* callbacks );
+
+ /**
+ * Add a geofence area. This api currently supports circular geofences.
+ * Parameters:
+ * geofence_id - The id for the geofence. If a geofence with this id
+ * already exists, an error value (GPS_GEOFENCE_ERROR_ID_EXISTS)
+ * should be returned.
+ * latitude, longtitude, radius_meters - The lat, long and radius
+ * (in meters) for the geofence
+ * last_transition - The current state of the geofence. For example, if
+ * the system already knows that the user is inside the geofence,
+ * this will be set to GPS_GEOFENCE_ENTERED. In most cases, it
+ * will be GPS_GEOFENCE_UNCERTAIN.
+ * monitor_transition - Which transitions to monitor. Bitwise OR of
+ * GPS_GEOFENCE_ENTERED, GPS_GEOFENCE_EXITED and
+ * GPS_GEOFENCE_UNCERTAIN.
+ * notification_responsiveness_ms - Defines the best-effort description
+ * of how soon should the callback be called when the transition
+ * associated with the Geofence is triggered. For instance, if set
+ * to 1000 millseconds with GPS_GEOFENCE_ENTERED, the callback
+ * should be called 1000 milliseconds within entering the geofence.
+ * This parameter is defined in milliseconds.
+ * NOTE: This is not to be confused with the rate that the GPS is
+ * polled at. It is acceptable to dynamically vary the rate of
+ * sampling the GPS for power-saving reasons; thus the rate of
+ * sampling may be faster or slower than this.
+ * unknown_timer_ms - The time limit after which the UNCERTAIN transition
+ * should be triggered. This parameter is defined in milliseconds.
+ * See above for a detailed explanation.
+ */
+ void (*add_geofence_area) (int32_t geofence_id, double latitude, double longitude,
+ double radius_meters, int last_transition, int monitor_transitions,
+ int notification_responsiveness_ms, int unknown_timer_ms);
+
+ /**
+ * Pause monitoring a particular geofence.
+ * Parameters:
+ * geofence_id - The id for the geofence.
+ */
+ void (*pause_geofence) (int32_t geofence_id);
+
+ /**
+ * Resume monitoring a particular geofence.
+ * Parameters:
+ * geofence_id - The id for the geofence.
+ * monitor_transitions - Which transitions to monitor. Bitwise OR of
+ * GPS_GEOFENCE_ENTERED, GPS_GEOFENCE_EXITED and
+ * GPS_GEOFENCE_UNCERTAIN.
+ * This supersedes the value associated provided in the
+ * add_geofence_area call.
+ */
+ void (*resume_geofence) (int32_t geofence_id, int monitor_transitions);
+
+ /**
+ * Remove a geofence area. After the function returns, no notifications
+ * should be sent.
+ * Parameter:
+ * geofence_id - The id for the geofence.
+ */
+ void (*remove_geofence_area) (int32_t geofence_id);
+} GpsGeofencingInterface;
+
+/**
+ * Legacy struct to represent an estimate of the GPS clock time.
+ * Deprecated, to be removed in the next Android release.
+ * Use GnssClock instead.
+ */
+typedef struct {
+ /** set to sizeof(GpsClock) */
+ size_t size;
+ GpsClockFlags flags;
+ int16_t leap_second;
+ GpsClockType type;
+ int64_t time_ns;
+ double time_uncertainty_ns;
+ int64_t full_bias_ns;
+ double bias_ns;
+ double bias_uncertainty_ns;
+ double drift_nsps;
+ double drift_uncertainty_nsps;
+} GpsClock;
+
+/**
+ * Represents an estimate of the GPS clock time.
+ */
+typedef struct {
+ /** set to sizeof(GnssClock) */
+ size_t size;
+
+ /**
+ * A set of flags indicating the validity of the fields in this data
+ * structure.
+ */
+ GnssClockFlags flags;
+
+ /**
+ * Leap second data.
+ * The sign of the value is defined by the following equation:
+ * utc_time_ns = time_ns - (full_bias_ns + bias_ns) - leap_second *
+ * 1,000,000,000
+ *
+ * If the data is available 'flags' must contain GNSS_CLOCK_HAS_LEAP_SECOND.
+ */
+ int16_t leap_second;
+
+ /**
+ * The GNSS receiver internal clock value. This is the local hardware clock
+ * value.
+ *
+ * For local hardware clock, this value is expected to be monotonically
+ * increasing while the hardware clock remains power on. (For the case of a
+ * HW clock that is not continuously on, see the
+ * hw_clock_discontinuity_count field). The receiver's estimate of GPS time
+ * can be derived by substracting the sum of full_bias_ns and bias_ns (when
+ * available) from this value.
+ *
+ * This GPS time is expected to be the best estimate of current GPS time
+ * that GNSS receiver can achieve.
+ *
+ * Sub-nanosecond accuracy can be provided by means of the 'bias_ns' field.
+ * The value contains the 'time uncertainty' in it.
+ *
+ * This field is mandatory.
+ */
+ int64_t time_ns;
+
+ /**
+ * 1-Sigma uncertainty associated with the clock's time in nanoseconds.
+ * The uncertainty is represented as an absolute (single sided) value.
+ *
+ * If the data is available, 'flags' must contain
+ * GNSS_CLOCK_HAS_TIME_UNCERTAINTY. This value is effectively zero (it is
+ * the reference local clock, by which all other times and time
+ * uncertainties are measured.) (And thus this field can be not provided,
+ * per GNSS_CLOCK_HAS_TIME_UNCERTAINTY flag, or provided & set to 0.)
+ */
+ double time_uncertainty_ns;
+
+ /**
+ * The difference between hardware clock ('time' field) inside GPS receiver
+ * and the true GPS time since 0000Z, January 6, 1980, in nanoseconds.
+ *
+ * The sign of the value is defined by the following equation:
+ * local estimate of GPS time = time_ns - (full_bias_ns + bias_ns)
+ *
+ * This value is mandatory if the receiver has estimated GPS time. If the
+ * computed time is for a non-GPS constellation, the time offset of that
+ * constellation to GPS has to be applied to fill this value. The error
+ * estimate for the sum of this and the bias_ns is the bias_uncertainty_ns,
+ * and the caller is responsible for using this uncertainty (it can be very
+ * large before the GPS time has been solved for.) If the data is available
+ * 'flags' must contain GNSS_CLOCK_HAS_FULL_BIAS.
+ */
+ int64_t full_bias_ns;
+
+ /**
+ * Sub-nanosecond bias.
+ * The error estimate for the sum of this and the full_bias_ns is the
+ * bias_uncertainty_ns
+ *
+ * If the data is available 'flags' must contain GNSS_CLOCK_HAS_BIAS. If GPS
+ * has computed a position fix. This value is mandatory if the receiver has
+ * estimated GPS time.
+ */
+ double bias_ns;
+
+ /**
+ * 1-Sigma uncertainty associated with the local estimate of GPS time (clock
+ * bias) in nanoseconds. The uncertainty is represented as an absolute
+ * (single sided) value.
+ *
+ * If the data is available 'flags' must contain
+ * GNSS_CLOCK_HAS_BIAS_UNCERTAINTY. This value is mandatory if the receiver
+ * has estimated GPS time.
+ */
+ double bias_uncertainty_ns;
+
+ /**
+ * The clock's drift in nanoseconds (per second).
+ *
+ * A positive value means that the frequency is higher than the nominal
+ * frequency, and that the (full_bias_ns + bias_ns) is growing more positive
+ * over time.
+ *
+ * The value contains the 'drift uncertainty' in it.
+ * If the data is available 'flags' must contain GNSS_CLOCK_HAS_DRIFT.
+ *
+ * This value is mandatory if the receiver has estimated GNSS time
+ */
+ double drift_nsps;
+
+ /**
+ * 1-Sigma uncertainty associated with the clock's drift in nanoseconds (per second).
+ * The uncertainty is represented as an absolute (single sided) value.
+ *
+ * If the data is available 'flags' must contain
+ * GNSS_CLOCK_HAS_DRIFT_UNCERTAINTY. If GPS has computed a position fix this
+ * field is mandatory and must be populated.
+ */
+ double drift_uncertainty_nsps;
+
+ /**
+ * When there are any discontinuities in the HW clock, this field is
+ * mandatory.
+ *
+ * A "discontinuity" is meant to cover the case of a switch from one source
+ * of clock to another. A single free-running crystal oscillator (XO)
+ * should generally not have any discontinuities, and this can be set and
+ * left at 0.
+ *
+ * If, however, the time_ns value (HW clock) is derived from a composite of
+ * sources, that is not as smooth as a typical XO, or is otherwise stopped &
+ * restarted, then this value shall be incremented each time a discontinuity
+ * occurs. (E.g. this value may start at zero at device boot-up and
+ * increment each time there is a change in clock continuity. In the
+ * unlikely event that this value reaches full scale, rollover (not
+ * clamping) is required, such that this value continues to change, during
+ * subsequent discontinuity events.)
+ *
+ * While this number stays the same, between GnssClock reports, it can be
+ * safely assumed that the time_ns value has been running continuously, e.g.
+ * derived from a single, high quality clock (XO like, or better, that's
+ * typically used during continuous GNSS signal sampling.)
+ *
+ * It is expected, esp. during periods where there are few GNSS signals
+ * available, that the HW clock be discontinuity-free as long as possible,
+ * as this avoids the need to use (waste) a GNSS measurement to fully
+ * re-solve for the GPS clock bias and drift, when using the accompanying
+ * measurements, from consecutive GnssData reports.
+ */
+ uint32_t hw_clock_discontinuity_count;
+
+} GnssClock;
+
+/**
+ * Legacy struct to represent a GPS Measurement, it contains raw and computed
+ * information.
+ * Deprecated, to be removed in the next Android release.
+ * Use GnssMeasurement instead.
+ */
+typedef struct {
+ /** set to sizeof(GpsMeasurement) */
+ size_t size;
+ GpsMeasurementFlags flags;
+ int8_t prn;
+ double time_offset_ns;
+ GpsMeasurementState state;
+ int64_t received_gps_tow_ns;
+ int64_t received_gps_tow_uncertainty_ns;
+ double c_n0_dbhz;
+ double pseudorange_rate_mps;
+ double pseudorange_rate_uncertainty_mps;
+ GpsAccumulatedDeltaRangeState accumulated_delta_range_state;
+ double accumulated_delta_range_m;
+ double accumulated_delta_range_uncertainty_m;
+ double pseudorange_m;
+ double pseudorange_uncertainty_m;
+ double code_phase_chips;
+ double code_phase_uncertainty_chips;
+ float carrier_frequency_hz;
+ int64_t carrier_cycles;
+ double carrier_phase;
+ double carrier_phase_uncertainty;
+ GpsLossOfLock loss_of_lock;
+ int32_t bit_number;
+ int16_t time_from_last_bit_ms;
+ double doppler_shift_hz;
+ double doppler_shift_uncertainty_hz;
+ GpsMultipathIndicator multipath_indicator;
+ double snr_db;
+ double elevation_deg;
+ double elevation_uncertainty_deg;
+ double azimuth_deg;
+ double azimuth_uncertainty_deg;
+ bool used_in_fix;
+} GpsMeasurement;
+
+/**
+ * Represents a GNSS Measurement, it contains raw and computed information.
+ *
+ * Independence - All signal measurement information (e.g. sv_time,
+ * pseudorange_rate, multipath_indicator) reported in this struct should be
+ * based on GNSS signal measurements only. You may not synthesize measurements
+ * by calculating or reporting expected measurements based on known or estimated
+ * position, velocity, or time.
+ */
+typedef struct {
+ /** set to sizeof(GpsMeasurement) */
+ size_t size;
+
+ /** A set of flags indicating the validity of the fields in this data structure. */
+ GnssMeasurementFlags flags;
+
+ /**
+ * Satellite vehicle ID number, as defined in GnssSvInfo::svid
+ * This is a mandatory value.
+ */
+ int16_t svid;
+
+ /**
+ * Defines the constellation of the given SV. Value should be one of those
+ * GNSS_CONSTELLATION_* constants
+ */
+ GnssConstellationType constellation;
+
+ /**
+ * Time offset at which the measurement was taken in nanoseconds.
+ * The reference receiver's time is specified by GpsData::clock::time_ns and should be
+ * interpreted in the same way as indicated by GpsClock::type.
+ *
+ * The sign of time_offset_ns is given by the following equation:
+ * measurement time = GpsClock::time_ns + time_offset_ns
+ *
+ * It provides an individual time-stamp for the measurement, and allows sub-nanosecond accuracy.
+ * This is a mandatory value.
+ */
+ double time_offset_ns;
+
+ /**
+ * Per satellite sync state. It represents the current sync state for the associated satellite.
+ * Based on the sync state, the 'received GPS tow' field should be interpreted accordingly.
+ *
+ * This is a mandatory value.
+ */
+ GnssMeasurementState state;
+
+ /**
+ * The received GNSS Time-of-Week at the measurement time, in nanoseconds.
+ * Ensure that this field is independent (see comment at top of
+ * GnssMeasurement struct.)
+ *
+ * For GPS & QZSS, this is:
+ * Received GPS Time-of-Week at the measurement time, in nanoseconds.
+ * The value is relative to the beginning of the current GPS week.
+ *
+ * Given the highest sync state that can be achieved, per each satellite, valid range
+ * for this field can be:
+ * Searching : [ 0 ] : GNSS_MEASUREMENT_STATE_UNKNOWN
+ * C/A code lock : [ 0 1ms ] : GNSS_MEASUREMENT_STATE_CODE_LOCK is set
+ * Bit sync : [ 0 20ms ] : GNSS_MEASUREMENT_STATE_BIT_SYNC is set
+ * Subframe sync : [ 0 6s ] : GNSS_MEASUREMENT_STATE_SUBFRAME_SYNC is set
+ * TOW decoded : [ 0 1week ] : GNSS_MEASUREMENT_STATE_TOW_DECODED is set
+ *
+ * Note well: if there is any ambiguity in integer millisecond,
+ * GNSS_MEASUREMENT_STATE_MSEC_AMBIGUOUS should be set accordingly, in the 'state' field.
+ *
+ * This value must be populated if 'state' != GNSS_MEASUREMENT_STATE_UNKNOWN.
+ *
+ * For Glonass, this is:
+ * Received Glonass time of day, at the measurement time in nanoseconds.
+ *
+ * Given the highest sync state that can be achieved, per each satellite, valid range for
+ * this field can be:
+ * Searching : [ 0 ] : GNSS_MEASUREMENT_STATE_UNKNOWN
+ * C/A code lock : [ 0 1ms ] : GNSS_MEASUREMENT_STATE_CODE_LOCK is set
+ * Symbol sync : [ 0 10ms ] : GNSS_MEASUREMENT_STATE_SYMBOL_SYNC is set
+ * Bit sync : [ 0 20ms ] : GNSS_MEASUREMENT_STATE_BIT_SYNC is set
+ * String sync : [ 0 2s ] : GNSS_MEASUREMENT_STATE_GLO_STRING_SYNC is set
+ * Time of day : [ 0 1day ] : GNSS_MEASUREMENT_STATE_GLO_TOD_DECODED is set
+ *
+ * For Beidou, this is:
+ * Received Beidou time of week, at the measurement time in nanoseconds.
+ *
+ * Given the highest sync state that can be achieved, per each satellite, valid range for
+ * this field can be:
+ * Searching : [ 0 ] : GNSS_MEASUREMENT_STATE_UNKNOWN
+ * C/A code lock: [ 0 1ms ] : GNSS_MEASUREMENT_STATE_CODE_LOCK is set
+ * Bit sync (D2): [ 0 2ms ] : GNSS_MEASUREMENT_STATE_BDS_D2_BIT_SYNC is set
+ * Bit sync (D1): [ 0 20ms ] : GNSS_MEASUREMENT_STATE_BIT_SYNC is set
+ * Subframe (D2): [ 0 0.6s ] : GNSS_MEASUREMENT_STATE_BDS_D2_SUBFRAME_SYNC is set
+ * Subframe (D1): [ 0 6s ] : GNSS_MEASUREMENT_STATE_SUBFRAME_SYNC is set
+ * Time of week : [ 0 1week ] : GNSS_MEASUREMENT_STATE_TOW_DECODED is set
+ *
+ * For Galileo, this is:
+ * Received Galileo time of week, at the measurement time in nanoseconds.
+ *
+ * E1BC code lock : [ 0 4ms ] : GNSS_MEASUREMENT_STATE_GAL_E1BC_CODE_LOCK is set
+ * E1C 2nd code lock: [ 0 100ms ] :
+ * GNSS_MEASUREMENT_STATE_GAL_E1C_2ND_CODE_LOCK is set
+ *
+ * E1B page : [ 0 2s ] : GNSS_MEASUREMENT_STATE_GAL_E1B_PAGE_SYNC is set
+ * Time of week: [ 0 1week ] : GNSS_MEASUREMENT_STATE_TOW_DECODED is set
+ *
+ * For SBAS, this is:
+ * Received SBAS time, at the measurement time in nanoseconds.
+ *
+ * Given the highest sync state that can be achieved, per each satellite,
+ * valid range for this field can be:
+ * Searching : [ 0 ] : GNSS_MEASUREMENT_STATE_UNKNOWN
+ * C/A code lock: [ 0 1ms ] : GNSS_MEASUREMENT_STATE_CODE_LOCK is set
+ * Symbol sync : [ 0 2ms ] : GNSS_MEASUREMENT_STATE_SYMBOL_SYNC is set
+ * Message : [ 0 1s ] : GNSS_MEASUREMENT_STATE_SBAS_SYNC is set
+ */
+ int64_t received_sv_time_in_ns;
+
+ /**
+ * 1-Sigma uncertainty of the Received GPS Time-of-Week in nanoseconds.
+ *
+ * This value must be populated if 'state' != GPS_MEASUREMENT_STATE_UNKNOWN.
+ */
+ int64_t received_sv_time_uncertainty_in_ns;
+
+ /**
+ * Carrier-to-noise density in dB-Hz, typically in the range [0, 63].
+ * It contains the measured C/N0 value for the signal at the antenna port.
+ *
+ * This is a mandatory value.
+ */
+ double c_n0_dbhz;
+
+ /**
+ * Pseudorange rate at the timestamp in m/s. The correction of a given
+ * Pseudorange Rate value includes corrections for receiver and satellite
+ * clock frequency errors. Ensure that this field is independent (see
+ * comment at top of GnssMeasurement struct.)
+ *
+ * It is mandatory to provide the 'uncorrected' 'pseudorange rate', and provide GpsClock's
+ * 'drift' field as well (When providing the uncorrected pseudorange rate, do not apply the
+ * corrections described above.)
+ *
+ * The value includes the 'pseudorange rate uncertainty' in it.
+ * A positive 'uncorrected' value indicates that the SV is moving away from the receiver.
+ *
+ * The sign of the 'uncorrected' 'pseudorange rate' and its relation to the sign of 'doppler
+ * shift' is given by the equation:
+ * pseudorange rate = -k * doppler shift (where k is a constant)
+ *
+ * This should be the most accurate pseudorange rate available, based on
+ * fresh signal measurements from this channel.
+ *
+ * It is mandatory that this value be provided at typical carrier phase PRR
+ * quality (few cm/sec per second of uncertainty, or better) - when signals
+ * are sufficiently strong & stable, e.g. signals from a GPS simulator at >=
+ * 35 dB-Hz.
+ */
+ double pseudorange_rate_mps;
+
+ /**
+ * 1-Sigma uncertainty of the pseudorange_rate_mps.
+ * The uncertainty is represented as an absolute (single sided) value.
+ *
+ * This is a mandatory value.
+ */
+ double pseudorange_rate_uncertainty_mps;
+
+ /**
+ * Accumulated delta range's state. It indicates whether ADR is reset or there is a cycle slip
+ * (indicating loss of lock).
+ *
+ * This is a mandatory value.
+ */
+ GnssAccumulatedDeltaRangeState accumulated_delta_range_state;
+
+ /**
+ * Accumulated delta range since the last channel reset in meters.
+ * A positive value indicates that the SV is moving away from the receiver.
+ *
+ * The sign of the 'accumulated delta range' and its relation to the sign of 'carrier phase'
+ * is given by the equation:
+ * accumulated delta range = -k * carrier phase (where k is a constant)
+ *
+ * This value must be populated if 'accumulated delta range state' != GPS_ADR_STATE_UNKNOWN.
+ * However, it is expected that the data is only accurate when:
+ * 'accumulated delta range state' == GPS_ADR_STATE_VALID.
+ */
+ double accumulated_delta_range_m;
+
+ /**
+ * 1-Sigma uncertainty of the accumulated delta range in meters.
+ * This value must be populated if 'accumulated delta range state' != GPS_ADR_STATE_UNKNOWN.
+ */
+ double accumulated_delta_range_uncertainty_m;
+
+ /**
+ * Carrier frequency at which codes and messages are modulated, it can be L1 or L2.
+ * If the field is not set, the carrier frequency is assumed to be L1.
+ *
+ * If the data is available, 'flags' must contain
+ * GNSS_MEASUREMENT_HAS_CARRIER_FREQUENCY.
+ */
+ float carrier_frequency_hz;
+
+ /**
+ * The number of full carrier cycles between the satellite and the receiver.
+ * The reference frequency is given by the field 'carrier_frequency_hz'.
+ * Indications of possible cycle slips and resets in the accumulation of
+ * this value can be inferred from the accumulated_delta_range_state flags.
+ *
+ * If the data is available, 'flags' must contain
+ * GNSS_MEASUREMENT_HAS_CARRIER_CYCLES.
+ */
+ int64_t carrier_cycles;
+
+ /**
+ * The RF phase detected by the receiver, in the range [0.0, 1.0].
+ * This is usually the fractional part of the complete carrier phase measurement.
+ *
+ * The reference frequency is given by the field 'carrier_frequency_hz'.
+ * The value contains the 'carrier-phase uncertainty' in it.
+ *
+ * If the data is available, 'flags' must contain
+ * GNSS_MEASUREMENT_HAS_CARRIER_PHASE.
+ */
+ double carrier_phase;
+
+ /**
+ * 1-Sigma uncertainty of the carrier-phase.
+ * If the data is available, 'flags' must contain
+ * GNSS_MEASUREMENT_HAS_CARRIER_PHASE_UNCERTAINTY.
+ */
+ double carrier_phase_uncertainty;
+
+ /**
+ * An enumeration that indicates the 'multipath' state of the event.
+ *
+ * The multipath Indicator is intended to report the presence of overlapping
+ * signals that manifest as distorted correlation peaks.
+ *
+ * - if there is a distorted correlation peak shape, report that multipath
+ * is GNSS_MULTIPATH_INDICATOR_PRESENT.
+ * - if there is not a distorted correlation peak shape, report
+ * GNSS_MULTIPATH_INDICATOR_NOT_PRESENT
+ * - if signals are too weak to discern this information, report
+ * GNSS_MULTIPATH_INDICATOR_UNKNOWN
+ *
+ * Example: when doing the standardized overlapping Multipath Performance
+ * test (3GPP TS 34.171) the Multipath indicator should report
+ * GNSS_MULTIPATH_INDICATOR_PRESENT for those signals that are tracked, and
+ * contain multipath, and GNSS_MULTIPATH_INDICATOR_NOT_PRESENT for those
+ * signals that are tracked and do not contain multipath.
+ */
+ GnssMultipathIndicator multipath_indicator;
+
+ /**
+ * Signal-to-noise ratio at correlator output in dB.
+ * If the data is available, 'flags' must contain GNSS_MEASUREMENT_HAS_SNR.
+ * This is the power ratio of the "correlation peak height above the
+ * observed noise floor" to "the noise RMS".
+ */
+ double snr_db;
+} GnssMeasurement;
+
+/**
+ * Legacy struct to represents a reading of GPS measurements.
+ * Deprecated, to be removed in the next Android release.
+ * Use GnssData instead.
+ */
+typedef struct {
+ /** set to sizeof(GpsData) */
+ size_t size;
+ size_t measurement_count;
+ GpsMeasurement measurements[GPS_MAX_MEASUREMENT];
+
+ /** The GPS clock time reading. */
+ GpsClock clock;
+} GpsData;
+
+/**
+ * Represents a reading of GNSS measurements. For devices where GnssSystemInfo's
+ * year_of_hw is set to 2016+, it is mandatory that these be provided, on
+ * request, when the GNSS receiver is searching/tracking signals.
+ *
+ * - Reporting of GPS constellation measurements is mandatory.
+ * - Reporting of all tracked constellations are encouraged.
+ */
+typedef struct {
+ /** set to sizeof(GnssData) */
+ size_t size;
+
+ /** Number of measurements. */
+ size_t measurement_count;
+
+ /** The array of measurements. */
+ GnssMeasurement measurements[GNSS_MAX_MEASUREMENT];
+
+ /** The GPS clock time reading. */
+ GnssClock clock;
+} GnssData;
+
+/**
+ * The legacy callback for to report measurements from the HAL.
+ *
+ * This callback is deprecated, and will be removed in the next release. Use
+ * gnss_measurement_callback() instead.
+ *
+ * Parameters:
+ * data - A data structure containing the measurements.
+ */
+typedef void (*gps_measurement_callback) (GpsData* data);
+
+/**
+ * The callback for to report measurements from the HAL.
+ *
+ * Parameters:
+ * data - A data structure containing the measurements.
+ */
+typedef void (*gnss_measurement_callback) (GnssData* data);
+
+typedef struct {
+ /** set to sizeof(GpsMeasurementCallbacks) */
+ size_t size;
+ gps_measurement_callback measurement_callback;
+ gnss_measurement_callback gnss_measurement_callback;
+} GpsMeasurementCallbacks;
+
+/**
+ * Extended interface for GPS Measurements support.
+ */
+typedef struct {
+ /** Set to sizeof(GpsMeasurementInterface) */
+ size_t size;
+
+ /**
+ * Initializes the interface and registers the callback routines with the HAL.
+ * After a successful call to 'init' the HAL must begin to provide updates at its own phase.
+ *
+ * Status:
+ * GPS_MEASUREMENT_OPERATION_SUCCESS
+ * GPS_MEASUREMENT_ERROR_ALREADY_INIT - if a callback has already been registered without a
+ * corresponding call to 'close'
+ * GPS_MEASUREMENT_ERROR_GENERIC - if any other error occurred, it is expected that the HAL
+ * will not generate any updates upon returning this error code.
+ */
+ int (*init) (GpsMeasurementCallbacks* callbacks);
+
+ /**
+ * Stops updates from the HAL, and unregisters the callback routines.
+ * After a call to stop, the previously registered callbacks must be considered invalid by the
+ * HAL.
+ * If stop is invoked without a previous 'init', this function should perform no work.
+ */
+ void (*close) ();
+
+} GpsMeasurementInterface;
+
+/**
+ * Legacy struct to represents a GPS navigation message (or a fragment of it).
+ * Deprecated, to be removed in the next Android release.
+ * Use GnssNavigationMessage instead.
+ */
+typedef struct {
+ /** set to sizeof(GpsNavigationMessage) */
+ size_t size;
+ int8_t prn;
+ GpsNavigationMessageType type;
+ NavigationMessageStatus status;
+ int16_t message_id;
+ int16_t submessage_id;
+ size_t data_length;
+ uint8_t* data;
+} GpsNavigationMessage;
+
+/** Represents a GPS navigation message (or a fragment of it). */
+typedef struct {
+ /** set to sizeof(GnssNavigationMessage) */
+ size_t size;
+
+ /**
+ * Satellite vehicle ID number, as defined in GnssSvInfo::svid
+ * This is a mandatory value.
+ */
+ int16_t svid;
+
+ /**
+ * The type of message contained in the structure.
+ * This is a mandatory value.
+ */
+ GnssNavigationMessageType type;
+
+ /**
+ * The status of the received navigation message.
+ * No need to send any navigation message that contains words with parity error and cannot be
+ * corrected.
+ */
+ NavigationMessageStatus status;
+
+ /**
+ * Message identifier. It provides an index so the complete Navigation
+ * Message can be assembled.
+ *
+ * - For GPS L1 C/A subframe 4 and 5, this value corresponds to the 'frame
+ * id' of the navigation message, in the range of 1-25 (Subframe 1, 2, 3
+ * does not contain a 'frame id' and this value can be set to -1.)
+ *
+ * - For Glonass L1 C/A, this refers to the frame ID, in the range of 1-5.
+ *
+ * - For BeiDou D1, this refers to the frame number in the range of 1-24
+ *
+ * - For Beidou D2, this refers to the frame number, in the range of 1-120
+ *
+ * - For Galileo F/NAV nominal frame structure, this refers to the subframe
+ * number, in the range of 1-12
+ *
+ * - For Galileo I/NAV nominal frame structure, this refers to the subframe
+ * number in the range of 1-24
+ */
+ int16_t message_id;
+
+ /**
+ * Sub-message identifier. If required by the message 'type', this value
+ * contains a sub-index within the current message (or frame) that is being
+ * transmitted.
+ *
+ * - For GPS L1 C/A, BeiDou D1 & BeiDou D2, the submessage id corresponds to
+ * the subframe number of the navigation message, in the range of 1-5.
+ *
+ * - For Glonass L1 C/A, this refers to the String number, in the range from
+ * 1-15
+ *
+ * - For Galileo F/NAV, this refers to the page type in the range 1-6
+ *
+ * - For Galileo I/NAV, this refers to the word type in the range 1-10+
+ */
+ int16_t submessage_id;
+
+ /**
+ * The length of the data (in bytes) contained in the current message.
+ * If this value is different from zero, 'data' must point to an array of the same size.
+ * e.g. for L1 C/A the size of the sub-frame will be 40 bytes (10 words, 30 bits/word).
+ *
+ * This is a mandatory value.
+ */
+ size_t data_length;
+
+ /**
+ * The data of the reported GPS message. The bytes (or words) specified
+ * using big endian format (MSB first).
+ *
+ * - For GPS L1 C/A, Beidou D1 & Beidou D2, each subframe contains 10 30-bit
+ * words. Each word (30 bits) should be fit into the last 30 bits in a
+ * 4-byte word (skip B31 and B32), with MSB first, for a total of 40
+ * bytes, covering a time period of 6, 6, and 0.6 seconds, respectively.
+ *
+ * - For Glonass L1 C/A, each string contains 85 data bits, including the
+ * checksum. These bits should be fit into 11 bytes, with MSB first (skip
+ * B86-B88), covering a time period of 2 seconds.
+ *
+ * - For Galileo F/NAV, each word consists of 238-bit (sync & tail symbols
+ * excluded). Each word should be fit into 30-bytes, with MSB first (skip
+ * B239, B240), covering a time period of 10 seconds.
+ *
+ * - For Galileo I/NAV, each page contains 2 page parts, even and odd, with
+ * a total of 2x114 = 228 bits, (sync & tail excluded) that should be fit
+ * into 29 bytes, with MSB first (skip B229-B232).
+ */
+ uint8_t* data;
+
+} GnssNavigationMessage;
+
+/**
+ * The legacy callback to report an available fragment of a GPS navigation
+ * messages from the HAL.
+ *
+ * This callback is deprecated, and will be removed in the next release. Use
+ * gnss_navigation_message_callback() instead.
+ *
+ * Parameters:
+ * message - The GPS navigation submessage/subframe representation.
+ */
+typedef void (*gps_navigation_message_callback) (GpsNavigationMessage* message);
+
+/**
+ * The callback to report an available fragment of a GPS navigation messages from the HAL.
+ *
+ * Parameters:
+ * message - The GPS navigation submessage/subframe representation.
+ */
+typedef void (*gnss_navigation_message_callback) (GnssNavigationMessage* message);
+
+typedef struct {
+ /** set to sizeof(GpsNavigationMessageCallbacks) */
+ size_t size;
+ gps_navigation_message_callback navigation_message_callback;
+ gnss_navigation_message_callback gnss_navigation_message_callback;
+} GpsNavigationMessageCallbacks;
+
+/**
+ * Extended interface for GPS navigation message reporting support.
+ */
+typedef struct {
+ /** Set to sizeof(GpsNavigationMessageInterface) */
+ size_t size;
+
+ /**
+ * Initializes the interface and registers the callback routines with the HAL.
+ * After a successful call to 'init' the HAL must begin to provide updates as they become
+ * available.
+ *
+ * Status:
+ * GPS_NAVIGATION_MESSAGE_OPERATION_SUCCESS
+ * GPS_NAVIGATION_MESSAGE_ERROR_ALREADY_INIT - if a callback has already been registered
+ * without a corresponding call to 'close'.
+ * GPS_NAVIGATION_MESSAGE_ERROR_GENERIC - if any other error occurred, it is expected that
+ * the HAL will not generate any updates upon returning this error code.
+ */
+ int (*init) (GpsNavigationMessageCallbacks* callbacks);
+
+ /**
+ * Stops updates from the HAL, and unregisters the callback routines.
+ * After a call to stop, the previously registered callbacks must be considered invalid by the
+ * HAL.
+ * If stop is invoked without a previous 'init', this function should perform no work.
+ */
+ void (*close) ();
+
+} GpsNavigationMessageInterface;
+
+/**
+ * Interface for passing GNSS configuration contents from platform to HAL.
+ */
+typedef struct {
+ /** Set to sizeof(GnssConfigurationInterface) */
+ size_t size;
+
+ /**
+ * Deliver GNSS configuration contents to HAL.
+ * Parameters:
+ * config_data - a pointer to a char array which holds what usually is expected from
+ file(/etc/gps.conf), i.e., a sequence of UTF8 strings separated by '\n'.
+ * length - total number of UTF8 characters in configuraiton data.
+ *
+ * IMPORTANT:
+ * GPS HAL should expect this function can be called multiple times. And it may be
+ * called even when GpsLocationProvider is already constructed and enabled. GPS HAL
+ * should maintain the existing requests for various callback regardless the change
+ * in configuration data.
+ */
+ void (*configuration_update) (const char* config_data, int32_t length);
+} GnssConfigurationInterface;
+
+__END_DECLS
+
+#endif
+
+#endif /* ANDROID_INCLUDE_HARDWARE_GPS_H */
+
diff --git a/src/connectivity/gps/gps_hal/hardware/gps_internal.h b/src/connectivity/gps/gps_hal/hardware/gps_internal.h
new file mode 100644
index 0000000..67a16e8
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/hardware/gps_internal.h
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef ANDROID_INCLUDE_HARDWARE_GPS_INTERNAL_H
+#define ANDROID_INCLUDE_HARDWARE_GPS_INTERNAL_H
+
+#ifdef __LINUX_OS__
+//#include <hardware/gps.h>
+#include "gps.h"
+
+/****************************************************************************
+ * This file contains legacy structs that are deprecated/retired from gps.h *
+ ****************************************************************************/
+
+__BEGIN_DECLS
+
+/**
+ * Legacy GPS callback structure.
+ * Deprecated, to be removed in the next Android release.
+ * Use GpsCallbacks instead.
+ */
+typedef struct {
+ /** set to sizeof(GpsCallbacks_v1) */
+ size_t size;
+ gps_location_callback location_cb;
+ gps_status_callback status_cb;
+ gps_sv_status_callback sv_status_cb;
+ gps_nmea_callback nmea_cb;
+ gps_set_capabilities set_capabilities_cb;
+ gps_acquire_wakelock acquire_wakelock_cb;
+ gps_release_wakelock release_wakelock_cb;
+ gps_create_thread create_thread_cb;
+ gps_request_utc_time request_utc_time_cb;
+} GpsCallbacks_v1;
+
+#pragma pack(push,4)
+// We need to keep the alignment of this data structure to 4-bytes, to ensure that in 64-bit
+// environments the size of this legacy definition does not collide with _v2. Implementations should
+// be using _v2 and _v3, so it's OK to pay the 'unaligned' penalty in 64-bit if an old
+// implementation is still in use.
+
+/**
+ * Legacy struct to represent the status of AGPS.
+ */
+typedef struct {
+ /** set to sizeof(AGpsStatus_v1) */
+ size_t size;
+ AGpsType type;
+ AGpsStatusValue status;
+} AGpsStatus_v1;
+
+#pragma pack(pop)
+
+/**
+ * Legacy struct to represent the status of AGPS augmented with a IPv4 address
+ * field.
+ */
+typedef struct {
+ /** set to sizeof(AGpsStatus_v2) */
+ size_t size;
+ AGpsType type;
+ AGpsStatusValue status;
+
+ /*-------------------- New fields in _v2 --------------------*/
+
+ uint32_t ipaddr;
+} AGpsStatus_v2;
+
+/**
+ * Legacy extended interface for AGPS support.
+ * See AGpsInterface_v2 for more information.
+ */
+typedef struct {
+ /** set to sizeof(AGpsInterface_v1) */
+ size_t size;
+ void (*init)( AGpsCallbacks* callbacks );
+ int (*data_conn_open)( const char* apn );
+ int (*data_conn_closed)();
+ int (*data_conn_failed)();
+ int (*set_server)( AGpsType type, const char* hostname, int port );
+} AGpsInterface_v1;
+
+__END_DECLS
+
+#endif
+#endif /* ANDROID_INCLUDE_HARDWARE_GPS_INTERNAL_H */
diff --git a/src/connectivity/gps/gps_hal/inc/data_coder.h b/src/connectivity/gps/gps_hal/inc/data_coder.h
new file mode 100644
index 0000000..fc66d2f
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/inc/data_coder.h
@@ -0,0 +1,32 @@
+#ifndef __DATA_CODER_H__
+#define __DATA_CODER_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+char get_byte(char* buff, int* offset, int src_len);
+short get_short(char* buff, int* offset, int src_len);
+int get_int(char* buff, int* offset, int src_len);
+long long get_long(char* buff, int* offset, int src_len);
+float get_float(char* buff, int* offset, int src_len);
+double get_double(char* buff, int* offset, int src_len);
+char* get_string(char* buff, int* offset, int src_len);
+char* get_string2(char* buff, int* offset, int src_len);
+int get_binary(char* buff, int* offset, char* output, int src_len, int des_len);
+
+void put_byte(char* buff, int* offset, const char input);
+void put_short(char* buff, int* offset, const short input);
+void put_int(char* buff, int* offset, const int input);
+void put_long(char* buff, int* offset, const long long input);
+void put_float(char* buff, int* offset, const float input);
+void put_double(char* buff, int* offset, const double input);
+void put_string(char* buff, int* offset, const char* input);
+void put_binary(char* buff, int* offset, const char* input, int len);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/src/connectivity/gps/gps_hal/inc/geofencehal_worker.h b/src/connectivity/gps/gps_hal/inc/geofencehal_worker.h
new file mode 100644
index 0000000..e5542dc
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/inc/geofencehal_worker.h
@@ -0,0 +1,142 @@
+#ifndef __GEOFENCE_HAL_WORKER_H__
+#define __GEOFENCE_HAL_WORKER_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+#include <pthread.h>
+#include "data_coder.h"
+
+#if defined(__ANDROID_OS__)
+#include <hardware/gps.h>
+#elif defined(__LINUX_OS__)
+#include "gps.h"
+#endif
+
+//======================================================
+// GFC(GPS HAL) -> MNL
+//======================================================
+#define GEOFENCE_TO_MNL "gfc_to_mnl"
+#define MNL_TO_GEOFENCE "mnl_to_gfc"
+
+#define HAL_GFC_BUFF_SIZE (1 * 1024)
+#define MAX_GOEFENCE 30
+#define GEO_CONFIG_MASK_DISABLE_SMD (1U<<0)
+#ifdef __aarch64__
+#define MTK_64_PLATFORM
+#endif
+
+#define MTK_GFC_SUCCESS (0)
+#define MTK_GFC_ERROR (-1)
+#define MTK_GFC_TIMEOUT (-2)
+
+
+typedef enum {
+ MTK_FLP_MSG_SYS_FLPD_RESET_NTF = 100,
+
+ //HAL messages
+ MTK_FLP_MSG_HAL_INIT_CMD = 200,
+ MTK_FLP_MSG_HAL_START_CMD,
+ MTK_FLP_MSG_HAL_STOP_CMD,
+ MTK_FLP_MSG_HAL_STOP_RSP,
+ MTK_FLP_MSG_HAL_SET_OPTION_CMD,
+ MTK_FLP_MSG_HAL_INJECT_LOC_CMD,
+ MTK_FLP_MSG_HAL_DIAG_INJECT_DATA_NTF,
+ MTK_FLP_MSG_HAL_DIAG_REPORT_DATA_NTF,
+
+ MTK_FLP_MSG_HSB_REPORT_LOC_NTF = 300,
+ MTK_FLP_MSG_OFL_REPORT_LOC_NTF,
+
+ MTK_FLP_MSG_HAL_GEOFENCE_CALLBACK_NTF = 400,
+ MTK_FLP_MSG_HAL_REQUEST_LOC_NTF,
+ MTK_FLP_MSG_HAL_FLUSH_LOC_NTF,
+ MTK_FLP_MSG_HAL_REPORT_STATUS_NTF,
+ MTK_FLP_MSG_OFL_GEOFENCE_CALLBACK_NTF, //for Offload geofence use
+ MTK_FLP_MSG_OFL_GEOFENCE_CMD,
+
+ MTK_FLP_MSG_DC_START_CMD = 500,
+ MTK_FLP_MSG_DC_STOP_CMD,
+ MTK_FLP_MSG_CONN_SCREEN_STATUS, //for AP to connsys screen on/off status exchange
+ MTK_FLP_MSG_END,
+}MTK_FLP_MSG_TYPE;
+
+typedef enum {
+ inside,
+ outside,
+ uncertain
+} SET_STATE;
+
+typedef enum {
+ INIT_GEOFENCE,
+ ADD_GEOFENCE_AREA,
+ PAUSE_GEOFENCE,
+ RESUME_GEOFENCE,
+ REMOVE_GEOFENCE,
+ RECOVER_GEOFENCE,
+ CLEAR_GEOFENCE,
+} MTK_GFC_COMMAND_T;
+
+typedef enum {
+ GEOFENCE_ADD_CALLBACK,
+ GEOFENCE_REMOVE_CALLBACK,
+ GEOFENCE_PAUSE_CALLBACK,
+ GEOFENCE_RESUME_CALLBACK
+} GEOFENCE_CALLBACK_T;
+
+typedef struct mtk_geofence_area {
+ int32_t geofence_id;
+ double latitude;
+ double longitude;
+ double radius;
+ float coordinate_dn;
+ float coordinate_de;
+ int last_transition; /*current state, most cases is GPS_GEOFENCE_UNCERTAIN*/
+ int monitor_transition; /*bitwise or of entered/exited/uncertain*/
+ int notification_period;/*timer interval, period of report transition status*/
+ int unknown_timer;/*continue positioning time limitied while positioning*/
+ int alive;/*geofence status, 1 alive, 0 sleep*/
+ SET_STATE latest_state;/*latest status: outside, inside, uncertain*/
+ uint32_t config;
+} MTK_GEOFENCE_PROPERTY_T;
+
+typedef struct {
+ int type;
+ int length;
+} MTK_FLP_MSG_T;
+
+typedef struct mtk_geofence_callback {
+ int32_t cb_id;
+ int32_t geofence_id;
+ int32_t result;
+} MTK_GEOFENCE_CALLBACK_T;
+
+
+void hal2_geofence_init();
+int is_gfc_exist();
+void hal2_geofence_add_geofences(const MTK_GEOFENCE_PROPERTY_T dbg_fence);
+void hal2_geofence_pause_geofence(const int32_t geofence_id);
+void hal2_geofence_resume_geofence(const int32_t geofence_id, const int monitor_transitions);
+void hal2_geofence_remove_geofences(const int32_t geofence_id);
+void mtk_geo_inject_info_set(int fence_id, float dn, float de);
+void mtk_geo_inject_info_get(int fence_id, float* dn, float* de);
+int check_buff_fence_exist(const int32_t fence_id);
+int set_buff_transition_fence(const int32_t fence_id, const int transition);
+#ifdef MTK_64_PLATFORM
+void mtk_loc_rearrange(unsigned char *loc_in, GpsLocation *loc_out);
+#endif
+
+//Callbacks to GPS HAL
+void mtk_geofence_transition_callbacks_proc(MTK_FLP_MSG_T *prmsg);
+void mtk_geofence_callbacks_proc(MTK_FLP_MSG_T *prmsg);
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/src/connectivity/gps/gps_hal/inc/gps.h b/src/connectivity/gps/gps_hal/inc/gps.h
new file mode 100644
index 0000000..596499c
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/inc/gps.h
@@ -0,0 +1,2233 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_INCLUDE_HARDWARE_GPS_H
+#define ANDROID_INCLUDE_HARDWARE_GPS_H
+
+#include <stdint.h>
+#include <sys/cdefs.h>
+#include <sys/types.h>
+#include <pthread.h>
+#include <sys/socket.h>
+#include <stdbool.h>
+#ifdef __ANDROID_OS__
+#include <hardware/hardware.h>
+#endif
+__BEGIN_DECLS
+
+/*
+ * Enums defined in HIDL in hardware/interfaces are auto-generated and present
+ * in gnss-base.h.
+ */
+
+/* for compatibility */
+
+/*#define GPS_REQUEST_AGPS_DATA_CONN GNSS_REQUEST_AGNSS_DATA_CONN
+#define GPS_RELEASE_AGPS_DATA_CONN GNSS_RELEASE_AGNSS_DATA_CONN
+#define GPS_AGPS_DATA_CONNECTED GNSS_AGNSS_DATA_CONNECTED
+#define GPS_AGPS_DATA_CONN_DONE GNSS_AGNSS_DATA_CONN_DONE
+#define GPS_AGPS_DATA_CONN_FAILED GNSS_AGNSS_DATA_CONN_FAILED
+#define AGPS_RIL_NETWORK_TYPE_MOBILE_MMS AGPS_RIL_NETWORK_TYPE_MMS
+#define AGPS_RIL_NETWORK_TYPE_MOBILE_SUPL AGPS_RIL_NETWORK_TYPE_SUPL
+#define AGPS_RIL_NETWORK_TTYPE_MOBILE_DUN AGPS_RIL_NETWORK_TYPE_DUN
+#define AGPS_RIL_NETWORK_TTYPE_MOBILE_HIPRI AGPS_RIL_NETWORK_TYPE_HIPRI
+#define AGPS_RIL_NETWORK_TTYPE_WIMAX AGPS_RIL_NETWORK_TYPE_WIMAX
+#define GNSS_MULTIPATH_INDICATOR_NOT_PRESENT GNSS_MULTIPATH_INDICATIOR_NOT_PRESENT
+#define AGPS_SETID_TYPE_MSISDN AGPS_SETID_TYPE_MSISDM
+#define GPS_MEASUREMENT_OPERATION_SUCCESS GPS_MEASUREMENT_SUCCESS
+#define GPS_NAVIGATION_MESSAGE_OPERATION_SUCCESS GPS_NAVIGATION_MESSAGE_SUCCESS
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_L1CA GNSS_NAVIGATION_MESSAGE_TYPE_GNSS_L1CA
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_L2CNAV GNSS_NAVIGATION_MESSAGE_TYPE_GNSS_L2CNAV
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_L5CNAV GNSS_NAVIGATION_MESSAGE_TYPE_GNSS_L5CNAV
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_CNAV2 GNSS_NAVIGATION_MESSAGE_TYPE_GNSS_CNAV2
+#define GPS_LOCATION_HAS_ACCURACY GPS_LOCATION_HAS_HORIZONTAL_ACCURACY
+*/
+/**
+ * The id of this module
+ */
+#define GPS_HARDWARE_MODULE_ID "gps"
+
+#define GPS_NAVIGATION_MESSAGE_OPERATION_SUCCESS 0
+#define GPS_NAVIGATION_MESSAGE_ERROR_ALREADY_INIT -100
+#define GPS_NAVIGATION_MESSAGE_ERROR_GENERIC -101
+
+/** Milliseconds since January 1, 1970 */
+typedef int64_t GpsUtcTime;
+
+/** Maximum number of SVs for gps_sv_status_callback(). */
+#define GPS_MAX_SVS 32
+/** Maximum number of SVs for gps_sv_status_callback(). */
+#define GNSS_MAX_SVS 64
+
+/** Maximum number of Measurements in gps_measurement_callback(). */
+#define GPS_MAX_MEASUREMENT 32
+
+/** Maximum number of Measurements in gnss_measurement_callback(). */
+#define GNSS_MAX_MEASUREMENT 64
+
+/** Requested operational mode for GPS operation. */
+typedef uint32_t GpsPositionMode;
+/* IMPORTANT: Note that the following values must match
+ * constants in GpsLocationProvider.java. */
+/** Mode for running GPS standalone (no assistance). */
+#define GPS_POSITION_MODE_STANDALONE 0
+/** AGPS MS-Based mode. */
+#define GPS_POSITION_MODE_MS_BASED 1
+/**
+ * AGPS MS-Assisted mode. This mode is not maintained by the platform anymore.
+ * It is strongly recommended to use GPS_POSITION_MODE_MS_BASED instead.
+ */
+#define GPS_POSITION_MODE_MS_ASSISTED 2
+
+/** Requested recurrence mode for GPS operation. */
+typedef uint32_t GpsPositionRecurrence;
+/* IMPORTANT: Note that the following values must match
+ * constants in GpsLocationProvider.java. */
+/** Receive GPS fixes on a recurring basis at a specified period. */
+#define GPS_POSITION_RECURRENCE_PERIODIC 0
+/** Request a single shot GPS fix. */
+#define GPS_POSITION_RECURRENCE_SINGLE 1
+
+/** GPS status event values. */
+typedef uint16_t GpsStatusValue;
+/* IMPORTANT: Note that the following values must match
+ * constants in GpsLocationProvider.java. */
+/** GPS status unknown. */
+#define GPS_STATUS_NONE 0
+/** GPS has begun navigating. */
+#define GPS_STATUS_SESSION_BEGIN 1
+/** GPS has stopped navigating. */
+#define GPS_STATUS_SESSION_END 2
+/** GPS has powered on but is not navigating. */
+#define GPS_STATUS_ENGINE_ON 3
+/** GPS is powered off. */
+#define GPS_STATUS_ENGINE_OFF 4
+
+/** Flags to indicate which values are valid in a GpsLocation. */
+typedef uint16_t GpsLocationFlags;
+/* IMPORTANT: Note that the following values must match
+ * constants in GpsLocationProvider.java. */
+/** GpsLocation has valid latitude and longitude. */
+#define GPS_LOCATION_HAS_LAT_LONG 0x0001
+/** GpsLocation has valid altitude. */
+#define GPS_LOCATION_HAS_ALTITUDE 0x0002
+/** GpsLocation has valid speed. */
+#define GPS_LOCATION_HAS_SPEED 0x0004
+/** GpsLocation has valid bearing. */
+#define GPS_LOCATION_HAS_BEARING 0x0008
+/** GpsLocation has valid accuracy. */
+#define GPS_LOCATION_HAS_ACCURACY 0x0010
+
+/**
+ * GPS HAL schedules fixes for GPS_POSITION_RECURRENCE_PERIODIC mode. If this is
+ * not set, then the framework will use 1000ms for min_interval and will start
+ * and call start() and stop() to schedule the GPS.
+ */
+#define GPS_CAPABILITY_SCHEDULING (1 << 0)
+/** GPS supports MS-Based AGPS mode */
+#define GPS_CAPABILITY_MSB (1 << 1)
+/** GPS supports MS-Assisted AGPS mode */
+#define GPS_CAPABILITY_MSA (1 << 2)
+/** GPS supports single-shot fixes */
+#define GPS_CAPABILITY_SINGLE_SHOT (1 << 3)
+/** GPS supports on demand time injection */
+#define GPS_CAPABILITY_ON_DEMAND_TIME (1 << 4)
+/** GPS supports Geofencing */
+#define GPS_CAPABILITY_GEOFENCING (1 << 5)
+/** GPS supports Measurements. */
+#define GPS_CAPABILITY_MEASUREMENTS (1 << 6)
+/** GPS supports Navigation Messages */
+#define GPS_CAPABILITY_NAV_MESSAGES (1 << 7)
+
+/**
+ * Flags used to specify which aiding data to delete when calling
+ * delete_aiding_data().
+ */
+typedef uint16_t GpsAidingData;
+/* IMPORTANT: Note that the following values must match
+ * constants in GpsLocationProvider.java. */
+#define GPS_DELETE_EPHEMERIS 0x0001
+#define GPS_DELETE_ALMANAC 0x0002
+#define GPS_DELETE_POSITION 0x0004
+#define GPS_DELETE_TIME 0x0008
+#define GPS_DELETE_IONO 0x0010
+#define GPS_DELETE_UTC 0x0020
+#define GPS_DELETE_HEALTH 0x0040
+#define GPS_DELETE_SVDIR 0x0080
+#define GPS_DELETE_SVSTEER 0x0100
+#define GPS_DELETE_SADATA 0x0200
+#define GPS_DELETE_RTI 0x0400
+#define GPS_DELETE_CELLDB_INFO 0x8000
+#define GPS_DELETE_ALL 0xFFFF
+
+/** AGPS type */
+typedef uint16_t AGpsType;
+#define AGPS_TYPE_SUPL 1
+#define AGPS_TYPE_C2K 2
+
+typedef uint16_t AGpsSetIDType;
+#define AGPS_SETID_TYPE_NONE 0
+#define AGPS_SETID_TYPE_IMSI 1
+#define AGPS_SETID_TYPE_MSISDN 2
+
+typedef uint16_t ApnIpType;
+#define APN_IP_INVALID 0
+#define APN_IP_IPV4 1
+#define APN_IP_IPV6 2
+#define APN_IP_IPV4V6 3
+
+/**
+ * String length constants
+ */
+#define GPS_NI_SHORT_STRING_MAXLEN 256
+#define GPS_NI_LONG_STRING_MAXLEN 2048
+
+/**
+ * GpsNiType constants
+ */
+typedef uint32_t GpsNiType;
+#define GPS_NI_TYPE_VOICE 1
+#define GPS_NI_TYPE_UMTS_SUPL 2
+#define GPS_NI_TYPE_UMTS_CTRL_PLANE 3
+
+/**
+ * GpsNiNotifyFlags constants
+ */
+typedef uint32_t GpsNiNotifyFlags;
+/** NI requires notification */
+#define GPS_NI_NEED_NOTIFY 0x0001
+/** NI requires verification */
+#define GPS_NI_NEED_VERIFY 0x0002
+/** NI requires privacy override, no notification/minimal trace */
+#define GPS_NI_PRIVACY_OVERRIDE 0x0004
+
+/**
+ * GPS NI responses, used to define the response in
+ * NI structures
+ */
+typedef int GpsUserResponseType;
+#define GPS_NI_RESPONSE_ACCEPT 1
+#define GPS_NI_RESPONSE_DENY 2
+#define GPS_NI_RESPONSE_NORESP 3
+
+/**
+ * NI data encoding scheme
+ */
+typedef int GpsNiEncodingType;
+#define GPS_ENC_NONE 0
+#define GPS_ENC_SUPL_GSM_DEFAULT 1
+#define GPS_ENC_SUPL_UTF8 2
+#define GPS_ENC_SUPL_UCS2 3
+#define GPS_ENC_UNKNOWN -1
+
+/** AGPS status event values. */
+typedef uint16_t AGpsStatusValue;
+/** GPS requests data connection for AGPS. */
+#define GPS_REQUEST_AGPS_DATA_CONN 1
+/** GPS releases the AGPS data connection. */
+#define GPS_RELEASE_AGPS_DATA_CONN 2
+/** AGPS data connection initiated */
+#define GPS_AGPS_DATA_CONNECTED 3
+/** AGPS data connection completed */
+#define GPS_AGPS_DATA_CONN_DONE 4
+/** AGPS data connection failed */
+#define GPS_AGPS_DATA_CONN_FAILED 5
+
+typedef uint16_t AGpsRefLocationType;
+#define AGPS_REF_LOCATION_TYPE_GSM_CELLID 1
+#define AGPS_REF_LOCATION_TYPE_UMTS_CELLID 2
+#define AGPS_REF_LOCATION_TYPE_MAC 3
+#define AGPS_REF_LOCATION_TYPE_LTE_CELLID 4
+
+/* Deprecated, to be removed in the next Android release. */
+#define AGPS_REG_LOCATION_TYPE_MAC 3
+
+/** Network types for update_network_state "type" parameter */
+#define AGPS_RIL_NETWORK_TYPE_MOBILE 0
+#define AGPS_RIL_NETWORK_TYPE_WIFI 1
+#define AGPS_RIL_NETWORK_TYPE_MOBILE_MMS 2
+#define AGPS_RIL_NETWORK_TYPE_MOBILE_SUPL 3
+#define AGPS_RIL_NETWORK_TTYPE_MOBILE_DUN 4
+#define AGPS_RIL_NETWORK_TTYPE_MOBILE_HIPRI 5
+#define AGPS_RIL_NETWORK_TTYPE_WIMAX 6
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. */
+typedef uint16_t GpsClockFlags;
+#define GPS_CLOCK_HAS_LEAP_SECOND (1<<0)
+#define GPS_CLOCK_HAS_TIME_UNCERTAINTY (1<<1)
+#define GPS_CLOCK_HAS_FULL_BIAS (1<<2)
+#define GPS_CLOCK_HAS_BIAS (1<<3)
+#define GPS_CLOCK_HAS_BIAS_UNCERTAINTY (1<<4)
+#define GPS_CLOCK_HAS_DRIFT (1<<5)
+#define GPS_CLOCK_HAS_DRIFT_UNCERTAINTY (1<<6)
+
+/**
+ * Flags to indicate what fields in GnssClock are valid.
+ */
+typedef uint16_t GnssClockFlags;
+/** A valid 'leap second' is stored in the data structure. */
+#define GNSS_CLOCK_HAS_LEAP_SECOND (1<<0)
+/** A valid 'time uncertainty' is stored in the data structure. */
+#define GNSS_CLOCK_HAS_TIME_UNCERTAINTY (1<<1)
+/** A valid 'full bias' is stored in the data structure. */
+#define GNSS_CLOCK_HAS_FULL_BIAS (1<<2)
+/** A valid 'bias' is stored in the data structure. */
+#define GNSS_CLOCK_HAS_BIAS (1<<3)
+/** A valid 'bias uncertainty' is stored in the data structure. */
+#define GNSS_CLOCK_HAS_BIAS_UNCERTAINTY (1<<4)
+/** A valid 'drift' is stored in the data structure. */
+#define GNSS_CLOCK_HAS_DRIFT (1<<5)
+/** A valid 'drift uncertainty' is stored in the data structure. */
+#define GNSS_CLOCK_HAS_DRIFT_UNCERTAINTY (1<<6)
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. */
+typedef uint8_t GpsClockType;
+#define GPS_CLOCK_TYPE_UNKNOWN 0
+#define GPS_CLOCK_TYPE_LOCAL_HW_TIME 1
+#define GPS_CLOCK_TYPE_GPS_TIME 2
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. */
+typedef uint32_t GpsMeasurementFlags;
+#define GPS_MEASUREMENT_HAS_SNR (1<<0)
+#define GPS_MEASUREMENT_HAS_ELEVATION (1<<1)
+#define GPS_MEASUREMENT_HAS_ELEVATION_UNCERTAINTY (1<<2)
+#define GPS_MEASUREMENT_HAS_AZIMUTH (1<<3)
+#define GPS_MEASUREMENT_HAS_AZIMUTH_UNCERTAINTY (1<<4)
+#define GPS_MEASUREMENT_HAS_PSEUDORANGE (1<<5)
+#define GPS_MEASUREMENT_HAS_PSEUDORANGE_UNCERTAINTY (1<<6)
+#define GPS_MEASUREMENT_HAS_CODE_PHASE (1<<7)
+#define GPS_MEASUREMENT_HAS_CODE_PHASE_UNCERTAINTY (1<<8)
+#define GPS_MEASUREMENT_HAS_CARRIER_FREQUENCY (1<<9)
+#define GPS_MEASUREMENT_HAS_CARRIER_CYCLES (1<<10)
+#define GPS_MEASUREMENT_HAS_CARRIER_PHASE (1<<11)
+#define GPS_MEASUREMENT_HAS_CARRIER_PHASE_UNCERTAINTY (1<<12)
+#define GPS_MEASUREMENT_HAS_BIT_NUMBER (1<<13)
+#define GPS_MEASUREMENT_HAS_TIME_FROM_LAST_BIT (1<<14)
+#define GPS_MEASUREMENT_HAS_DOPPLER_SHIFT (1<<15)
+#define GPS_MEASUREMENT_HAS_DOPPLER_SHIFT_UNCERTAINTY (1<<16)
+#define GPS_MEASUREMENT_HAS_USED_IN_FIX (1<<17)
+#define GPS_MEASUREMENT_HAS_UNCORRECTED_PSEUDORANGE_RATE (1<<18)
+
+/**
+ * Flags to indicate what fields in GnssMeasurement are valid.
+ */
+typedef uint32_t GnssMeasurementFlags;
+/** A valid 'snr' is stored in the data structure. */
+#define GNSS_MEASUREMENT_HAS_SNR (1<<0)
+/** A valid 'carrier frequency' is stored in the data structure. */
+#define GNSS_MEASUREMENT_HAS_CARRIER_FREQUENCY (1<<9)
+/** A valid 'carrier cycles' is stored in the data structure. */
+#define GNSS_MEASUREMENT_HAS_CARRIER_CYCLES (1<<10)
+/** A valid 'carrier phase' is stored in the data structure. */
+#define GNSS_MEASUREMENT_HAS_CARRIER_PHASE (1<<11)
+/** A valid 'carrier phase uncertainty' is stored in the data structure. */
+#define GNSS_MEASUREMENT_HAS_CARRIER_PHASE_UNCERTAINTY (1<<12)
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. */
+typedef uint8_t GpsLossOfLock;
+#define GPS_LOSS_OF_LOCK_UNKNOWN 0
+#define GPS_LOSS_OF_LOCK_OK 1
+#define GPS_LOSS_OF_LOCK_CYCLE_SLIP 2
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. Use GnssMultipathIndicator instead.
+ */
+typedef uint8_t GpsMultipathIndicator;
+#define GPS_MULTIPATH_INDICATOR_UNKNOWN 0
+#define GPS_MULTIPATH_INDICATOR_DETECTED 1
+#define GPS_MULTIPATH_INDICATOR_NOT_USED 2
+
+/**
+ * Enumeration of available values for the GNSS Measurement's multipath
+ * indicator.
+ */
+typedef uint8_t GnssMultipathIndicator;
+/** The indicator is not available or unknown. */
+#define GNSS_MULTIPATH_INDICATOR_UNKNOWN 0
+/** The measurement is indicated to be affected by multipath. */
+#define GNSS_MULTIPATH_INDICATOR_PRESENT 1
+/** The measurement is indicated to be not affected by multipath. */
+#define GNSS_MULTIPATH_INDICATOR_NOT_PRESENT 2
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. */
+typedef uint16_t GpsMeasurementState;
+#define GPS_MEASUREMENT_STATE_UNKNOWN 0
+#define GPS_MEASUREMENT_STATE_CODE_LOCK (1<<0)
+#define GPS_MEASUREMENT_STATE_BIT_SYNC (1<<1)
+#define GPS_MEASUREMENT_STATE_SUBFRAME_SYNC (1<<2)
+#define GPS_MEASUREMENT_STATE_TOW_DECODED (1<<3)
+#define GPS_MEASUREMENT_STATE_MSEC_AMBIGUOUS (1<<4)
+
+/**
+ * Flags indicating the GNSS measurement state.
+ *
+ * The expected behavior here is for GPS HAL to set all the flags that applies.
+ * For example, if the state for a satellite is only C/A code locked and bit
+ * synchronized, and there is still millisecond ambiguity, the state should be
+ * set as:
+ *
+ * GNSS_MEASUREMENT_STATE_CODE_LOCK | GNSS_MEASUREMENT_STATE_BIT_SYNC |
+ * GNSS_MEASUREMENT_STATE_MSEC_AMBIGUOUS
+ *
+ * If GNSS is still searching for a satellite, the corresponding state should be
+ * set to GNSS_MEASUREMENT_STATE_UNKNOWN(0).
+ */
+typedef uint32_t GnssMeasurementState;
+#define GNSS_MEASUREMENT_STATE_UNKNOWN 0
+#define GNSS_MEASUREMENT_STATE_CODE_LOCK (1<<0)
+#define GNSS_MEASUREMENT_STATE_BIT_SYNC (1<<1)
+#define GNSS_MEASUREMENT_STATE_SUBFRAME_SYNC (1<<2)
+#define GNSS_MEASUREMENT_STATE_TOW_DECODED (1<<3)
+#define GNSS_MEASUREMENT_STATE_MSEC_AMBIGUOUS (1<<4)
+#define GNSS_MEASUREMENT_STATE_SYMBOL_SYNC (1<<5)
+#define GNSS_MEASUREMENT_STATE_GLO_STRING_SYNC (1<<6)
+#define GNSS_MEASUREMENT_STATE_GLO_TOD_DECODED (1<<7)
+#define GNSS_MEASUREMENT_STATE_BDS_D2_BIT_SYNC (1<<8)
+#define GNSS_MEASUREMENT_STATE_BDS_D2_SUBFRAME_SYNC (1<<9)
+#define GNSS_MEASUREMENT_STATE_GAL_E1BC_CODE_LOCK (1<<10)
+#define GNSS_MEASUREMENT_STATE_GAL_E1C_2ND_CODE_LOCK (1<<11)
+#define GNSS_MEASUREMENT_STATE_GAL_E1B_PAGE_SYNC (1<<12)
+#define GNSS_MEASUREMENT_STATE_SBAS_SYNC (1<<13)
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. */
+typedef uint16_t GpsAccumulatedDeltaRangeState;
+#define GPS_ADR_STATE_UNKNOWN 0
+#define GPS_ADR_STATE_VALID (1<<0)
+#define GPS_ADR_STATE_RESET (1<<1)
+#define GPS_ADR_STATE_CYCLE_SLIP (1<<2)
+
+/**
+ * Flags indicating the Accumulated Delta Range's states.
+ */
+typedef uint16_t GnssAccumulatedDeltaRangeState;
+#define GNSS_ADR_STATE_UNKNOWN 0
+#define GNSS_ADR_STATE_VALID (1<<0)
+#define GNSS_ADR_STATE_RESET (1<<1)
+#define GNSS_ADR_STATE_CYCLE_SLIP (1<<2)
+
+/* The following typedef together with its constants below are deprecated, and
+ * will be removed in the next release. */
+typedef uint8_t GpsNavigationMessageType;
+#define GPS_NAVIGATION_MESSAGE_TYPE_UNKNOWN 0
+#define GPS_NAVIGATION_MESSAGE_TYPE_L1CA 1
+#define GPS_NAVIGATION_MESSAGE_TYPE_L2CNAV 2
+#define GPS_NAVIGATION_MESSAGE_TYPE_L5CNAV 3
+#define GPS_NAVIGATION_MESSAGE_TYPE_CNAV2 4
+
+/**
+ * Enumeration of available values to indicate the GNSS Navigation message
+ * types.
+ *
+ * For convenience, first byte is the GnssConstellationType on which that signal
+ * is typically transmitted
+ */
+typedef int16_t GnssNavigationMessageType;
+
+#define GNSS_NAVIGATION_MESSAGE_TYPE_UNKNOWN 0
+/** GPS L1 C/A message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_L1CA 0x0101
+/** GPS L2-CNAV message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_L2CNAV 0x0102
+/** GPS L5-CNAV message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_L5CNAV 0x0103
+/** GPS CNAV-2 message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GPS_CNAV2 0x0104
+/** Glonass L1 CA message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GLO_L1CA 0x0301
+/** Beidou D1 message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_BDS_D1 0x0501
+/** Beidou D2 message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_BDS_D2 0x0502
+/** Galileo I/NAV message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GAL_I 0x0601
+/** Galileo F/NAV message contained in the structure. */
+#define GNSS_NAVIGATION_MESSAGE_TYPE_GAL_F 0x0602
+
+/**
+ * Status of Navigation Message
+ * When a message is received properly without any parity error in its navigation words, the
+ * status should be set to NAV_MESSAGE_STATUS_PARITY_PASSED. But if a message is received
+ * with words that failed parity check, but GPS is able to correct those words, the status
+ * should be set to NAV_MESSAGE_STATUS_PARITY_REBUILT.
+ * No need to send any navigation message that contains words with parity error and cannot be
+ * corrected.
+ */
+typedef uint16_t NavigationMessageStatus;
+#define NAV_MESSAGE_STATUS_UNKNOWN 0
+#define NAV_MESSAGE_STATUS_PARITY_PASSED (1<<0)
+#define NAV_MESSAGE_STATUS_PARITY_REBUILT (1<<1)
+
+/* This constant is deprecated, and will be removed in the next release. */
+#define NAV_MESSAGE_STATUS_UNKONW 0
+
+/**
+ * Flags that indicate information about the satellite
+ */
+typedef uint8_t GnssSvFlags;
+#define GNSS_SV_FLAGS_NONE 0
+#define GNSS_SV_FLAGS_HAS_EPHEMERIS_DATA (1 << 0)
+#define GNSS_SV_FLAGS_HAS_ALMANAC_DATA (1 << 1)
+#define GNSS_SV_FLAGS_USED_IN_FIX (1 << 2)
+
+/**
+ * Constellation type of GnssSvInfo
+ */
+typedef uint8_t GnssConstellationType;
+#define GNSS_CONSTELLATION_UNKNOWN 0
+#define GNSS_CONSTELLATION_GPS 1
+#define GNSS_CONSTELLATION_SBAS 2
+#define GNSS_CONSTELLATION_GLONASS 3
+#define GNSS_CONSTELLATION_QZSS 4
+#define GNSS_CONSTELLATION_BEIDOU 5
+#define GNSS_CONSTELLATION_GALILEO 6
+
+/**
+ * Name for the GPS XTRA interface.
+ */
+#define GPS_XTRA_INTERFACE "gps-xtra"
+
+/**
+ * Name for the GPS DEBUG interface.
+ */
+#define GPS_DEBUG_INTERFACE "gps-debug"
+
+/**
+ * Name for the AGPS interface.
+ */
+#define AGPS_INTERFACE "agps"
+
+/**
+ * Name of the Supl Certificate interface.
+ */
+#define SUPL_CERTIFICATE_INTERFACE "supl-certificate"
+
+/**
+ * Name for NI interface
+ */
+#define GPS_NI_INTERFACE "gps-ni"
+
+/**
+ * Name for the AGPS-RIL interface.
+ */
+#define AGPS_RIL_INTERFACE "agps_ril"
+
+/**
+ * Name for the GPS_Geofencing interface.
+ */
+#define GPS_GEOFENCING_INTERFACE "gps_geofencing"
+
+/**
+ * Name of the GPS Measurements interface.
+ */
+#define GPS_MEASUREMENT_INTERFACE "gps_measurement"
+
+/**
+ * Name of the GPS navigation message interface.
+ */
+#define GPS_NAVIGATION_MESSAGE_INTERFACE "gps_navigation_message"
+
+/**
+ * Name of the GNSS/GPS configuration interface.
+ */
+#define GNSS_CONFIGURATION_INTERFACE "gnss_configuration"
+
+/** Represents a location. */
+typedef struct {
+ /** set to sizeof(GpsLocation) */
+ size_t size;
+ /** Contains GpsLocationFlags bits. */
+ uint16_t flags;
+ /** Represents latitude in degrees. */
+ double latitude;
+ /** Represents longitude in degrees. */
+ double longitude;
+ /**
+ * Represents altitude in meters above the WGS 84 reference ellipsoid.
+ */
+ double altitude;
+ /** Represents speed in meters per second. */
+ float speed;
+ /** Represents heading in degrees. */
+ float bearing;
+ /** Represents expected accuracy in meters. */
+ float accuracy;
+ /** Timestamp for the location fix. */
+ GpsUtcTime timestamp;
+} GpsLocation;
+
+/** Represents the status. */
+typedef struct {
+ /** set to sizeof(GpsStatus) */
+ size_t size;
+ GpsStatusValue status;
+} GpsStatus;
+
+/**
+ * Legacy struct to represents SV information.
+ * Deprecated, to be removed in the next Android release.
+ * Use GnssSvInfo instead.
+ */
+typedef struct {
+ /** set to sizeof(GpsSvInfo) */
+ size_t size;
+ /** Pseudo-random number for the SV. */
+ int prn;
+ /** Signal to noise ratio. */
+ float snr;
+ /** Elevation of SV in degrees. */
+ float elevation;
+ /** Azimuth of SV in degrees. */
+ float azimuth;
+} GpsSvInfo;
+
+typedef struct {
+ /** set to sizeof(GnssSvInfo) */
+ size_t size;
+
+ /**
+ * Pseudo-random number for the SV, or FCN/OSN number for Glonass. The
+ * distinction is made by looking at constellation field. Values should be
+ * in the range of:
+ *
+ * - GPS: 1-32
+ * - SBAS: 120-151, 183-192
+ * - GLONASS: 1-24, the orbital slot number (OSN), if known. Or, if not:
+ * 93-106, the frequency channel number (FCN) (-7 to +6) offset by + 100
+ * i.e. report an FCN of -7 as 93, FCN of 0 as 100, and FCN of +6 as 106.
+ * - QZSS: 193-200
+ * - Galileo: 1-36
+ * - Beidou: 1-37
+ */
+ int16_t svid;
+
+ /**
+ * Defines the constellation of the given SV. Value should be one of those
+ * GNSS_CONSTELLATION_* constants
+ */
+ GnssConstellationType constellation;
+
+ /**
+ * Carrier-to-noise density in dB-Hz, typically in the range [0, 63].
+ * It contains the measured C/N0 value for the signal at the antenna port.
+ *
+ * This is a mandatory value.
+ */
+ float c_n0_dbhz;
+
+ /** Elevation of SV in degrees. */
+ float elevation;
+
+ /** Azimuth of SV in degrees. */
+ float azimuth;
+
+ /**
+ * Contains additional data about the given SV. Value should be one of those
+ * GNSS_SV_FLAGS_* constants
+ */
+ GnssSvFlags flags;
+
+} GnssSvInfo;
+
+/**
+ * Legacy struct to represents SV status.
+ * Deprecated, to be removed in the next Android release.
+ * Use GnssSvStatus instead.
+ */
+typedef struct {
+ /** set to sizeof(GpsSvStatus) */
+ size_t size;
+ int num_svs;
+ GpsSvInfo sv_list[GPS_MAX_SVS];
+ uint32_t ephemeris_mask;
+ uint32_t almanac_mask;
+ uint32_t used_in_fix_mask;
+} GpsSvStatus;
+
+/**
+ * Represents SV status.
+ */
+typedef struct {
+ /** set to sizeof(GnssSvStatus) */
+ size_t size;
+
+ /** Number of GPS SVs currently visible, refers to the SVs stored in sv_list */
+ int num_svs;
+ /**
+ * Pointer to an array of SVs information for all GNSS constellations,
+ * except GPS, which is reported using sv_list
+ */
+ GnssSvInfo gnss_sv_list[GNSS_MAX_SVS];
+
+} GnssSvStatus;
+
+/* CellID for 2G, 3G and LTE, used in AGPS. */
+typedef struct {
+ AGpsRefLocationType type;
+ /** Mobile Country Code. */
+ uint16_t mcc;
+ /** Mobile Network Code .*/
+ uint16_t mnc;
+ /** Location Area Code in 2G, 3G and LTE. In 3G lac is discarded. In LTE,
+ * lac is populated with tac, to ensure that we don't break old clients that
+ * might rely in the old (wrong) behavior.
+ */
+ uint16_t lac;
+ /** Cell id in 2G. Utran Cell id in 3G. Cell Global Id EUTRA in LTE. */
+ uint32_t cid;
+ /** Tracking Area Code in LTE. */
+ uint16_t tac;
+ /** Physical Cell id in LTE (not used in 2G and 3G) */
+ uint16_t pcid;
+} AGpsRefLocationCellID;
+
+typedef struct {
+ uint8_t mac[6];
+} AGpsRefLocationMac;
+
+/** Represents ref locations */
+typedef struct {
+ AGpsRefLocationType type;
+ union {
+ AGpsRefLocationCellID cellID;
+ AGpsRefLocationMac mac;
+ } u;
+} AGpsRefLocation;
+
+/**
+ * Callback with location information. Can only be called from a thread created
+ * by create_thread_cb.
+ */
+typedef void (* gps_location_callback)(GpsLocation* location);
+
+/**
+ * Callback with status information. Can only be called from a thread created by
+ * create_thread_cb.
+ */
+typedef void (* gps_status_callback)(GpsStatus* status);
+
+/**
+ * Legacy callback with SV status information.
+ * Can only be called from a thread created by create_thread_cb.
+ *
+ * This callback is deprecated, and will be removed in the next release. Use
+ * gnss_sv_status_callback() instead.
+ */
+typedef void (* gps_sv_status_callback)(GpsSvStatus* sv_info);
+
+/**
+ * Callback with SV status information.
+ * Can only be called from a thread created by create_thread_cb.
+ */
+typedef void (* gnss_sv_status_callback)(GnssSvStatus* sv_info);
+
+/**
+ * Callback for reporting NMEA sentences. Can only be called from a thread
+ * created by create_thread_cb.
+ */
+typedef void (* gps_nmea_callback)(GpsUtcTime timestamp, const char* nmea, int length);
+
+/**
+ * Callback to inform framework of the GPS engine's capabilities. Capability
+ * parameter is a bit field of GPS_CAPABILITY_* flags.
+ */
+typedef void (* gps_set_capabilities)(uint32_t capabilities);
+
+/**
+ * Callback utility for acquiring the GPS wakelock. This can be used to prevent
+ * the CPU from suspending while handling GPS events.
+ */
+typedef void (* gps_acquire_wakelock)();
+
+/** Callback utility for releasing the GPS wakelock. */
+typedef void (* gps_release_wakelock)();
+
+/** Callback for requesting NTP time */
+typedef void (* gps_request_utc_time)();
+
+/**
+ * Callback for creating a thread that can call into the Java framework code.
+ * This must be used to create any threads that report events up to the
+ * framework.
+ */
+typedef pthread_t (* gps_create_thread)(const char* name, void (*start)(void *), void* arg);
+
+/**
+ * Provides information about how new the underlying GPS/GNSS hardware and
+ * software is.
+ *
+ * This information will be available for Android Test Applications. If a GPS
+ * HAL does not provide this information, it will be considered "2015 or
+ * earlier".
+ *
+ * If a GPS HAL does provide this information, then newer years will need to
+ * meet newer CTS standards. E.g. if the date are 2016 or above, then N+ level
+ * GpsMeasurement support will be verified.
+ */
+typedef struct {
+ /** Set to sizeof(GnssSystemInfo) */
+ size_t size;
+ /* year in which the last update was made to the underlying hardware/firmware
+ * used to capture GNSS signals, e.g. 2016 */
+ uint16_t year_of_hw;
+} GnssSystemInfo;
+
+/**
+ * Callback to inform framework of the engine's hardware version information.
+ */
+typedef void (*gnss_set_system_info)(const GnssSystemInfo* info);
+
+/** New GPS callback structure. */
+typedef struct {
+ /** set to sizeof(GpsCallbacks) */
+ size_t size;
+ gps_location_callback location_cb;
+ gps_status_callback status_cb;
+ gps_sv_status_callback sv_status_cb;
+ gps_nmea_callback nmea_cb;
+ gps_set_capabilities set_capabilities_cb;
+ gps_acquire_wakelock acquire_wakelock_cb;
+ gps_release_wakelock release_wakelock_cb;
+ gps_create_thread create_thread_cb;
+ gps_request_utc_time request_utc_time_cb;
+
+ gnss_set_system_info set_system_info_cb;
+ gnss_sv_status_callback gnss_sv_status_cb;
+} GpsCallbacks;
+
+/** Represents the standard GPS interface. */
+typedef struct {
+ /** set to sizeof(GpsInterface) */
+ size_t size;
+ /**
+ * Opens the interface and provides the callback routines
+ * to the implementation of this interface.
+ */
+ int (*init)( GpsCallbacks* callbacks );
+
+ /** Starts navigating. */
+ int (*start)( void );
+
+ /** Stops navigating. */
+ int (*stop)( void );
+
+ /** Closes the interface. */
+ void (*cleanup)( void );
+
+ /** Injects the current time. */
+ int (*inject_time)(GpsUtcTime time, int64_t timeReference,
+ int uncertainty);
+
+ /**
+ * Injects current location from another location provider (typically cell
+ * ID). Latitude and longitude are measured in degrees expected accuracy is
+ * measured in meters
+ */
+ int (*inject_location)(double latitude, double longitude, float accuracy);
+
+ /**
+ * Specifies that the next call to start will not use the
+ * information defined in the flags. GPS_DELETE_ALL is passed for
+ * a cold start.
+ */
+ void (*delete_aiding_data)(GpsAidingData flags);
+
+ /**
+ * min_interval represents the time between fixes in milliseconds.
+ * preferred_accuracy represents the requested fix accuracy in meters.
+ * preferred_time represents the requested time to first fix in milliseconds.
+ *
+ * 'mode' parameter should be one of GPS_POSITION_MODE_MS_BASED
+ * or GPS_POSITION_MODE_STANDALONE.
+ * It is allowed by the platform (and it is recommended) to fallback to
+ * GPS_POSITION_MODE_MS_BASED if GPS_POSITION_MODE_MS_ASSISTED is passed in, and
+ * GPS_POSITION_MODE_MS_BASED is supported.
+ */
+ int (*set_position_mode)(GpsPositionMode mode, GpsPositionRecurrence recurrence,
+ uint32_t min_interval, uint32_t preferred_accuracy, uint32_t preferred_time);
+
+ /** Get a pointer to extension information. */
+ const void* (*get_extension)(const char* name);
+} GpsInterface;
+
+/**
+ * Callback to request the client to download XTRA data. The client should
+ * download XTRA data and inject it by calling inject_xtra_data(). Can only be
+ * called from a thread created by create_thread_cb.
+ */
+typedef void (* gps_xtra_download_request)();
+
+/** Callback structure for the XTRA interface. */
+typedef struct {
+ gps_xtra_download_request download_request_cb;
+ gps_create_thread create_thread_cb;
+} GpsXtraCallbacks;
+
+/** Extended interface for XTRA support. */
+typedef struct {
+ /** set to sizeof(GpsXtraInterface) */
+ size_t size;
+ /**
+ * Opens the XTRA interface and provides the callback routines
+ * to the implementation of this interface.
+ */
+ int (*init)( GpsXtraCallbacks* callbacks );
+ /** Injects XTRA data into the GPS. */
+ int (*inject_xtra_data)( char* data, int length );
+} GpsXtraInterface;
+
+/** Extended interface for DEBUG support. */
+typedef struct {
+ /** set to sizeof(GpsDebugInterface) */
+ size_t size;
+
+ /**
+ * This function should return any information that the native
+ * implementation wishes to include in a bugreport.
+ */
+ size_t (*get_internal_state)(char* buffer, size_t bufferSize);
+} GpsDebugInterface;
+
+/*
+ * Represents the status of AGPS augmented to support IPv4 and IPv6.
+ */
+typedef struct {
+ /** set to sizeof(AGpsStatus) */
+ size_t size;
+
+ AGpsType type;
+ AGpsStatusValue status;
+
+ /**
+ * Must be set to a valid IPv4 address if the field 'addr' contains an IPv4
+ * address, or set to INADDR_NONE otherwise.
+ */
+ uint32_t ipaddr;
+
+ /**
+ * Must contain the IPv4 (AF_INET) or IPv6 (AF_INET6) address to report.
+ * Any other value of addr.ss_family will be rejected.
+ */
+ struct sockaddr_storage addr;
+} AGpsStatus;
+
+/**
+ * Callback with AGPS status information. Can only be called from a thread
+ * created by create_thread_cb.
+ */
+typedef void (* agps_status_callback)(AGpsStatus* status);
+
+/** Callback structure for the AGPS interface. */
+typedef struct {
+ agps_status_callback status_cb;
+ gps_create_thread create_thread_cb;
+} AGpsCallbacks;
+
+/**
+ * Extended interface for AGPS support, it is augmented to enable to pass
+ * extra APN data.
+ */
+typedef struct {
+ /** set to sizeof(AGpsInterface) */
+ size_t size;
+
+ /**
+ * Opens the AGPS interface and provides the callback routines to the
+ * implementation of this interface.
+ */
+ void (*init)(AGpsCallbacks* callbacks);
+ /**
+ * Deprecated.
+ * If the HAL supports AGpsInterface_v2 this API will not be used, see
+ * data_conn_open_with_apn_ip_type for more information.
+ */
+ int (*data_conn_open)(const char* apn);
+ /**
+ * Notifies that the AGPS data connection has been closed.
+ */
+ int (*data_conn_closed)();
+ /**
+ * Notifies that a data connection is not available for AGPS.
+ */
+ int (*data_conn_failed)();
+ /**
+ * Sets the hostname and port for the AGPS server.
+ */
+ int (*set_server)(AGpsType type, const char* hostname, int port);
+
+ /**
+ * Notifies that a data connection is available and sets the name of the
+ * APN, and its IP type, to be used for SUPL connections.
+ */
+ int (*data_conn_open_with_apn_ip_type)(
+ const char* apn,
+ ApnIpType apnIpType);
+} AGpsInterface;
+
+/** Error codes associated with certificate operations */
+#define AGPS_CERTIFICATE_OPERATION_SUCCESS 0
+#define AGPS_CERTIFICATE_ERROR_GENERIC -100
+#define AGPS_CERTIFICATE_ERROR_TOO_MANY_CERTIFICATES -101
+
+/** A data structure that represents an X.509 certificate using DER encoding */
+typedef struct {
+ size_t length;
+ u_char* data;
+} DerEncodedCertificate;
+
+/**
+ * A type definition for SHA1 Fingerprints used to identify X.509 Certificates
+ * The Fingerprint is a digest of the DER Certificate that uniquely identifies it.
+ */
+typedef struct {
+ u_char data[20];
+} Sha1CertificateFingerprint;
+
+/** AGPS Interface to handle SUPL certificate operations */
+typedef struct {
+ /** set to sizeof(SuplCertificateInterface) */
+ size_t size;
+
+ /**
+ * Installs a set of Certificates used for SUPL connections to the AGPS server.
+ * If needed the HAL should find out internally any certificates that need to be removed to
+ * accommodate the certificates to install.
+ * The certificates installed represent a full set of valid certificates needed to connect to
+ * AGPS SUPL servers.
+ * The list of certificates is required, and all must be available at the same time, when trying
+ * to establish a connection with the AGPS Server.
+ *
+ * Parameters:
+ * certificates - A pointer to an array of DER encoded certificates that are need to be
+ * installed in the HAL.
+ * length - The number of certificates to install.
+ * Returns:
+ * AGPS_CERTIFICATE_OPERATION_SUCCESS if the operation is completed successfully
+ * AGPS_CERTIFICATE_ERROR_TOO_MANY_CERTIFICATES if the HAL cannot store the number of
+ * certificates attempted to be installed, the state of the certificates stored should
+ * remain the same as before on this error case.
+ *
+ * IMPORTANT:
+ * If needed the HAL should find out internally the set of certificates that need to be
+ * removed to accommodate the certificates to install.
+ */
+ int (*install_certificates) ( const DerEncodedCertificate* certificates, size_t length );
+
+ /**
+ * Notifies the HAL that a list of certificates used for SUPL connections are revoked. It is
+ * expected that the given set of certificates is removed from the internal store of the HAL.
+ *
+ * Parameters:
+ * fingerprints - A pointer to an array of SHA1 Fingerprints to identify the set of
+ * certificates to revoke.
+ * length - The number of fingerprints provided.
+ * Returns:
+ * AGPS_CERTIFICATE_OPERATION_SUCCESS if the operation is completed successfully.
+ *
+ * IMPORTANT:
+ * If any of the certificates provided (through its fingerprint) is not known by the HAL,
+ * it should be ignored and continue revoking/deleting the rest of them.
+ */
+ int (*revoke_certificates) ( const Sha1CertificateFingerprint* fingerprints, size_t length );
+} SuplCertificateInterface;
+
+/** Represents an NI request */
+typedef struct {
+ /** set to sizeof(GpsNiNotification) */
+ size_t size;
+
+ /**
+ * An ID generated by HAL to associate NI notifications and UI
+ * responses
+ */
+ int notification_id;
+
+ /**
+ * An NI type used to distinguish different categories of NI
+ * events, such as GPS_NI_TYPE_VOICE, GPS_NI_TYPE_UMTS_SUPL, ...
+ */
+ GpsNiType ni_type;
+
+ /**
+ * Notification/verification options, combinations of GpsNiNotifyFlags constants
+ */
+ GpsNiNotifyFlags notify_flags;
+
+ /**
+ * Timeout period to wait for user response.
+ * Set to 0 for no time out limit.
+ */
+ int timeout;
+
+ /**
+ * Default response when time out.
+ */
+ GpsUserResponseType default_response;
+
+ /**
+ * Requestor ID
+ */
+ char requestor_id[GPS_NI_SHORT_STRING_MAXLEN];
+
+ /**
+ * Notification message. It can also be used to store client_id in some cases
+ */
+ char text[GPS_NI_LONG_STRING_MAXLEN];
+
+ /**
+ * Client name decoding scheme
+ */
+ GpsNiEncodingType requestor_id_encoding;
+
+ /**
+ * Client name decoding scheme
+ */
+ GpsNiEncodingType text_encoding;
+
+ /**
+ * A pointer to extra data. Format:
+ * key_1 = value_1
+ * key_2 = value_2
+ */
+ char extras[GPS_NI_LONG_STRING_MAXLEN];
+
+} GpsNiNotification;
+
+/**
+ * Callback with NI notification. Can only be called from a thread created by
+ * create_thread_cb.
+ */
+typedef void (*gps_ni_notify_callback)(GpsNiNotification *notification);
+
+/** GPS NI callback structure. */
+typedef struct
+{
+ /**
+ * Sends the notification request from HAL to GPSLocationProvider.
+ */
+ gps_ni_notify_callback notify_cb;
+ gps_create_thread create_thread_cb;
+} GpsNiCallbacks;
+
+/**
+ * Extended interface for Network-initiated (NI) support.
+ */
+typedef struct
+{
+ /** set to sizeof(GpsNiInterface) */
+ size_t size;
+
+ /** Registers the callbacks for HAL to use. */
+ void (*init) (GpsNiCallbacks *callbacks);
+
+ /** Sends a response to HAL. */
+ void (*respond) (int notif_id, GpsUserResponseType user_response);
+} GpsNiInterface;
+
+#if defined(__ANDROID_OS__)
+struct gps_device_t {
+ struct hw_device_t common;
+
+ /**
+ * Set the provided lights to the provided values.
+ *
+ * Returns: 0 on succes, error code on failure.
+ */
+ const GpsInterface* (*get_gps_interface)(struct gps_device_t* dev);
+};
+#elif defined(__LINUX_OS__)
+struct gps_device_t {
+ const GpsInterface* (*get_gps_interface)(struct gps_device_t* dev);
+};
+#endif
+
+#define AGPS_RIL_REQUEST_REFLOC_CELLID (1<<0L)
+#define AGPS_RIL_REQUEST_REFLOC_MAC (1<<1L)
+
+typedef void (*agps_ril_request_set_id)(uint32_t flags);
+typedef void (*agps_ril_request_ref_loc)(uint32_t flags);
+
+typedef struct {
+ agps_ril_request_set_id request_setid;
+ agps_ril_request_ref_loc request_refloc;
+ gps_create_thread create_thread_cb;
+} AGpsRilCallbacks;
+
+/** Extended interface for AGPS_RIL support. */
+typedef struct {
+ /** set to sizeof(AGpsRilInterface) */
+ size_t size;
+ /**
+ * Opens the AGPS interface and provides the callback routines
+ * to the implementation of this interface.
+ */
+ void (*init)( AGpsRilCallbacks* callbacks );
+
+ /**
+ * Sets the reference location.
+ */
+ void (*set_ref_location) (const AGpsRefLocation *agps_reflocation, size_t sz_struct);
+ /**
+ * Sets the set ID.
+ */
+ void (*set_set_id) (AGpsSetIDType type, const char* setid);
+
+ /**
+ * Send network initiated message.
+ */
+ void (*ni_message) (uint8_t *msg, size_t len);
+
+ /**
+ * Notify GPS of network status changes.
+ * These parameters match values in the android.net.NetworkInfo class.
+ */
+ void (*update_network_state) (int connected, int type, int roaming, const char* extra_info);
+
+ /**
+ * Notify GPS of network status changes.
+ * These parameters match values in the android.net.NetworkInfo class.
+ */
+ void (*update_network_availability) (int avaiable, const char* apn);
+} AGpsRilInterface;
+
+/**
+ * GPS Geofence.
+ * There are 3 states associated with a Geofence: Inside, Outside, Unknown.
+ * There are 3 transitions: ENTERED, EXITED, UNCERTAIN.
+ *
+ * An example state diagram with confidence level: 95% and Unknown time limit
+ * set as 30 secs is shown below. (confidence level and Unknown time limit are
+ * explained latter)
+ * ____________________________
+ * | Unknown (30 secs) |
+ * """"""""""""""""""""""""""""
+ * ^ | | ^
+ * UNCERTAIN| |ENTERED EXITED| |UNCERTAIN
+ * | v v |
+ * ________ EXITED _________
+ * | Inside | -----------> | Outside |
+ * | | <----------- | |
+ * """""""" ENTERED """""""""
+ *
+ * Inside state: We are 95% confident that the user is inside the geofence.
+ * Outside state: We are 95% confident that the user is outside the geofence
+ * Unknown state: Rest of the time.
+ *
+ * The Unknown state is better explained with an example:
+ *
+ * __________
+ * | c|
+ * | ___ | _______
+ * | |a| | | b |
+ * | """ | """""""
+ * | |
+ * """"""""""
+ * In the diagram above, "a" and "b" are 2 geofences and "c" is the accuracy
+ * circle reported by the GPS subsystem. Now with regard to "b", the system is
+ * confident that the user is outside. But with regard to "a" is not confident
+ * whether it is inside or outside the geofence. If the accuracy remains the
+ * same for a sufficient period of time, the UNCERTAIN transition would be
+ * triggered with the state set to Unknown. If the accuracy improves later, an
+ * appropriate transition should be triggered. This "sufficient period of time"
+ * is defined by the parameter in the add_geofence_area API.
+ * In other words, Unknown state can be interpreted as a state in which the
+ * GPS subsystem isn't confident enough that the user is either inside or
+ * outside the Geofence. It moves to Unknown state only after the expiry of the
+ * timeout.
+ *
+ * The geofence callback needs to be triggered for the ENTERED and EXITED
+ * transitions, when the GPS system is confident that the user has entered
+ * (Inside state) or exited (Outside state) the Geofence. An implementation
+ * which uses a value of 95% as the confidence is recommended. The callback
+ * should be triggered only for the transitions requested by the
+ * add_geofence_area call.
+ *
+ * Even though the diagram and explanation talks about states and transitions,
+ * the callee is only interested in the transistions. The states are mentioned
+ * here for illustrative purposes.
+ *
+ * Startup Scenario: When the device boots up, if an application adds geofences,
+ * and then we get an accurate GPS location fix, it needs to trigger the
+ * appropriate (ENTERED or EXITED) transition for every Geofence it knows about.
+ * By default, all the Geofences will be in the Unknown state.
+ *
+ * When the GPS system is unavailable, gps_geofence_status_callback should be
+ * called to inform the upper layers of the same. Similarly, when it becomes
+ * available the callback should be called. This is a global state while the
+ * UNKNOWN transition described above is per geofence.
+ *
+ * An important aspect to note is that users of this API (framework), will use
+ * other subsystems like wifi, sensors, cell to handle Unknown case and
+ * hopefully provide a definitive state transition to the third party
+ * application. GPS Geofence will just be a signal indicating what the GPS
+ * subsystem knows about the Geofence.
+ *
+ */
+#define GPS_GEOFENCE_ENTERED (1<<0L)
+#define GPS_GEOFENCE_EXITED (1<<1L)
+#define GPS_GEOFENCE_UNCERTAIN (1<<2L)
+
+#define GPS_GEOFENCE_UNAVAILABLE (1<<0L)
+#define GPS_GEOFENCE_AVAILABLE (1<<1L)
+
+#define GPS_GEOFENCE_OPERATION_SUCCESS 0
+#define GPS_GEOFENCE_ERROR_TOO_MANY_GEOFENCES -100
+#define GPS_GEOFENCE_ERROR_ID_EXISTS -101
+#define GPS_GEOFENCE_ERROR_ID_UNKNOWN -102
+#define GPS_GEOFENCE_ERROR_INVALID_TRANSITION -103
+#define GPS_GEOFENCE_ERROR_GENERIC -149
+
+/**
+ * The callback associated with the geofence.
+ * Parameters:
+ * geofence_id - The id associated with the add_geofence_area.
+ * location - The current GPS location.
+ * transition - Can be one of GPS_GEOFENCE_ENTERED, GPS_GEOFENCE_EXITED,
+ * GPS_GEOFENCE_UNCERTAIN.
+ * timestamp - Timestamp when the transition was detected.
+ *
+ * The callback should only be called when the caller is interested in that
+ * particular transition. For instance, if the caller is interested only in
+ * ENTERED transition, then the callback should NOT be called with the EXITED
+ * transition.
+ *
+ * IMPORTANT: If a transition is triggered resulting in this callback, the GPS
+ * subsystem will wake up the application processor, if its in suspend state.
+ */
+typedef void (*gps_geofence_transition_callback) (int32_t geofence_id, GpsLocation* location,
+ int32_t transition, GpsUtcTime timestamp);
+
+/**
+ * The callback associated with the availability of the GPS system for geofencing
+ * monitoring. If the GPS system determines that it cannot monitor geofences
+ * because of lack of reliability or unavailability of the GPS signals, it will
+ * call this callback with GPS_GEOFENCE_UNAVAILABLE parameter.
+ *
+ * Parameters:
+ * status - GPS_GEOFENCE_UNAVAILABLE or GPS_GEOFENCE_AVAILABLE.
+ * last_location - Last known location.
+ */
+typedef void (*gps_geofence_status_callback) (int32_t status, GpsLocation* last_location);
+
+/**
+ * The callback associated with the add_geofence call.
+ *
+ * Parameter:
+ * geofence_id - Id of the geofence.
+ * status - GPS_GEOFENCE_OPERATION_SUCCESS
+ * GPS_GEOFENCE_ERROR_TOO_MANY_GEOFENCES - geofence limit has been reached.
+ * GPS_GEOFENCE_ERROR_ID_EXISTS - geofence with id already exists
+ * GPS_GEOFENCE_ERROR_INVALID_TRANSITION - the monitorTransition contains an
+ * invalid transition
+ * GPS_GEOFENCE_ERROR_GENERIC - for other errors.
+ */
+typedef void (*gps_geofence_add_callback) (int32_t geofence_id, int32_t status);
+
+/**
+ * The callback associated with the remove_geofence call.
+ *
+ * Parameter:
+ * geofence_id - Id of the geofence.
+ * status - GPS_GEOFENCE_OPERATION_SUCCESS
+ * GPS_GEOFENCE_ERROR_ID_UNKNOWN - for invalid id
+ * GPS_GEOFENCE_ERROR_GENERIC for others.
+ */
+typedef void (*gps_geofence_remove_callback) (int32_t geofence_id, int32_t status);
+
+
+/**
+ * The callback associated with the pause_geofence call.
+ *
+ * Parameter:
+ * geofence_id - Id of the geofence.
+ * status - GPS_GEOFENCE_OPERATION_SUCCESS
+ * GPS_GEOFENCE_ERROR_ID_UNKNOWN - for invalid id
+ * GPS_GEOFENCE_ERROR_INVALID_TRANSITION -
+ * when monitor_transitions is invalid
+ * GPS_GEOFENCE_ERROR_GENERIC for others.
+ */
+typedef void (*gps_geofence_pause_callback) (int32_t geofence_id, int32_t status);
+
+/**
+ * The callback associated with the resume_geofence call.
+ *
+ * Parameter:
+ * geofence_id - Id of the geofence.
+ * status - GPS_GEOFENCE_OPERATION_SUCCESS
+ * GPS_GEOFENCE_ERROR_ID_UNKNOWN - for invalid id
+ * GPS_GEOFENCE_ERROR_GENERIC for others.
+ */
+typedef void (*gps_geofence_resume_callback) (int32_t geofence_id, int32_t status);
+
+typedef struct {
+ gps_geofence_transition_callback geofence_transition_callback;
+ gps_geofence_status_callback geofence_status_callback;
+ gps_geofence_add_callback geofence_add_callback;
+ gps_geofence_remove_callback geofence_remove_callback;
+ gps_geofence_pause_callback geofence_pause_callback;
+ gps_geofence_resume_callback geofence_resume_callback;
+ gps_create_thread create_thread_cb;
+} GpsGeofenceCallbacks;
+
+/** Extended interface for GPS_Geofencing support */
+typedef struct {
+ /** set to sizeof(GpsGeofencingInterface) */
+ size_t size;
+
+ /**
+ * Opens the geofence interface and provides the callback routines
+ * to the implementation of this interface.
+ */
+ void (*init)( GpsGeofenceCallbacks* callbacks );
+
+ /**
+ * Add a geofence area. This api currently supports circular geofences.
+ * Parameters:
+ * geofence_id - The id for the geofence. If a geofence with this id
+ * already exists, an error value (GPS_GEOFENCE_ERROR_ID_EXISTS)
+ * should be returned.
+ * latitude, longtitude, radius_meters - The lat, long and radius
+ * (in meters) for the geofence
+ * last_transition - The current state of the geofence. For example, if
+ * the system already knows that the user is inside the geofence,
+ * this will be set to GPS_GEOFENCE_ENTERED. In most cases, it
+ * will be GPS_GEOFENCE_UNCERTAIN.
+ * monitor_transition - Which transitions to monitor. Bitwise OR of
+ * GPS_GEOFENCE_ENTERED, GPS_GEOFENCE_EXITED and
+ * GPS_GEOFENCE_UNCERTAIN.
+ * notification_responsiveness_ms - Defines the best-effort description
+ * of how soon should the callback be called when the transition
+ * associated with the Geofence is triggered. For instance, if set
+ * to 1000 millseconds with GPS_GEOFENCE_ENTERED, the callback
+ * should be called 1000 milliseconds within entering the geofence.
+ * This parameter is defined in milliseconds.
+ * NOTE: This is not to be confused with the rate that the GPS is
+ * polled at. It is acceptable to dynamically vary the rate of
+ * sampling the GPS for power-saving reasons; thus the rate of
+ * sampling may be faster or slower than this.
+ * unknown_timer_ms - The time limit after which the UNCERTAIN transition
+ * should be triggered. This parameter is defined in milliseconds.
+ * See above for a detailed explanation.
+ */
+ void (*add_geofence_area) (int32_t geofence_id, double latitude, double longitude,
+ double radius_meters, int last_transition, int monitor_transitions,
+ int notification_responsiveness_ms, int unknown_timer_ms);
+
+ /**
+ * Pause monitoring a particular geofence.
+ * Parameters:
+ * geofence_id - The id for the geofence.
+ */
+ void (*pause_geofence) (int32_t geofence_id);
+
+ /**
+ * Resume monitoring a particular geofence.
+ * Parameters:
+ * geofence_id - The id for the geofence.
+ * monitor_transitions - Which transitions to monitor. Bitwise OR of
+ * GPS_GEOFENCE_ENTERED, GPS_GEOFENCE_EXITED and
+ * GPS_GEOFENCE_UNCERTAIN.
+ * This supersedes the value associated provided in the
+ * add_geofence_area call.
+ */
+ void (*resume_geofence) (int32_t geofence_id, int monitor_transitions);
+
+ /**
+ * Remove a geofence area. After the function returns, no notifications
+ * should be sent.
+ * Parameter:
+ * geofence_id - The id for the geofence.
+ */
+ void (*remove_geofence_area) (int32_t geofence_id);
+} GpsGeofencingInterface;
+
+/**
+ * Legacy struct to represent an estimate of the GPS clock time.
+ * Deprecated, to be removed in the next Android release.
+ * Use GnssClock instead.
+ */
+typedef struct {
+ /** set to sizeof(GpsClock) */
+ size_t size;
+ GpsClockFlags flags;
+ int16_t leap_second;
+ GpsClockType type;
+ int64_t time_ns;
+ double time_uncertainty_ns;
+ int64_t full_bias_ns;
+ double bias_ns;
+ double bias_uncertainty_ns;
+ double drift_nsps;
+ double drift_uncertainty_nsps;
+} GpsClock;
+
+/**
+ * Represents an estimate of the GPS clock time.
+ */
+typedef struct {
+ /** set to sizeof(GnssClock) */
+ size_t size;
+
+ /**
+ * A set of flags indicating the validity of the fields in this data
+ * structure.
+ */
+ GnssClockFlags flags;
+
+ /**
+ * Leap second data.
+ * The sign of the value is defined by the following equation:
+ * utc_time_ns = time_ns - (full_bias_ns + bias_ns) - leap_second *
+ * 1,000,000,000
+ *
+ * If the data is available 'flags' must contain GNSS_CLOCK_HAS_LEAP_SECOND.
+ */
+ int16_t leap_second;
+
+ /**
+ * The GNSS receiver internal clock value. This is the local hardware clock
+ * value.
+ *
+ * For local hardware clock, this value is expected to be monotonically
+ * increasing while the hardware clock remains power on. (For the case of a
+ * HW clock that is not continuously on, see the
+ * hw_clock_discontinuity_count field). The receiver's estimate of GPS time
+ * can be derived by substracting the sum of full_bias_ns and bias_ns (when
+ * available) from this value.
+ *
+ * This GPS time is expected to be the best estimate of current GPS time
+ * that GNSS receiver can achieve.
+ *
+ * Sub-nanosecond accuracy can be provided by means of the 'bias_ns' field.
+ * The value contains the 'time uncertainty' in it.
+ *
+ * This field is mandatory.
+ */
+ int64_t time_ns;
+
+ /**
+ * 1-Sigma uncertainty associated with the clock's time in nanoseconds.
+ * The uncertainty is represented as an absolute (single sided) value.
+ *
+ * If the data is available, 'flags' must contain
+ * GNSS_CLOCK_HAS_TIME_UNCERTAINTY. This value is effectively zero (it is
+ * the reference local clock, by which all other times and time
+ * uncertainties are measured.) (And thus this field can be not provided,
+ * per GNSS_CLOCK_HAS_TIME_UNCERTAINTY flag, or provided & set to 0.)
+ */
+ double time_uncertainty_ns;
+
+ /**
+ * The difference between hardware clock ('time' field) inside GPS receiver
+ * and the true GPS time since 0000Z, January 6, 1980, in nanoseconds.
+ *
+ * The sign of the value is defined by the following equation:
+ * local estimate of GPS time = time_ns - (full_bias_ns + bias_ns)
+ *
+ * This value is mandatory if the receiver has estimated GPS time. If the
+ * computed time is for a non-GPS constellation, the time offset of that
+ * constellation to GPS has to be applied to fill this value. The error
+ * estimate for the sum of this and the bias_ns is the bias_uncertainty_ns,
+ * and the caller is responsible for using this uncertainty (it can be very
+ * large before the GPS time has been solved for.) If the data is available
+ * 'flags' must contain GNSS_CLOCK_HAS_FULL_BIAS.
+ */
+ int64_t full_bias_ns;
+
+ /**
+ * Sub-nanosecond bias.
+ * The error estimate for the sum of this and the full_bias_ns is the
+ * bias_uncertainty_ns
+ *
+ * If the data is available 'flags' must contain GNSS_CLOCK_HAS_BIAS. If GPS
+ * has computed a position fix. This value is mandatory if the receiver has
+ * estimated GPS time.
+ */
+ double bias_ns;
+
+ /**
+ * 1-Sigma uncertainty associated with the local estimate of GPS time (clock
+ * bias) in nanoseconds. The uncertainty is represented as an absolute
+ * (single sided) value.
+ *
+ * If the data is available 'flags' must contain
+ * GNSS_CLOCK_HAS_BIAS_UNCERTAINTY. This value is mandatory if the receiver
+ * has estimated GPS time.
+ */
+ double bias_uncertainty_ns;
+
+ /**
+ * The clock's drift in nanoseconds (per second).
+ *
+ * A positive value means that the frequency is higher than the nominal
+ * frequency, and that the (full_bias_ns + bias_ns) is growing more positive
+ * over time.
+ *
+ * The value contains the 'drift uncertainty' in it.
+ * If the data is available 'flags' must contain GNSS_CLOCK_HAS_DRIFT.
+ *
+ * This value is mandatory if the receiver has estimated GNSS time
+ */
+ double drift_nsps;
+
+ /**
+ * 1-Sigma uncertainty associated with the clock's drift in nanoseconds (per second).
+ * The uncertainty is represented as an absolute (single sided) value.
+ *
+ * If the data is available 'flags' must contain
+ * GNSS_CLOCK_HAS_DRIFT_UNCERTAINTY. If GPS has computed a position fix this
+ * field is mandatory and must be populated.
+ */
+ double drift_uncertainty_nsps;
+
+ /**
+ * When there are any discontinuities in the HW clock, this field is
+ * mandatory.
+ *
+ * A "discontinuity" is meant to cover the case of a switch from one source
+ * of clock to another. A single free-running crystal oscillator (XO)
+ * should generally not have any discontinuities, and this can be set and
+ * left at 0.
+ *
+ * If, however, the time_ns value (HW clock) is derived from a composite of
+ * sources, that is not as smooth as a typical XO, or is otherwise stopped &
+ * restarted, then this value shall be incremented each time a discontinuity
+ * occurs. (E.g. this value may start at zero at device boot-up and
+ * increment each time there is a change in clock continuity. In the
+ * unlikely event that this value reaches full scale, rollover (not
+ * clamping) is required, such that this value continues to change, during
+ * subsequent discontinuity events.)
+ *
+ * While this number stays the same, between GnssClock reports, it can be
+ * safely assumed that the time_ns value has been running continuously, e.g.
+ * derived from a single, high quality clock (XO like, or better, that's
+ * typically used during continuous GNSS signal sampling.)
+ *
+ * It is expected, esp. during periods where there are few GNSS signals
+ * available, that the HW clock be discontinuity-free as long as possible,
+ * as this avoids the need to use (waste) a GNSS measurement to fully
+ * re-solve for the GPS clock bias and drift, when using the accompanying
+ * measurements, from consecutive GnssData reports.
+ */
+ uint32_t hw_clock_discontinuity_count;
+
+} GnssClock;
+
+/**
+ * Legacy struct to represent a GPS Measurement, it contains raw and computed
+ * information.
+ * Deprecated, to be removed in the next Android release.
+ * Use GnssMeasurement instead.
+ */
+typedef struct {
+ /** set to sizeof(GpsMeasurement) */
+ size_t size;
+ GpsMeasurementFlags flags;
+ int8_t prn;
+ double time_offset_ns;
+ GpsMeasurementState state;
+ int64_t received_gps_tow_ns;
+ int64_t received_gps_tow_uncertainty_ns;
+ double c_n0_dbhz;
+ double pseudorange_rate_mps;
+ double pseudorange_rate_uncertainty_mps;
+ GpsAccumulatedDeltaRangeState accumulated_delta_range_state;
+ double accumulated_delta_range_m;
+ double accumulated_delta_range_uncertainty_m;
+ double pseudorange_m;
+ double pseudorange_uncertainty_m;
+ double code_phase_chips;
+ double code_phase_uncertainty_chips;
+ float carrier_frequency_hz;
+ int64_t carrier_cycles;
+ double carrier_phase;
+ double carrier_phase_uncertainty;
+ GpsLossOfLock loss_of_lock;
+ int32_t bit_number;
+ int16_t time_from_last_bit_ms;
+ double doppler_shift_hz;
+ double doppler_shift_uncertainty_hz;
+ GpsMultipathIndicator multipath_indicator;
+ double snr_db;
+ double elevation_deg;
+ double elevation_uncertainty_deg;
+ double azimuth_deg;
+ double azimuth_uncertainty_deg;
+ bool used_in_fix;
+} GpsMeasurement;
+
+/**
+ * Represents a GNSS Measurement, it contains raw and computed information.
+ *
+ * Independence - All signal measurement information (e.g. sv_time,
+ * pseudorange_rate, multipath_indicator) reported in this struct should be
+ * based on GNSS signal measurements only. You may not synthesize measurements
+ * by calculating or reporting expected measurements based on known or estimated
+ * position, velocity, or time.
+ */
+typedef struct {
+ /** set to sizeof(GpsMeasurement) */
+ size_t size;
+
+ /** A set of flags indicating the validity of the fields in this data structure. */
+ GnssMeasurementFlags flags;
+
+ /**
+ * Satellite vehicle ID number, as defined in GnssSvInfo::svid
+ * This is a mandatory value.
+ */
+ int16_t svid;
+
+ /**
+ * Defines the constellation of the given SV. Value should be one of those
+ * GNSS_CONSTELLATION_* constants
+ */
+ GnssConstellationType constellation;
+
+ /**
+ * Time offset at which the measurement was taken in nanoseconds.
+ * The reference receiver's time is specified by GpsData::clock::time_ns and should be
+ * interpreted in the same way as indicated by GpsClock::type.
+ *
+ * The sign of time_offset_ns is given by the following equation:
+ * measurement time = GpsClock::time_ns + time_offset_ns
+ *
+ * It provides an individual time-stamp for the measurement, and allows sub-nanosecond accuracy.
+ * This is a mandatory value.
+ */
+ double time_offset_ns;
+
+ /**
+ * Per satellite sync state. It represents the current sync state for the associated satellite.
+ * Based on the sync state, the 'received GPS tow' field should be interpreted accordingly.
+ *
+ * This is a mandatory value.
+ */
+ GnssMeasurementState state;
+
+ /**
+ * The received GNSS Time-of-Week at the measurement time, in nanoseconds.
+ * Ensure that this field is independent (see comment at top of
+ * GnssMeasurement struct.)
+ *
+ * For GPS & QZSS, this is:
+ * Received GPS Time-of-Week at the measurement time, in nanoseconds.
+ * The value is relative to the beginning of the current GPS week.
+ *
+ * Given the highest sync state that can be achieved, per each satellite, valid range
+ * for this field can be:
+ * Searching : [ 0 ] : GNSS_MEASUREMENT_STATE_UNKNOWN
+ * C/A code lock : [ 0 1ms ] : GNSS_MEASUREMENT_STATE_CODE_LOCK is set
+ * Bit sync : [ 0 20ms ] : GNSS_MEASUREMENT_STATE_BIT_SYNC is set
+ * Subframe sync : [ 0 6s ] : GNSS_MEASUREMENT_STATE_SUBFRAME_SYNC is set
+ * TOW decoded : [ 0 1week ] : GNSS_MEASUREMENT_STATE_TOW_DECODED is set
+ *
+ * Note well: if there is any ambiguity in integer millisecond,
+ * GNSS_MEASUREMENT_STATE_MSEC_AMBIGUOUS should be set accordingly, in the 'state' field.
+ *
+ * This value must be populated if 'state' != GNSS_MEASUREMENT_STATE_UNKNOWN.
+ *
+ * For Glonass, this is:
+ * Received Glonass time of day, at the measurement time in nanoseconds.
+ *
+ * Given the highest sync state that can be achieved, per each satellite, valid range for
+ * this field can be:
+ * Searching : [ 0 ] : GNSS_MEASUREMENT_STATE_UNKNOWN
+ * C/A code lock : [ 0 1ms ] : GNSS_MEASUREMENT_STATE_CODE_LOCK is set
+ * Symbol sync : [ 0 10ms ] : GNSS_MEASUREMENT_STATE_SYMBOL_SYNC is set
+ * Bit sync : [ 0 20ms ] : GNSS_MEASUREMENT_STATE_BIT_SYNC is set
+ * String sync : [ 0 2s ] : GNSS_MEASUREMENT_STATE_GLO_STRING_SYNC is set
+ * Time of day : [ 0 1day ] : GNSS_MEASUREMENT_STATE_GLO_TOD_DECODED is set
+ *
+ * For Beidou, this is:
+ * Received Beidou time of week, at the measurement time in nanoseconds.
+ *
+ * Given the highest sync state that can be achieved, per each satellite, valid range for
+ * this field can be:
+ * Searching : [ 0 ] : GNSS_MEASUREMENT_STATE_UNKNOWN
+ * C/A code lock: [ 0 1ms ] : GNSS_MEASUREMENT_STATE_CODE_LOCK is set
+ * Bit sync (D2): [ 0 2ms ] : GNSS_MEASUREMENT_STATE_BDS_D2_BIT_SYNC is set
+ * Bit sync (D1): [ 0 20ms ] : GNSS_MEASUREMENT_STATE_BIT_SYNC is set
+ * Subframe (D2): [ 0 0.6s ] : GNSS_MEASUREMENT_STATE_BDS_D2_SUBFRAME_SYNC is set
+ * Subframe (D1): [ 0 6s ] : GNSS_MEASUREMENT_STATE_SUBFRAME_SYNC is set
+ * Time of week : [ 0 1week ] : GNSS_MEASUREMENT_STATE_TOW_DECODED is set
+ *
+ * For Galileo, this is:
+ * Received Galileo time of week, at the measurement time in nanoseconds.
+ *
+ * E1BC code lock : [ 0 4ms ] : GNSS_MEASUREMENT_STATE_GAL_E1BC_CODE_LOCK is set
+ * E1C 2nd code lock: [ 0 100ms ] :
+ * GNSS_MEASUREMENT_STATE_GAL_E1C_2ND_CODE_LOCK is set
+ *
+ * E1B page : [ 0 2s ] : GNSS_MEASUREMENT_STATE_GAL_E1B_PAGE_SYNC is set
+ * Time of week: [ 0 1week ] : GNSS_MEASUREMENT_STATE_TOW_DECODED is set
+ *
+ * For SBAS, this is:
+ * Received SBAS time, at the measurement time in nanoseconds.
+ *
+ * Given the highest sync state that can be achieved, per each satellite,
+ * valid range for this field can be:
+ * Searching : [ 0 ] : GNSS_MEASUREMENT_STATE_UNKNOWN
+ * C/A code lock: [ 0 1ms ] : GNSS_MEASUREMENT_STATE_CODE_LOCK is set
+ * Symbol sync : [ 0 2ms ] : GNSS_MEASUREMENT_STATE_SYMBOL_SYNC is set
+ * Message : [ 0 1s ] : GNSS_MEASUREMENT_STATE_SBAS_SYNC is set
+ */
+ int64_t received_sv_time_in_ns;
+
+ /**
+ * 1-Sigma uncertainty of the Received GPS Time-of-Week in nanoseconds.
+ *
+ * This value must be populated if 'state' != GPS_MEASUREMENT_STATE_UNKNOWN.
+ */
+ int64_t received_sv_time_uncertainty_in_ns;
+
+ /**
+ * Carrier-to-noise density in dB-Hz, typically in the range [0, 63].
+ * It contains the measured C/N0 value for the signal at the antenna port.
+ *
+ * This is a mandatory value.
+ */
+ double c_n0_dbhz;
+
+ /**
+ * Pseudorange rate at the timestamp in m/s. The correction of a given
+ * Pseudorange Rate value includes corrections for receiver and satellite
+ * clock frequency errors. Ensure that this field is independent (see
+ * comment at top of GnssMeasurement struct.)
+ *
+ * It is mandatory to provide the 'uncorrected' 'pseudorange rate', and provide GpsClock's
+ * 'drift' field as well (When providing the uncorrected pseudorange rate, do not apply the
+ * corrections described above.)
+ *
+ * The value includes the 'pseudorange rate uncertainty' in it.
+ * A positive 'uncorrected' value indicates that the SV is moving away from the receiver.
+ *
+ * The sign of the 'uncorrected' 'pseudorange rate' and its relation to the sign of 'doppler
+ * shift' is given by the equation:
+ * pseudorange rate = -k * doppler shift (where k is a constant)
+ *
+ * This should be the most accurate pseudorange rate available, based on
+ * fresh signal measurements from this channel.
+ *
+ * It is mandatory that this value be provided at typical carrier phase PRR
+ * quality (few cm/sec per second of uncertainty, or better) - when signals
+ * are sufficiently strong & stable, e.g. signals from a GPS simulator at >=
+ * 35 dB-Hz.
+ */
+ double pseudorange_rate_mps;
+
+ /**
+ * 1-Sigma uncertainty of the pseudorange_rate_mps.
+ * The uncertainty is represented as an absolute (single sided) value.
+ *
+ * This is a mandatory value.
+ */
+ double pseudorange_rate_uncertainty_mps;
+
+ /**
+ * Accumulated delta range's state. It indicates whether ADR is reset or there is a cycle slip
+ * (indicating loss of lock).
+ *
+ * This is a mandatory value.
+ */
+ GnssAccumulatedDeltaRangeState accumulated_delta_range_state;
+
+ /**
+ * Accumulated delta range since the last channel reset in meters.
+ * A positive value indicates that the SV is moving away from the receiver.
+ *
+ * The sign of the 'accumulated delta range' and its relation to the sign of 'carrier phase'
+ * is given by the equation:
+ * accumulated delta range = -k * carrier phase (where k is a constant)
+ *
+ * This value must be populated if 'accumulated delta range state' != GPS_ADR_STATE_UNKNOWN.
+ * However, it is expected that the data is only accurate when:
+ * 'accumulated delta range state' == GPS_ADR_STATE_VALID.
+ */
+ double accumulated_delta_range_m;
+
+ /**
+ * 1-Sigma uncertainty of the accumulated delta range in meters.
+ * This value must be populated if 'accumulated delta range state' != GPS_ADR_STATE_UNKNOWN.
+ */
+ double accumulated_delta_range_uncertainty_m;
+
+ /**
+ * Carrier frequency at which codes and messages are modulated, it can be L1 or L2.
+ * If the field is not set, the carrier frequency is assumed to be L1.
+ *
+ * If the data is available, 'flags' must contain
+ * GNSS_MEASUREMENT_HAS_CARRIER_FREQUENCY.
+ */
+ float carrier_frequency_hz;
+
+ /**
+ * The number of full carrier cycles between the satellite and the receiver.
+ * The reference frequency is given by the field 'carrier_frequency_hz'.
+ * Indications of possible cycle slips and resets in the accumulation of
+ * this value can be inferred from the accumulated_delta_range_state flags.
+ *
+ * If the data is available, 'flags' must contain
+ * GNSS_MEASUREMENT_HAS_CARRIER_CYCLES.
+ */
+ int64_t carrier_cycles;
+
+ /**
+ * The RF phase detected by the receiver, in the range [0.0, 1.0].
+ * This is usually the fractional part of the complete carrier phase measurement.
+ *
+ * The reference frequency is given by the field 'carrier_frequency_hz'.
+ * The value contains the 'carrier-phase uncertainty' in it.
+ *
+ * If the data is available, 'flags' must contain
+ * GNSS_MEASUREMENT_HAS_CARRIER_PHASE.
+ */
+ double carrier_phase;
+
+ /**
+ * 1-Sigma uncertainty of the carrier-phase.
+ * If the data is available, 'flags' must contain
+ * GNSS_MEASUREMENT_HAS_CARRIER_PHASE_UNCERTAINTY.
+ */
+ double carrier_phase_uncertainty;
+
+ /**
+ * An enumeration that indicates the 'multipath' state of the event.
+ *
+ * The multipath Indicator is intended to report the presence of overlapping
+ * signals that manifest as distorted correlation peaks.
+ *
+ * - if there is a distorted correlation peak shape, report that multipath
+ * is GNSS_MULTIPATH_INDICATOR_PRESENT.
+ * - if there is not a distorted correlation peak shape, report
+ * GNSS_MULTIPATH_INDICATOR_NOT_PRESENT
+ * - if signals are too weak to discern this information, report
+ * GNSS_MULTIPATH_INDICATOR_UNKNOWN
+ *
+ * Example: when doing the standardized overlapping Multipath Performance
+ * test (3GPP TS 34.171) the Multipath indicator should report
+ * GNSS_MULTIPATH_INDICATOR_PRESENT for those signals that are tracked, and
+ * contain multipath, and GNSS_MULTIPATH_INDICATOR_NOT_PRESENT for those
+ * signals that are tracked and do not contain multipath.
+ */
+ GnssMultipathIndicator multipath_indicator;
+
+ /**
+ * Signal-to-noise ratio at correlator output in dB.
+ * If the data is available, 'flags' must contain GNSS_MEASUREMENT_HAS_SNR.
+ * This is the power ratio of the "correlation peak height above the
+ * observed noise floor" to "the noise RMS".
+ */
+ double snr_db;
+} GnssMeasurement;
+
+/**
+ * Legacy struct to represents a reading of GPS measurements.
+ * Deprecated, to be removed in the next Android release.
+ * Use GnssData instead.
+ */
+typedef struct {
+ /** set to sizeof(GpsData) */
+ size_t size;
+ size_t measurement_count;
+ GpsMeasurement measurements[GPS_MAX_MEASUREMENT];
+
+ /** The GPS clock time reading. */
+ GpsClock clock;
+} GpsData;
+
+/**
+ * Represents a reading of GNSS measurements. For devices where GnssSystemInfo's
+ * year_of_hw is set to 2016+, it is mandatory that these be provided, on
+ * request, when the GNSS receiver is searching/tracking signals.
+ *
+ * - Reporting of GPS constellation measurements is mandatory.
+ * - Reporting of all tracked constellations are encouraged.
+ */
+typedef struct {
+ /** set to sizeof(GnssData) */
+ size_t size;
+
+ /** Number of measurements. */
+ size_t measurement_count;
+
+ /** The array of measurements. */
+ GnssMeasurement measurements[GNSS_MAX_MEASUREMENT];
+
+ /** The GPS clock time reading. */
+ GnssClock clock;
+} GnssData;
+
+/**
+ * The legacy callback for to report measurements from the HAL.
+ *
+ * This callback is deprecated, and will be removed in the next release. Use
+ * gnss_measurement_callback() instead.
+ *
+ * Parameters:
+ * data - A data structure containing the measurements.
+ */
+typedef void (*gps_measurement_callback) (GpsData* data);
+
+/**
+ * The callback for to report measurements from the HAL.
+ *
+ * Parameters:
+ * data - A data structure containing the measurements.
+ */
+typedef void (*gnss_measurement_callback) (GnssData* data);
+
+typedef struct {
+ /** set to sizeof(GpsMeasurementCallbacks) */
+ size_t size;
+ gps_measurement_callback measurement_callback;
+ gnss_measurement_callback gnss_measurement_callback;
+} GpsMeasurementCallbacks;
+
+/**
+ * Extended interface for GPS Measurements support.
+ */
+typedef struct {
+ /** Set to sizeof(GpsMeasurementInterface) */
+ size_t size;
+
+ /**
+ * Initializes the interface and registers the callback routines with the HAL.
+ * After a successful call to 'init' the HAL must begin to provide updates at its own phase.
+ *
+ * Status:
+ * GPS_MEASUREMENT_OPERATION_SUCCESS
+ * GPS_MEASUREMENT_ERROR_ALREADY_INIT - if a callback has already been registered without a
+ * corresponding call to 'close'
+ * GPS_MEASUREMENT_ERROR_GENERIC - if any other error occurred, it is expected that the HAL
+ * will not generate any updates upon returning this error code.
+ */
+ int (*init) (GpsMeasurementCallbacks* callbacks);
+
+ /**
+ * Stops updates from the HAL, and unregisters the callback routines.
+ * After a call to stop, the previously registered callbacks must be considered invalid by the
+ * HAL.
+ * If stop is invoked without a previous 'init', this function should perform no work.
+ */
+ void (*close) ();
+
+} GpsMeasurementInterface;
+
+/**
+ * Legacy struct to represents a GPS navigation message (or a fragment of it).
+ * Deprecated, to be removed in the next Android release.
+ * Use GnssNavigationMessage instead.
+ */
+typedef struct {
+ /** set to sizeof(GpsNavigationMessage) */
+ size_t size;
+ int8_t prn;
+ GpsNavigationMessageType type;
+ NavigationMessageStatus status;
+ int16_t message_id;
+ int16_t submessage_id;
+ size_t data_length;
+ uint8_t* data;
+} GpsNavigationMessage;
+
+/** Represents a GPS navigation message (or a fragment of it). */
+typedef struct {
+ /** set to sizeof(GnssNavigationMessage) */
+ size_t size;
+
+ /**
+ * Satellite vehicle ID number, as defined in GnssSvInfo::svid
+ * This is a mandatory value.
+ */
+ int16_t svid;
+
+ /**
+ * The type of message contained in the structure.
+ * This is a mandatory value.
+ */
+ GnssNavigationMessageType type;
+
+ /**
+ * The status of the received navigation message.
+ * No need to send any navigation message that contains words with parity error and cannot be
+ * corrected.
+ */
+ NavigationMessageStatus status;
+
+ /**
+ * Message identifier. It provides an index so the complete Navigation
+ * Message can be assembled.
+ *
+ * - For GPS L1 C/A subframe 4 and 5, this value corresponds to the 'frame
+ * id' of the navigation message, in the range of 1-25 (Subframe 1, 2, 3
+ * does not contain a 'frame id' and this value can be set to -1.)
+ *
+ * - For Glonass L1 C/A, this refers to the frame ID, in the range of 1-5.
+ *
+ * - For BeiDou D1, this refers to the frame number in the range of 1-24
+ *
+ * - For Beidou D2, this refers to the frame number, in the range of 1-120
+ *
+ * - For Galileo F/NAV nominal frame structure, this refers to the subframe
+ * number, in the range of 1-12
+ *
+ * - For Galileo I/NAV nominal frame structure, this refers to the subframe
+ * number in the range of 1-24
+ */
+ int16_t message_id;
+
+ /**
+ * Sub-message identifier. If required by the message 'type', this value
+ * contains a sub-index within the current message (or frame) that is being
+ * transmitted.
+ *
+ * - For GPS L1 C/A, BeiDou D1 & BeiDou D2, the submessage id corresponds to
+ * the subframe number of the navigation message, in the range of 1-5.
+ *
+ * - For Glonass L1 C/A, this refers to the String number, in the range from
+ * 1-15
+ *
+ * - For Galileo F/NAV, this refers to the page type in the range 1-6
+ *
+ * - For Galileo I/NAV, this refers to the word type in the range 1-10+
+ */
+ int16_t submessage_id;
+
+ /**
+ * The length of the data (in bytes) contained in the current message.
+ * If this value is different from zero, 'data' must point to an array of the same size.
+ * e.g. for L1 C/A the size of the sub-frame will be 40 bytes (10 words, 30 bits/word).
+ *
+ * This is a mandatory value.
+ */
+ size_t data_length;
+
+ /**
+ * The data of the reported GPS message. The bytes (or words) specified
+ * using big endian format (MSB first).
+ *
+ * - For GPS L1 C/A, Beidou D1 & Beidou D2, each subframe contains 10 30-bit
+ * words. Each word (30 bits) should be fit into the last 30 bits in a
+ * 4-byte word (skip B31 and B32), with MSB first, for a total of 40
+ * bytes, covering a time period of 6, 6, and 0.6 seconds, respectively.
+ *
+ * - For Glonass L1 C/A, each string contains 85 data bits, including the
+ * checksum. These bits should be fit into 11 bytes, with MSB first (skip
+ * B86-B88), covering a time period of 2 seconds.
+ *
+ * - For Galileo F/NAV, each word consists of 238-bit (sync & tail symbols
+ * excluded). Each word should be fit into 30-bytes, with MSB first (skip
+ * B239, B240), covering a time period of 10 seconds.
+ *
+ * - For Galileo I/NAV, each page contains 2 page parts, even and odd, with
+ * a total of 2x114 = 228 bits, (sync & tail excluded) that should be fit
+ * into 29 bytes, with MSB first (skip B229-B232).
+ */
+ uint8_t* data;
+
+} GnssNavigationMessage;
+
+/**
+ * The legacy callback to report an available fragment of a GPS navigation
+ * messages from the HAL.
+ *
+ * This callback is deprecated, and will be removed in the next release. Use
+ * gnss_navigation_message_callback() instead.
+ *
+ * Parameters:
+ * message - The GPS navigation submessage/subframe representation.
+ */
+typedef void (*gps_navigation_message_callback) (GpsNavigationMessage* message);
+
+/**
+ * The callback to report an available fragment of a GPS navigation messages from the HAL.
+ *
+ * Parameters:
+ * message - The GPS navigation submessage/subframe representation.
+ */
+typedef void (*gnss_navigation_message_callback) (GnssNavigationMessage* message);
+
+typedef struct {
+ /** set to sizeof(GpsNavigationMessageCallbacks) */
+ size_t size;
+ gps_navigation_message_callback navigation_message_callback;
+ gnss_navigation_message_callback gnss_navigation_message_callback;
+} GpsNavigationMessageCallbacks;
+
+/**
+ * Extended interface for GPS navigation message reporting support.
+ */
+typedef struct {
+ /** Set to sizeof(GpsNavigationMessageInterface) */
+ size_t size;
+
+ /**
+ * Initializes the interface and registers the callback routines with the HAL.
+ * After a successful call to 'init' the HAL must begin to provide updates as they become
+ * available.
+ *
+ * Status:
+ * GPS_NAVIGATION_MESSAGE_OPERATION_SUCCESS
+ * GPS_NAVIGATION_MESSAGE_ERROR_ALREADY_INIT - if a callback has already been registered
+ * without a corresponding call to 'close'.
+ * GPS_NAVIGATION_MESSAGE_ERROR_GENERIC - if any other error occurred, it is expected that
+ * the HAL will not generate any updates upon returning this error code.
+ */
+ int (*init) (GpsNavigationMessageCallbacks* callbacks);
+
+ /**
+ * Stops updates from the HAL, and unregisters the callback routines.
+ * After a call to stop, the previously registered callbacks must be considered invalid by the
+ * HAL.
+ * If stop is invoked without a previous 'init', this function should perform no work.
+ */
+ void (*close) ();
+
+} GpsNavigationMessageInterface;
+
+/**
+ * Interface for passing GNSS configuration contents from platform to HAL.
+ */
+typedef struct {
+ /** Set to sizeof(GnssConfigurationInterface) */
+ size_t size;
+
+ /**
+ * Deliver GNSS configuration contents to HAL.
+ * Parameters:
+ * config_data - a pointer to a char array which holds what usually is expected from
+ file(/etc/gps.conf), i.e., a sequence of UTF8 strings separated by '\n'.
+ * length - total number of UTF8 characters in configuraiton data.
+ *
+ * IMPORTANT:
+ * GPS HAL should expect this function can be called multiple times. And it may be
+ * called even when GpsLocationProvider is already constructed and enabled. GPS HAL
+ * should maintain the existing requests for various callback regardless the change
+ * in configuration data.
+ */
+ void (*configuration_update) (const char* config_data, int32_t length);
+} GnssConfigurationInterface;
+
+__END_DECLS
+
+#endif /* ANDROID_INCLUDE_HARDWARE_GPS_H */
+
diff --git a/src/connectivity/gps/gps_hal/inc/gps_internal.h b/src/connectivity/gps/gps_hal/inc/gps_internal.h
new file mode 100644
index 0000000..0aa335d
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/inc/gps_internal.h
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_INCLUDE_HARDWARE_GPS_INTERNAL_H
+#define ANDROID_INCLUDE_HARDWARE_GPS_INTERNAL_H
+
+#ifdef __ANDROID_OS__
+#include "hardware/gps.h"
+#else
+#include "gps.h"
+#endif
+
+/****************************************************************************
+ * This file contains legacy structs that are deprecated/retired from gps.h *
+ ****************************************************************************/
+
+__BEGIN_DECLS
+
+/**
+ * Legacy GPS callback structure.
+ * Deprecated, to be removed in the next Android release.
+ * Use GpsCallbacks instead.
+ */
+typedef struct {
+ /** set to sizeof(GpsCallbacks_v1) */
+ size_t size;
+ gps_location_callback location_cb;
+ gps_status_callback status_cb;
+ gps_sv_status_callback sv_status_cb;
+ gps_nmea_callback nmea_cb;
+ gps_set_capabilities set_capabilities_cb;
+ gps_acquire_wakelock acquire_wakelock_cb;
+ gps_release_wakelock release_wakelock_cb;
+ gps_create_thread create_thread_cb;
+ gps_request_utc_time request_utc_time_cb;
+} GpsCallbacks_v1;
+
+#pragma pack(push,4)
+// We need to keep the alignment of this data structure to 4-bytes, to ensure that in 64-bit
+// environments the size of this legacy definition does not collide with _v2. Implementations should
+// be using _v2 and _v3, so it's OK to pay the 'unaligned' penalty in 64-bit if an old
+// implementation is still in use.
+
+/**
+ * Legacy struct to represent the status of AGPS.
+ */
+typedef struct {
+ /** set to sizeof(AGpsStatus_v1) */
+ size_t size;
+ AGpsType type;
+ AGpsStatusValue status;
+} AGpsStatus_v1;
+
+#pragma pack(pop)
+
+/**
+ * Legacy struct to represent the status of AGPS augmented with a IPv4 address
+ * field.
+ */
+typedef struct {
+ /** set to sizeof(AGpsStatus_v2) */
+ size_t size;
+ AGpsType type;
+ AGpsStatusValue status;
+
+ /*-------------------- New fields in _v2 --------------------*/
+
+ uint32_t ipaddr;
+} AGpsStatus_v2;
+
+/**
+ * Legacy extended interface for AGPS support.
+ * See AGpsInterface_v2 for more information.
+ */
+typedef struct {
+ /** set to sizeof(AGpsInterface_v1) */
+ size_t size;
+ void (*init)( AGpsCallbacks* callbacks );
+ int (*data_conn_open)( const char* apn );
+ int (*data_conn_closed)();
+ int (*data_conn_failed)();
+ int (*set_server)( AGpsType type, const char* hostname, int port );
+} AGpsInterface_v1;
+
+__END_DECLS
+
+#endif /* ANDROID_INCLUDE_HARDWARE_GPS_INTERNAL_H */
diff --git a/src/connectivity/gps/gps_hal/inc/gpshal.h b/src/connectivity/gps/gps_hal/inc/gpshal.h
new file mode 100644
index 0000000..0b0f9e2
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/inc/gpshal.h
@@ -0,0 +1,99 @@
+/* Copyright Statement:
+ *
+ * This software/firmware and related documentation ("MediaTek Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to MediaTek Inc. and/or its licensors.
+ * Without the prior written permission of MediaTek inc. and/or its licensors,
+ * any reproduction, modification, use or disclosure of MediaTek Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ *
+ * MediaTek Inc. (C) 2016. All rights reserved.
+ *
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
+ * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
+ * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
+ *
+ * The following software/firmware and/or related documentation ("MediaTek Software")
+ * have been modified by MediaTek Inc. All revisions are subject to any receiver's
+ * applicable license agreements with MediaTek Inc.
+ */
+#ifndef __GPS_HAL_H__
+#define __GPS_HAL_H__
+
+#include "hardware/gps_mtk.h"
+#include <pthread.h>
+
+//=========================================================
+
+#define MAX_EPOLL_EVENT 50
+
+//=========================================================
+
+typedef enum { // state order is important
+ GPSHAL_STATE_UNKNOWN,
+ GPSHAL_STATE_RESOURCE,
+ GPSHAL_STATE_CLEANUP,
+ GPSHAL_STATE_INIT, // == STOP
+ GPSHAL_STATE_STOP, // == INIT
+ GPSHAL_STATE_START
+} gpshal_state;
+
+typedef struct {
+ int fd_mnl2hal;
+ int fd_worker_epoll;
+ pthread_t thd_worker;
+
+ pthread_mutex_t mutex_gps_state_intent;
+ gpshal_state gps_state_intent; // what we want
+ gpshal_state gps_state; // what we are, but we may fail to change it
+
+ GpsCallbacks_ext* gps_cbs;
+ AGpsCallbacks* agps_cbs;
+ GpsNiCallbacks* gpsni_cbs;
+ AGpsRilCallbacks* agpsril_cbs;
+ GpsMeasurementCallbacks_ext* meas_cbs;
+ GpsNavigationMessageCallbacks* navimsg_cbs;
+ GpsGeofenceCallbacks* geofence_cbs;
+ VzwDebugCallbacks* vzw_debug_cbs;
+} gpshal_context_t;
+
+//=========================================================
+
+extern gpshal_context_t g_gpshal_ctx;
+extern const AGpsInterface mtk_agps_inf;
+extern const GpsNiInterface mtk_gps_ni_inf;
+extern const AGpsRilInterface mtk_agps_ril_inf;
+extern const GpsGeofencingInterface mtkGeofence_inf;
+
+
+//=========================================================
+
+extern const char* gpshal_state_to_string(gpshal_state state);
+
+extern int gpshal_gpscbs_save(GpsCallbacks_ext* src);
+
+extern void gpshal_set_gps_state_intent(gpshal_state newState);
+
+extern void gpshal2mnl_gps_init();
+extern void gpshal2mnl_gps_start();
+extern void gpshal2mnl_gps_stop();
+extern void gpshal2mnl_gps_cleanup();
+
+extern void gpshal_worker_thread(void *arg);
+
+#endif // __GPS_HAL_DEBUG_H__
diff --git a/src/connectivity/gps/gps_hal/inc/gpshal_param_check.h b/src/connectivity/gps/gps_hal/inc/gpshal_param_check.h
new file mode 100644
index 0000000..c87ec98
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/inc/gpshal_param_check.h
@@ -0,0 +1,91 @@
+/* Copyright Statement:
+ *
+ * This software/firmware and related documentation ("MediaTek Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to MediaTek Inc. and/or its licensors.
+ * Without the prior written permission of MediaTek inc. and/or its licensors,
+ * any reproduction, modification, use or disclosure of MediaTek Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ *
+ * MediaTek Inc. (C) 2016. All rights reserved.
+ *
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
+ * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
+ * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
+ *
+ * The following software/firmware and/or related documentation ("MediaTek Software")
+ * have been modified by MediaTek Inc. All revisions are subject to any receiver's
+ * applicable license agreements with MediaTek Inc.
+ */
+
+#ifndef __GPS_HAL_PARAM_CHECK_H__
+#define __GPS_HAL_PARAM_CHECK_H__
+
+#include <string.h>
+
+#if 0 != PARAM_CHECK // PARAM_CHECK is enabled
+ #define GPS_HW_MODULE_OPEN__CHECK_PARAM \
+ do { \
+ if (&HAL_MODULE_INFO_SYM != module) { \
+ ALOGT("-: Bad module object"); \
+ return -1; /* Fail: any non-zero value */ \
+ } else if (NULL == id || strcmp(id, HAL_MODULE_INFO_SYM.id)) { \
+ ALOGT("-: Bad id"); \
+ return -2; \
+ } else if (NULL == device) { \
+ ALOGT("-: Bad device"); \
+ return -3; \
+ } \
+ } while (0)
+ #define GPS_DEVICE__GET_GPS_INTERFACE__CHECK_PARAM \
+ do { \
+ if (NULL == device || \
+ &HAL_MODULE_INFO_SYM != device->common.module || \
+ gps_device__get_gps_interface != device->get_gps_interface) { \
+ ALOGT("-: Bad device object"); \
+ return NULL; \
+ } \
+ } while (0)
+#elif !defined(NDEBUG) // assert() is effective
+ #define GPS_HW_MODULE_OPEN__CHECK_PARAM \
+ do { \
+ assert(&HAL_MODULE_INFO_SYM == module); \
+ assert(NULL != id); \
+ assert(NULL != device); \
+ assert(0 == strcmp(id, HAL_MODULE_INFO_SYM.id)); \
+ } while (0)
+ #define GPS_DEVICE__GET_GPS_INTERFACE__CHECK_PARAM \
+ do { \
+ assert(NULL != device); \
+ assert(&HAL_MODULE_INFO_SYM == device->common.module); \
+ assert(gps_device__get_gps_interface == device->get_gps_interface); \
+ } while (0)
+#else
+ // PARAM_CHECK is disabled
+ // And assert() is not effective
+ #define GPS_HW_MODULE_OPEN__CHECK_PARAM \
+ do { \
+ UNUSED(module); \
+ UNUSED(id); \
+ } while (0)
+ #define GPS_DEVICE__GET_GPS_INTERFACE__CHECK_PARAM \
+ UNUSED(device)
+#endif
+
+
+#endif // __GPS_HAL_PARAM_CHECK_H__
\ No newline at end of file
diff --git a/src/connectivity/gps/gps_hal/inc/hal2mnl_interface.h b/src/connectivity/gps/gps_hal/inc/hal2mnl_interface.h
new file mode 100644
index 0000000..77cd331
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/inc/hal2mnl_interface.h
@@ -0,0 +1,87 @@
+#ifndef __HAL2MNL_INTERFACE_H__
+#define __HAL2MNL_INTERFACE_H__
+
+#include "hal_mnl_interface_common.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ void (*mnld_reboot)();
+
+ void (*location)(gps_location location);
+ void (*gps_status)(gps_status status);
+ void (*gps_sv)(gnss_sv_info sv);
+ void (*nmea)(int64_t timestamp, const char* nmea, int length);
+ void (*gps_capabilities)(gps_capabilites capabilities);
+ void (*gps_measurements)(gps_data data);
+ void (*gps_navigation)(gps_nav_msg msg);
+ void (*gnss_measurements)(gnss_data data);
+ void (*gnss_navigation)(gnss_nav_msg msg);
+
+ void (*request_wakelock)();
+ void (*release_wakelock)();
+
+ void (*request_utc_time)();
+
+ void (*request_data_conn)(struct sockaddr_storage* addr);
+ void (*release_data_conn)();
+ void (*request_ni_notify)(int session_id, agps_notify_type type, const char* requestor_id,
+ const char* client_name, ni_encoding_type requestor_id_encoding,
+ ni_encoding_type client_name_encoding);
+ void (*request_set_id)(request_setid flags);
+ void (*request_ref_loc)(request_refloc flags);
+ void (*output_vzw_debug)(const char* str);
+ void (*update_gnss_name)(const char* name, int length);
+ void (*request_nlp)(bool independentFromGnss);
+} mnl2hal_interface;
+
+int hal2mnl_hal_reboot();
+
+int hal2mnl_gps_init();
+int hal2mnl_gps_start();
+int hal2mnl_gps_stop();
+int hal2mnl_gps_cleanup();
+
+int hal2mnl_gps_inject_time(int64_t time, int64_t time_reference, int uncertainty);
+int hal2mnl_gps_inject_location(double lat, double lng, float acc);
+int hal2mnl_gps_delete_aiding_data(int flags);
+int hal2mnl_gps_set_position_mode(gps_pos_mode mode, gps_pos_recurrence recurrence,
+ int min_interval, int preferred_acc, int preferred_time, bool lowPowerMode);
+
+int hal2mnl_data_conn_open(const char* apn);
+int hal2mnl_data_conn_open_with_apn_ip_type(const char* apn, apn_ip_type ip_type);
+int hal2mnl_data_conn_closed();
+int hal2mnl_data_conn_failed();
+
+int hal2mnl_set_server(agps_type type, const char* hostname, int port);
+int hal2mnl_set_ref_location(cell_type type, int mcc, int mnc, int lac, int cid);
+int hal2mnl_set_id(agps_id_type type, const char* setid);
+
+int hal2mnl_ni_message(char* msg, int len);
+int hal2mnl_ni_respond(int notif_id, ni_user_response_type user_response);
+
+int hal2mnl_update_network_state(int connected, network_type type, int roaming,
+ const char* extra_info);
+int hal2mnl_update_network_availability(int available, const char* apn);
+
+int hal2mnl_set_gps_measurement(bool enabled, bool enableFullTracking);
+int hal2mnl_set_gps_navigation(bool enabled);
+
+int hal2mnl_set_vzw_debug(bool enabled);
+int hal2mnl_update_gnss_config(const char* config_data, int length);
+int hal2mnl_setBlacklist(long long* blacklist, int32_t size);
+
+// -1 means failure
+int mnl2hal_hdlr(int fd, mnl2hal_interface* hdlr);
+
+// -1 means failure
+int create_mnl2hal_fd();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/src/connectivity/gps/gps_hal/inc/hal_mnl_interface_common.h b/src/connectivity/gps/gps_hal/inc/hal_mnl_interface_common.h
new file mode 100644
index 0000000..ab01a3a
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/inc/hal_mnl_interface_common.h
@@ -0,0 +1,1353 @@
+#ifndef __HAL_MNL_INTERFACE_COMMON_H__
+#define __HAL_MNL_INTERFACE_COMMON_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <time.h>
+#include <sys/socket.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define HAL_MNL_BUFF_SIZE (16 * 1024)
+#define HAL_MNL_INTERFACE_VERSION 1
+
+//======================================================
+// GPS HAL -> MNLD
+//======================================================
+#define MTK_HAL2MNL "mtk_hal2mnl"
+
+typedef enum {
+ HAL2MNL_HAL_REBOOT = 0,
+ HAL2MNL_GPS_INIT = 101,
+ HAL2MNL_GPS_START = 102,
+ HAL2MNL_GPS_STOP = 103,
+ HAL2MNL_GPS_CLEANUP = 104,
+ HAL2MNL_GPS_INJECT_TIME = 105,
+ HAL2MNL_GPS_INJECT_LOCATION = 106,
+ HAL2MNL_GPS_DELETE_AIDING_DATA = 107,
+ HAL2MNL_GPS_SET_POSITION_MODE = 108,
+ HAL2MNL_DATA_CONN_OPEN = 201,
+ HAL2MNL_DATA_CONN_OPEN_WITH_APN_IP_TYPE = 202,
+ HAL2MNL_DATA_CONN_CLOSED = 203,
+ HAL2MNL_DATA_CONN_FAILED = 204,
+ HAL2MNL_SET_SERVER = 301,
+ HAL2MNL_SET_REF_LOCATION = 302,
+ HAL2MNL_SET_ID = 303,
+ HAL2MNL_NI_MESSAGE = 401,
+ HAL2MNL_NI_RESPOND = 402,
+ HAL2MNL_UPDATE_NETWORK_STATE = 501,
+ HAL2MNL_UPDATE_NETWORK_AVAILABILITY = 502,
+ HAL2MNL_GPS_MEASUREMENT = 601,
+ HAL2MNL_GPS_NAVIGATION = 602,
+ HAL2MNL_VZW_DEBUG = 603,
+ HAL2MNL_GNSS_CONFIG = 604,
+ //HAL2MNL_SV_BLACKLIST = 605,
+ HAL2MNL_SEND_PMTK = 701,
+} hal2mnl_cmd;
+
+typedef int gps_pos_mode;
+#define GPS_POS_MODE_STANDALONE 0
+#define GPS_POS_MODE_MSB 1
+
+typedef int gps_pos_recurrence;
+#define GPS_POS_RECURRENCE_PERIODIC 0
+#define GPS_POS_RECURRENCE_SINGLE 1
+
+typedef int ni_user_response_type;
+#define NI_USER_RESPONSE_ACCEPT 1
+#define NI_USER_RESPONSE_DENY 2
+#define NI_USER_RESPONSE_NORESP 3
+
+typedef int cell_type;
+#define CELL_TYPE_GSM 1
+#define CELL_TYPE_UMTS 2
+
+typedef int agps_id_type;
+#define AGPS_ID_TYPE_NONE 0
+#define AGPS_ID_TYPE_IMSI 1
+#define AGPS_ID_TYPE_MSISDN 2
+
+typedef int network_type;
+#define NETWORK_TYPE_MOBILE 0
+#define NETWORK_TYPE_WIFI 1
+#define NETWORK_TYPE_MOBILE_MMS 2
+#define NETWORK_TYPE_MOBILE_SUPL 3
+#define NETWORK_TYPE_MOBILE_DUN 4
+#define NETWORK_TYPE_MOBILE_HIPRI 5
+#define NETWORK_TYPE_WIMAX 6
+
+typedef int apn_ip_type;
+#define MTK_APN_IP_INVALID 0
+#define MTK_APN_IP_IPV4 1
+#define MTK_APN_IP_IPV6 2
+#define MTK_APN_IP_IPV4V6 3
+
+typedef int agps_type;
+#define MTK_AGPS_TYPE_SUPL 1
+#define MTK_AGPS_TYPE_C2K 2
+
+//======================================================
+// MNLD -> GPS HAL
+//======================================================
+#define MTK_MNL2HAL "mtk_mnl2hal"
+
+typedef enum {
+ MNL2HAL_MNLD_REBOOT = 1,
+ MNL2HAL_LOCATION = 101,
+ MNL2HAL_GPS_STATUS = 102,
+ MNL2HAL_GPS_SV = 103,
+ MNL2HAL_NMEA = 104,
+ MNL2HAL_GPS_CAPABILITIES = 105,
+ MNL2HAL_GPS_MEASUREMENTS = 106,
+ MNL2HAL_GPS_NAVIGATION = 107,
+ MNL2HAL_GNSS_MEASUREMENTS = 108,
+ MNL2HAL_GNSS_NAVIGATION = 109,
+ MNL2HAL_REQUEST_WAKELOCK = 201,
+ MNL2HAL_RELEASE_WAKELOCK = 202,
+ MNL2HAL_REQUEST_UTC_TIME = 301,
+ MNL2HAL_REQUEST_DATA_CONN = 302,
+ MNL2HAL_RELEASE_DATA_CONN = 303,
+ MNL2HAL_REQUEST_NI_NOTIFY = 304,
+ MNL2HAL_REQUEST_SET_ID = 305,
+ MNL2HAL_REQUEST_REF_LOC = 306,
+ MNL2HAL_VZW_DEBUG_OUTPUT = 307,
+ MNL2HAL_UPDATE_GNSS_NAME = 308,
+ MNL2HAL_REQUEST_NLP = 309,
+} mnl2hal_cmd;
+
+#define MTK_HAL_GNSS_MAX_SVS 64
+#define GPS_MAX_MEASUREMENT 32
+#define MTK_HAL_GNSS_MAX_MEASUREMENT 64
+
+typedef int gps_location_flags;
+#define MTK_GPS_LOCATION_HAS_LAT_LONG 0x0001
+#define MTK_GPS_LOCATION_HAS_ALT 0x0002
+#define MTK_GPS_LOCATION_HAS_SPEED 0x0004
+#define MTK_GPS_LOCATION_HAS_BEARING 0x0008
+#define MTK_GPS_LOCATION_HAS_HORIZONTAL_ACCURACY 0x0010
+#define MTK_GPS_LOCATION_HAS_VERTICAL_ACCURACY 0x0020
+#define MTK_GPS_LOCATION_HAS_SPEED_ACCURACY 0x0040
+#define MTK_GPS_LOCATION_HAS_BEARING_ACCURACY 0x0080
+
+typedef int gps_capabilites;
+#define GPS_CAP_NONE 0x0010000
+#define GPS_CAP_SCHEDULING 0x0000001
+#define GPS_CAP_MSB 0x0000002
+#define GPS_CAP_MSA 0x0000004
+#define GPS_CAP_SINGLE_SHOT 0x0000008
+#define GPS_CAP_ON_DEMAND_TIME 0x0000010
+#define GPS_CAP_GEOFENCING 0x0000020
+#define GPS_CAP_MEASUREMENTS 0x0000040
+#define GPS_CAP_NAV_MESSAGES 0x0000080
+
+typedef int request_setid;
+#define REQUEST_SETID_IMSI (1<<0L)
+#define REQUEST_SETID_MSISDN (1<<1L)
+
+typedef int request_refloc;
+#define REQUEST_REFLOC_CELLID (1<<0L)
+#define REQUEST_REFLOC_MAC (1<<1L) // not ready
+
+typedef short gps_clock_flags;
+#define GPS_CLK_HAS_LEAP_SECOND (1<<0)
+#define GPS_CLK_HAS_TIME_UNCERTAINTY (1<<1)
+#define GPS_CLK_HAS_FULL_BIAS (1<<2)
+#define GPS_CLK_HAS_BIAS (1<<3)
+#define GPS_CLK_HAS_BIAS_UNCERTAINTY (1<<4)
+#define GPS_CLK_HAS_DRIFT (1<<5)
+#define GPS_CLK_HAS_DRIFT_UNCERTAINTY (1<<6)
+
+typedef char gps_clock_type;
+#define GPS_CLOCK_TYPE_UNKNOWN 0
+#define GPS_CLOCK_TYPE_LOCAL_HW_TIME 1
+#define GPS_CLOCK_TYPE_GPS_TIME 2
+
+typedef int gps_measurement_flags;
+#define GPS_MEASUREMENT_HAS_SNR (1<<0)
+#define GPS_MEASUREMENT_HAS_ELEVATION (1<<1)
+#define GPS_MEASUREMENT_HAS_ELEVATION_UNCERTAINTY (1<<2)
+#define GPS_MEASUREMENT_HAS_AZIMUTH (1<<3)
+#define GPS_MEASUREMENT_HAS_AZIMUTH_UNCERTAINTY (1<<4)
+#define GPS_MEASUREMENT_HAS_PSEUDORANGE (1<<5)
+#define GPS_MEASUREMENT_HAS_PSEUDORANGE_UNCERTAINTY (1<<6)
+#define GPS_MEASUREMENT_HAS_CODE_PHASE (1<<7)
+#define GPS_MEASUREMENT_HAS_CODE_PHASE_UNCERTAINTY (1<<8)
+#define GPS_MEASUREMENT_HAS_CARRIER_FREQUENCY (1<<9)
+#define GPS_MEASUREMENT_HAS_CARRIER_CYCLES (1<<10)
+#define GPS_MEASUREMENT_HAS_CARRIER_PHASE (1<<11)
+#define GPS_MEASUREMENT_HAS_CARRIER_PHASE_UNCERTAINTY (1<<12)
+#define GPS_MEASUREMENT_HAS_BIT_NUMBER (1<<13)
+#define GPS_MEASUREMENT_HAS_TIME_FROM_LAST_BIT (1<<14)
+#define GPS_MEASUREMENT_HAS_DOPPLER_SHIFT (1<<15)
+#define GPS_MEASUREMENT_HAS_DOPPLER_SHIFT_UNCERTAINTY (1<<16)
+#define GPS_MEASUREMENT_HAS_USED_IN_FIX (1<<17)
+
+typedef short gps_measurement_state;
+#define GPS_MEASUREMENT_STATE_UNKNOWN 0
+#define GPS_MEASUREMENT_STATE_CODE_LOCK (1<<0)
+#define GPS_MEASUREMENT_STATE_BIT_SYNC (1<<1)
+#define GPS_MEASUREMENT_STATE_SUBFRAME_SYNC (1<<2)
+#define GPS_MEASUREMENT_STATE_TOW_DECODED (1<<3)
+#define GPS_MEASUREMENT_STATE_MSEC_AMBIGUOUS (1<<4)
+
+typedef short gps_accumulated_delta_range_state;
+#define GPS_ADR_STATE_UNKNOWN 0
+#define GPS_ADR_STATE_VALID (1<<0)
+#define GPS_ADR_STATE_RESET (1<<1)
+#define GPS_ADR_STATE_CYCLE_SLIP (1<<2)
+
+typedef char gps_loss_of_lock;
+#define GPS_LOSS_OF_LOCK_UNKNOWN 0
+#define GPS_LOSS_OF_LOCK_OK 1
+#define GPS_LOSS_OF_LOCK_CYCLE_SLIP 2
+
+typedef char gps_multipath_indicator;
+#define GPS_MULTIPATH_INDICATOR_UNKNOWN 0
+#define GPS_MULTIPATH_INDICATOR_DETECTED 1
+#define GPS_MULTIPATH_INDICATOR_NOT_USED 2
+
+typedef char gps_nav_msg_type;
+#define GPS_NAV_MSG_TYPE_UNKNOWN 0
+#define GPS_NAV_MSG_TYPE_L1CA 1
+#define GPS_NAV_MSG_TYPE_L2CNAV 2
+#define GPS_NAV_MSG_TYPE_L5CNAV 3
+#define GPS_NAV_MSG_TYPE_CNAV2 4
+
+typedef short nav_msg_status;
+#define NAV_MSG_STATUS_UNKONW 0
+#define NAV_MSG_STATUS_PARITY_PASSED (1<<0)
+#define NAV_MSG_STATUS_PARITY_REBUILT (1<<1)
+
+typedef int gps_status;
+#define MTK_GPS_STATUS_SESSION_BEGIN 1
+#define MTK_GPS_STATUS_SESSION_END 2
+#define MTK_GPS_STATUS_SESSION_ENGINE_ON 3
+#define MTK_GPS_STATUS_SESSION_ENGINE_OFF 4
+
+typedef int agps_ni_type;
+#define AGPS_NI_TYPE_VOICE 1
+#define AGPS_NI_TYPE_UMTS_SUPL 2
+#define AGPS_NI_TYPE_UMTS_CTRL_PLANE 3
+#define AGPS_NI_TYPE_EMERGENCY_SUPL 4
+
+typedef int agps_notify_type;
+#define AGPS_NOTIFY_TYPE_NONE 0
+#define AGPS_NOTIFY_TYPE_NOTIFY_ONLY 1
+#define AGPS_NOTIFY_TYPE_NOTIFY_ALLOW_NO_ANSWER 2
+#define AGPS_NOTIFY_TYPE_NOTIFY_DENY_NO_ANSWER 3
+#define AGPS_NOTIFY_TYPE_PRIVACY 4
+
+typedef int ni_encoding_type;
+#define NI_ENCODING_TYPE_NONE 0
+#define NI_ENCODING_TYPE_GSM7 1
+#define NI_ENCODING_TYPE_UTF8 2
+#define NI_ENCODING_TYPE_UCS2 3
+
+typedef struct {
+ gps_location_flags flags;
+ double lat;
+ double lng;
+ double alt;
+ float speed;
+ float bearing;
+ float h_accuracy; //horizontal
+ float v_accuracy; //vertical
+ float s_accuracy; //spedd
+ float b_accuracy; //bearing
+ int64_t timestamp;
+} gps_location;
+
+typedef struct {
+ int16_t svid;
+ uint8_t constellation;
+ float c_n0_dbhz;
+ float elevation;
+ float azimuth;
+ uint8_t flags;
+ float carrier_frequency;
+} gnss_sv;
+
+typedef struct {
+ int num_svs;
+ gnss_sv sv_list[MTK_HAL_GNSS_MAX_SVS];
+} gnss_sv_info;
+
+typedef struct {
+ int prn;
+ bool has_ephemeris_data;
+ bool has_almanac_data;
+ bool used_in_fix;
+} NmeaCash;
+
+typedef uint16_t MTK_HAL_NavigationMessageStatus;
+#define MTK_NAV_MESSAGE_STATUS_UNKNOWN 0
+#define MTK_NAV_MESSAGE_STATUS_PARITY_PASSED (1<<0)
+#define MTK_NAV_MESSAGE_STATUS_PARITY_REBUILT (1<<1)
+
+typedef int16_t MTK_HAL_GnssNavigationMessageType;
+#define MTK_GNSS_NAVIGATION_MESSAGE_TYPE_UNKNOWN 0
+/** GPS L1 C/A message contained in the structure. */
+#define MTK_GNSS_NAVIGATION_MESSAGE_TYPE_GPS_L1CA 0x0101
+/** GPS L2-CNAV message contained in the structure. */
+#define MTK_GNSS_NAVIGATION_MESSAGE_TYPE_GPS_L2CNAV 0x0102
+/** GPS L5-CNAV message contained in the structure. */
+#define MTK_GNSS_NAVIGATION_MESSAGE_TYPE_GPS_L5CNAV 0x0103
+/** GPS CNAV-2 message contained in the structure. */
+#define MTK_GNSS_NAVIGATION_MESSAGE_TYPE_GPS_CNAV2 0x0104
+/** Glonass L1 CA message contained in the structure. */
+#define MTK_GNSS_NAVIGATION_MESSAGE_TYPE_GLO_L1CA 0x0301
+/** Beidou D1 message contained in the structure. */
+#define MTK_GNSS_NAVIGATION_MESSAGE_TYPE_BDS_D1 0x0501
+/** Beidou D2 message contained in the structure. */
+#define MTK_GNSS_NAVIGATION_MESSAGE_TYPE_BDS_D2 0x0502
+/** Galileo I/NAV message contained in the structure. */
+#define MTK_GNSS_NAVIGATION_MESSAGE_TYPE_GAL_I 0x0601
+/** Galileo F/NAV message contained in the structure. */
+#define MTK_GNSS_NAVIGATION_MESSAGE_TYPE_GAL_F 0x0602
+
+typedef uint8_t MTK_HAL_GnssMultipathIndicator;
+/** The indicator is not available or unknown. */
+#define MTK_GNSS_MULTIPATH_INDICATOR_UNKNOWN 0
+/** The measurement is indicated to be affected by multipath. */
+#define MTK_GNSS_MULTIPATH_INDICATOR_PRESENT 1
+/** The measurement is indicated to be not affected by multipath. */
+#define MTK_GNSS_MULTIPATH_INDICATOR_NOT_PRESENT 2
+
+typedef uint16_t MTK_HAL_GnssAccumulatedDeltaRangeState;
+#define MTK_GNSS_ADR_STATE_UNKNOWN 0
+#define MTK_GNSS_ADR_STATE_VALID (1<<0)
+#define MTK_GNSS_ADR_STATE_RESET (1<<1)
+#define MTK_GNSS_ADR_STATE_CYCLE_SLIP (1<<2)
+
+typedef uint32_t MTK_HAL_GnssMeasurementState;
+#define MTK_GNSS_MEASUREMENT_STATE_UNKNOWN 0
+#define MTK_GNSS_MEASUREMENT_STATE_CODE_LOCK (1<<0)
+#define MTK_GNSS_MEASUREMENT_STATE_BIT_SYNC (1<<1)
+#define MTK_GNSS_MEASUREMENT_STATE_SUBFRAME_SYNC (1<<2)
+#define MTK_GNSS_MEASUREMENT_STATE_TOW_DECODED (1<<3)
+#define MTK_GNSS_MEASUREMENT_STATE_MSEC_AMBIGUOUS (1<<4)
+#define MTK_GNSS_MEASUREMENT_STATE_SYMBOL_SYNC (1<<5)
+#define MTK_GNSS_MEASUREMENT_STATE_GLO_STRING_SYNC (1<<6)
+#define MTK_GNSS_MEASUREMENT_STATE_GLO_TOD_DECODED (1<<7)
+#define MTK_GNSS_MEASUREMENT_STATE_BDS_D2_BIT_SYNC (1<<8)
+#define MTK_GNSS_MEASUREMENT_STATE_BDS_D2_SUBFRAME_SYNC (1<<9)
+#define MTK_GNSS_MEASUREMENT_STATE_GAL_E1BC_CODE_LOCK (1<<10)
+#define MTK_GNSS_MEASUREMENT_STATE_GAL_E1C_2ND_CODE_LOCK (1<<11)
+#define MTK_GNSS_MEASUREMENT_STATE_GAL_E1B_PAGE_SYNC (1<<12)
+#define MTK_GNSS_MEASUREMENT_STATE_SBAS_SYNC (1<<13)
+
+typedef uint8_t MTK_HAL_GnssConstellationType;
+#define MTK_GNSS_CONSTELLATION_UNKNOWN 0
+#define MTK_GNSS_CONSTELLATION_GPS 1
+#define MTK_GNSS_CONSTELLATION_SBAS 2
+#define MTK_GNSS_CONSTELLATION_GLONASS 3
+#define MTK_GNSS_CONSTELLATION_QZSS 4
+#define MTK_GNSS_CONSTELLATION_BEIDOU 5
+#define MTK_GNSS_CONSTELLATION_GALILEO 6
+
+typedef uint32_t MTK_HAL_GnssMeasurementFlags;
+/** A valid 'snr' is stored in the data structure. */
+#define MTK_GNSS_MEASUREMENT_HAS_SNR (1<<0)
+/** A valid 'carrier frequency' is stored in the data structure. */
+#define MTK_GNSS_MEASUREMENT_HAS_CARRIER_FREQUENCY (1<<9)
+/** A valid 'carrier cycles' is stored in the data structure. */
+#define MTK_GNSS_MEASUREMENT_HAS_CARRIER_CYCLES (1<<10)
+/** A valid 'carrier phase' is stored in the data structure. */
+#define MTK_GNSS_MEASUREMENT_HAS_CARRIER_PHASE (1<<11)
+/** A valid 'carrier phase uncertainty' is stored in the data structure. */
+#define MTK_GNSS_MEASUREMENT_HAS_CARRIER_PHASE_UNCERTAINTY (1<<12)
+
+typedef uint16_t MTK_HAL_GnssClockFlags;
+/** A valid 'leap second' is stored in the data structure. */
+#define MTK_GNSS_CLOCK_HAS_LEAP_SECOND (1<<0)
+/** A valid 'time uncertainty' is stored in the data structure. */
+#define MTK_GNSS_CLOCK_HAS_TIME_UNCERTAINTY (1<<1)
+/** A valid 'full bias' is stored in the data structure. */
+#define MTK_GNSS_CLOCK_HAS_FULL_BIAS (1<<2)
+/** A valid 'bias' is stored in the data structure. */
+#define MTK_GNSS_CLOCK_HAS_BIAS (1<<3)
+/** A valid 'bias uncertainty' is stored in the data structure. */
+#define MTK_GNSS_CLOCK_HAS_BIAS_UNCERTAINTY (1<<4)
+/** A valid 'drift' is stored in the data structure. */
+#define MTK_GNSS_CLOCK_HAS_DRIFT (1<<5)
+/** A valid 'drift uncertainty' is stored in the data structure. */
+#define MTK_GNSS_CLOCK_HAS_DRIFT_UNCERTAINTY (1<<6)
+
+typedef struct {
+ /** A set of flags indicating the validity of the fields in this data structure. */
+ gps_clock_flags flags;
+
+ /**
+ * Leap second data.
+ * The sign of the value is defined by the following equation:
+ * utc_time_ns = time_ns + (full_bias_ns + bias_ns) - leap_second * 1,000,000,000
+ *
+ * If the data is available 'flags' must contain GPS_CLOCK_HAS_LEAP_SECOND.
+ */
+ short leap_second;
+
+ /**
+ * Indicates the type of time reported by the 'time_ns' field.
+ */
+ gps_clock_type type;
+
+ /**
+ * The GPS receiver internal clock value. This can be either the local hardware clock value
+ * (GPS_CLOCK_TYPE_LOCAL_HW_TIME), or the current GPS time derived inside GPS receiver
+ * (GPS_CLOCK_TYPE_GPS_TIME). The field 'type' defines the time reported.
+ *
+ * For local hardware clock, this value is expected to be monotonically increasing during
+ * the reporting session. The real GPS time can be derived by compensating the 'full bias'
+ * (when it is available) from this value.
+ *
+ * For GPS time, this value is expected to be the best estimation of current GPS time that GPS
+ * receiver can achieve. Set the 'time uncertainty' appropriately when GPS time is specified.
+ *
+ * Sub-nanosecond accuracy can be provided by means of the 'bias' field.
+ * The value contains the 'time uncertainty' in it.
+ */
+ int64_t time_ns;
+
+ /**
+ * 1-Sigma uncertainty associated with the clock's time in nanoseconds.
+ * The uncertainty is represented as an absolute (single sided) value.
+ *
+ * This value should be set if GPS_CLOCK_TYPE_GPS_TIME is set.
+ * If the data is available 'flags' must contain GPS_CLOCK_HAS_TIME_UNCERTAINTY.
+ */
+ double time_uncertainty_ns;
+
+ /**
+ * The difference between hardware clock ('time' field) inside GPS receiver and the true GPS
+ * time since 0000Z, January 6, 1980, in nanoseconds.
+ * This value is used if and only if GPS_CLOCK_TYPE_LOCAL_HW_TIME is set, and GPS receiver
+ * has solved the clock for GPS time.
+ * The caller is responsible for using the 'bias uncertainty' field for quality check.
+ *
+ * The sign of the value is defined by the following equation:
+ * true time (GPS time) = time_ns + (full_bias_ns + bias_ns)
+ *
+ * This value contains the 'bias uncertainty' in it.
+ * If the data is available 'flags' must contain GPS_CLOCK_HAS_FULL_BIAS.
+
+ */
+ int64_t full_bias_ns;
+
+ /**
+ * Sub-nanosecond bias.
+ * The value contains the 'bias uncertainty' in it.
+ *
+ * If the data is available 'flags' must contain GPS_CLOCK_HAS_BIAS.
+ */
+ double bias_ns;
+
+ /**
+ * 1-Sigma uncertainty associated with the clock's bias in nanoseconds.
+ * The uncertainty is represented as an absolute (single sided) value.
+ *
+ * If the data is available 'flags' must contain GPS_CLOCK_HAS_BIAS_UNCERTAINTY.
+ */
+ double bias_uncertainty_ns;
+
+ /**
+ * The clock's drift in nanoseconds (per second).
+ * A positive value means that the frequency is higher than the nominal frequency.
+ *
+ * The value contains the 'drift uncertainty' in it.
+ * If the data is available 'flags' must contain GPS_CLOCK_HAS_DRIFT.
+ *
+ * If GpsMeasurement's 'flags' field contains GPS_MEASUREMENT_HAS_UNCORRECTED_PSEUDORANGE_RATE,
+ * it is encouraged that this field is also provided.
+ */
+ double drift_nsps;
+
+ /**
+ * 1-Sigma uncertainty associated with the clock's drift in nanoseconds (per second).
+ * The uncertainty is represented as an absolute (single sided) value.
+ *
+ * If the data is available 'flags' must contain GPS_CLOCK_HAS_DRIFT_UNCERTAINTY.
+ */
+ double drift_uncertainty_nsps;
+} gps_clock;
+
+/**
+ * Represents an estimate of the GPS clock time.
+ */
+typedef struct {
+ /**
+ * A set of flags indicating the validity of the fields in this data
+ * structure.
+ */
+ MTK_HAL_GnssClockFlags flags;
+
+ /**
+ * Leap second data.
+ * The sign of the value is defined by the following equation:
+ * utc_time_ns = time_ns - (full_bias_ns + bias_ns) - leap_second *
+ * 1,000,000,000
+ *
+ * If the data is available 'flags' must contain GNSS_CLOCK_HAS_LEAP_SECOND.
+ */
+ int16_t leap_second;
+
+ /**
+ * The GNSS receiver internal clock value. This is the local hardware clock
+ * value.
+ *
+ * For local hardware clock, this value is expected to be monotonically
+ * increasing while the hardware clock remains power on. (For the case of a
+ * HW clock that is not continuously on, see the
+ * hw_clock_discontinuity_count field). The receiver's estimate of GPS time
+ * can be derived by substracting the sum of full_bias_ns and bias_ns (when
+ * available) from this value.
+ *
+ * This GPS time is expected to be the best estimate of current GPS time
+ * that GNSS receiver can achieve.
+ *
+ * Sub-nanosecond accuracy can be provided by means of the 'bias_ns' field.
+ * The value contains the 'time uncertainty' in it.
+ *
+ * This field is mandatory.
+ */
+ int64_t time_ns;
+
+ /**
+ * 1-Sigma uncertainty associated with the clock's time in nanoseconds.
+ * The uncertainty is represented as an absolute (single sided) value.
+ *
+ * If the data is available, 'flags' must contain
+ * GNSS_CLOCK_HAS_TIME_UNCERTAINTY. This value is effectively zero (it is
+ * the reference local clock, by which all other times and time
+ * uncertainties are measured.) (And thus this field can be not provided,
+ * per GNSS_CLOCK_HAS_TIME_UNCERTAINTY flag, or provided & set to 0.)
+ */
+ double time_uncertainty_ns;
+
+ /**
+ * The difference between hardware clock ('time' field) inside GPS receiver
+ * and the true GPS time since 0000Z, January 6, 1980, in nanoseconds.
+ *
+ * The sign of the value is defined by the following equation:
+ * local estimate of GPS time = time_ns - (full_bias_ns + bias_ns)
+ *
+ * This value is mandatory if the receiver has estimated GPS time. If the
+ * computed time is for a non-GPS constellation, the time offset of that
+ * constellation to GPS has to be applied to fill this value. The error
+ * estimate for the sum of this and the bias_ns is the bias_uncertainty_ns,
+ * and the caller is responsible for using this uncertainty (it can be very
+ * large before the GPS time has been solved for.) If the data is available
+ * 'flags' must contain GNSS_CLOCK_HAS_FULL_BIAS.
+ */
+ int64_t full_bias_ns;
+
+ /**
+ * Sub-nanosecond bias.
+ * The error estimate for the sum of this and the full_bias_ns is the
+ * bias_uncertainty_ns
+ *
+ * If the data is available 'flags' must contain GNSS_CLOCK_HAS_BIAS. If GPS
+ * has computed a position fix. This value is mandatory if the receiver has
+ * estimated GPS time.
+ */
+ double bias_ns;
+
+ /**
+ * 1-Sigma uncertainty associated with the local estimate of GPS time (clock
+ * bias) in nanoseconds. The uncertainty is represented as an absolute
+ * (single sided) value.
+ *
+ * If the data is available 'flags' must contain
+ * GNSS_CLOCK_HAS_BIAS_UNCERTAINTY. This value is mandatory if the receiver
+ * has estimated GPS time.
+ */
+ double bias_uncertainty_ns;
+
+ /**
+ * The clock's drift in nanoseconds (per second).
+ *
+ * A positive value means that the frequency is higher than the nominal
+ * frequency, and that the (full_bias_ns + bias_ns) is growing more positive
+ * over time.
+ *
+ * The value contains the 'drift uncertainty' in it.
+ * If the data is available 'flags' must contain GNSS_CLOCK_HAS_DRIFT.
+ *
+ * This value is mandatory if the receiver has estimated GNSS time
+ */
+ double drift_nsps;
+
+ /**
+ * 1-Sigma uncertainty associated with the clock's drift in nanoseconds (per second).
+ * The uncertainty is represented as an absolute (single sided) value.
+ *
+ * If the data is available 'flags' must contain
+ * GNSS_CLOCK_HAS_DRIFT_UNCERTAINTY. If GPS has computed a position fix this
+ * field is mandatory and must be populated.
+ */
+ double drift_uncertainty_nsps;
+
+ /**
+ * When there are any discontinuities in the HW clock, this field is
+ * mandatory.
+ *
+ * A "discontinuity" is meant to cover the case of a switch from one source
+ * of clock to another. A single free-running crystal oscillator (XO)
+ * should generally not have any discontinuities, and this can be set and
+ * left at 0.
+ *
+ * If, however, the time_ns value (HW clock) is derived from a composite of
+ * sources, that is not as smooth as a typical XO, or is otherwise stopped &
+ * restarted, then this value shall be incremented each time a discontinuity
+ * occurs. (E.g. this value may start at zero at device boot-up and
+ * increment each time there is a change in clock continuity. In the
+ * unlikely event that this value reaches full scale, rollover (not
+ * clamping) is required, such that this value continues to change, during
+ * subsequent discontinuity events.)
+ *
+ * While this number stays the same, between GnssClock reports, it can be
+ * safely assumed that the time_ns value has been running continuously, e.g.
+ * derived from a single, high quality clock (XO like, or better, that's
+ * typically used during continuous GNSS signal sampling.)
+ *
+ * It is expected, esp. during periods where there are few GNSS signals
+ * available, that the HW clock be discontinuity-free as long as possible,
+ * as this avoids the need to use (waste) a GNSS measurement to fully
+ * re-solve for the GPS clock bias and drift, when using the accompanying
+ * measurements, from consecutive GnssData reports.
+ */
+ uint32_t hw_clock_discontinuity_count;
+} gnss_clock;
+
+typedef struct {
+ /** A set of flags indicating the validity of the fields in this data structure. */
+ gps_measurement_flags flags;
+
+ /**
+ * Pseudo-random number in the range of [1, 32]
+ * This is a Mandatory value.
+ */
+ int8_t prn;
+
+ /**
+ * Time offset at which the measurement was taken in nanoseconds.
+ * The reference receiver's time is specified by GpsData::clock::time_ns and should be
+ * interpreted in the same way as indicated by GpsClock::type.
+ *
+ * The sign of time_offset_ns is given by the following equation:
+ * measurement time = GpsClock::time_ns + time_offset_ns
+ *
+ * It provides an individual time-stamp for the measurement, and allows sub-nanosecond accuracy.
+ * This is a Mandatory value.
+ */
+ double time_offset_ns;
+
+ /**
+ * Per satellite sync state. It represents the current sync state for the associated satellite.
+ * Based on the sync state, the 'received GPS tow' field should be interpreted accordingly.
+ * This is a Mandatory value.
+ */
+ gps_measurement_state state;
+
+ /**
+ * Received GPS Time-of-Week at the measurement time, in nanoseconds.
+ * The value is relative to the beginning of the current GPS week.
+ *
+ * Given the highest sync state that can be achieved, per each satellite, valid range for
+ * this field can be:
+ * Searching : [ 0 ] : GPS_MEASUREMENT_STATE_UNKNOWN
+ * C/A code lock : [ 0 1ms ] : GPS_MEASUREMENT_STATE_CODE_LOCK is set
+ * Bit sync : [ 0 20ms ] : GPS_MEASUREMENT_STATE_BIT_SYNC is set
+ * Subframe sync : [ 0 6s ] : GPS_MEASUREMENT_STATE_SUBFRAME_SYNC is set
+ * TOW decoded : [ 0 1week ] : GPS_MEASUREMENT_STATE_TOW_DECODED is set
+ *
+ * However, if there is any ambiguity in integer millisecond,
+ * GPS_MEASUREMENT_STATE_MSEC_AMBIGUOUS should be set accordingly, in the 'state' field.
+ * This value must be populated if 'state' != GPS_MEASUREMENT_STATE_UNKNOWN.
+ */
+ int64_t received_gps_tow_ns;
+
+ /**
+ * 1-Sigma uncertainty of the Received GPS Time-of-Week in nanoseconds.
+ * This value must be populated if 'state' != GPS_MEASUREMENT_STATE_UNKNOWN.
+ */
+ int64_t received_gps_tow_uncertainty_ns;
+
+ /**
+ * Carrier-to-noise density in dB-Hz, in the range [0, 63].
+ * It contains the measured C/N0 value for the signal at the antenna input.
+ * This is a Mandatory value.
+ */
+ double c_n0_dbhz;
+
+ /**
+ * Pseudorange rate at the timestamp in m/s.
+ * The value also includes the effects of the receiver clock frequency and satellite clock
+ * frequency errors.
+ *
+ * The value includes the 'pseudorange rate uncertainty' in it.
+ * A positive value indicates that the pseudorange is getting larger.
+ * This is a Mandatory value.
+ */
+ double pseudorange_rate_mps;
+
+ /**
+ * 1-Sigma uncertainty of the pseudurange rate in m/s.
+ * The uncertainty is represented as an absolute (single sided) value.
+ * This is a Mandatory value.
+ */
+ double pseudorange_rate_uncertainty_mps;
+
+ /**
+ * Accumulated delta range's state. It indicates whether ADR is reset or there is a cycle slip
+ * (indicating loss of lock).
+ * This is a Mandatory value.
+ */
+ gps_accumulated_delta_range_state accumulated_delta_range_state;
+
+ /**
+ * Accumulated delta range since the last channel reset in meters.
+ * A positive value indicates that the SV is moving away from the receiver.
+ *
+ * The sign of the 'accumulated delta range' and its relation to the sign of 'carrier phase'
+ * is given by the equation:
+ * accumulated delta range = -k * carrier phase (where k is a constant)
+ *
+ * This value must be populated if 'accumulated delta range state' != GPS_ADR_STATE_UNKNOWN.
+ * However, it is expected that the data is only accurate when:
+ * 'accumulated delta range state' == GPS_ADR_STATE_VALID.
+ */
+ double accumulated_delta_range_m;
+
+ /**
+ * 1-Sigma uncertainty of the accumulated delta range in meters.
+ * The data is available if 'accumulated delta range state' != GPS_ADR_STATE_UNKNOWN.
+ */
+ double accumulated_delta_range_uncertainty_m;
+
+ /**
+ * Best derived Pseudorange by the chip-set, in meters.
+ * The value contains the 'pseudorange uncertainty' in it.
+ *
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_PSEUDORANGE.
+ */
+ double pseudorange_m;
+
+ /**
+ * 1-Sigma uncertainty of the pseudorange in meters.
+ * The value contains the 'pseudorange' and 'clock' uncertainty in it.
+ * The uncertainty is represented as an absolute (single sided) value.
+ *
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_PSEUDORANGE_UNCERTAINTY.
+ */
+ double pseudorange_uncertainty_m;
+
+ /**
+ * A fraction of the current C/A code cycle, in the range [0.0, 1023.0]
+ * This value contains the time (in Chip units) since the last C/A code cycle (GPS Msec epoch).
+ *
+ * The reference frequency is given by the field 'carrier_frequency_hz'.
+ * The value contains the 'code-phase uncertainty' in it.
+ *
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_CODE_PHASE.
+ */
+ double code_phase_chips;
+
+ /**
+ * 1-Sigma uncertainty of the code-phase, in a fraction of chips.
+ * The uncertainty is represented as an absolute (single sided) value.
+ *
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_CODE_PHASE_UNCERTAINTY.
+ */
+ double code_phase_uncertainty_chips;
+
+ /**
+ * Carrier frequency at which codes and messages are modulated, it can be L1 or L2.
+ * If the field is not set, the carrier frequency is assumed to be L1.
+ *
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_CARRIER_FREQUENCY.
+ */
+ float carrier_frequency_hz;
+
+ /**
+ * The number of full carrier cycles between the satellite and the receiver.
+ * The reference frequency is given by the field 'carrier_frequency_hz'.
+ *
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_CARRIER_CYCLES.
+ */
+ int64_t carrier_cycles;
+
+ /**
+ * The RF phase detected by the receiver, in the range [0.0, 1.0].
+ * This is usually the fractional part of the complete carrier phase measurement.
+ *
+ * The reference frequency is given by the field 'carrier_frequency_hz'.
+ * The value contains the 'carrier-phase uncertainty' in it.
+ *
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_CARRIER_PHASE.
+ */
+ double carrier_phase;
+
+ /**
+ * 1-Sigma uncertainty of the carrier-phase.
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_CARRIER_PHASE_UNCERTAINTY.
+ */
+ double carrier_phase_uncertainty;
+
+ /**
+ * An enumeration that indicates the 'loss of lock' state of the event.
+ */
+ gps_loss_of_lock loss_of_lock;
+
+ /**
+ * The number of GPS bits transmitted since Sat-Sun midnight (GPS week).
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_BIT_NUMBER.
+ */
+ int32_t bit_number;
+
+ /**
+ * The elapsed time since the last received bit in milliseconds, in the range [0, 20]
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_TIME_FROM_LAST_BIT.
+ */
+ int16_t time_from_last_bit_ms;
+
+ /**
+ * Doppler shift in Hz.
+ * A positive value indicates that the SV is moving toward the receiver.
+ *
+ * The reference frequency is given by the field 'carrier_frequency_hz'.
+ * The value contains the 'doppler shift uncertainty' in it.
+ *
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_DOPPLER_SHIFT.
+ */
+ double doppler_shift_hz;
+
+ /**
+ * 1-Sigma uncertainty of the doppler shift in Hz.
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_DOPPLER_SHIFT_UNCERTAINTY.
+ */
+ double doppler_shift_uncertainty_hz;
+
+ /**
+ * An enumeration that indicates the 'multipath' state of the event.
+ */
+ gps_multipath_indicator multipath_indicator;
+
+ /**
+ * Signal-to-noise ratio in dB.
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_SNR.
+ */
+ double snr_db;
+
+ /**
+ * Elevation in degrees, the valid range is [-90, 90].
+ * The value contains the 'elevation uncertainty' in it.
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_ELEVATION.
+ */
+ double elevation_deg;
+
+ /**
+ * 1-Sigma uncertainty of the elevation in degrees, the valid range is [0, 90].
+ * The uncertainty is represented as the absolute (single sided) value.
+ *
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_ELEVATION_UNCERTAINTY.
+ */
+ double elevation_uncertainty_deg;
+
+ /**
+ * Azimuth in degrees, in the range [0, 360).
+ * The value contains the 'azimuth uncertainty' in it.
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_AZIMUTH.
+ * */
+ double azimuth_deg;
+
+ /**
+ * 1-Sigma uncertainty of the azimuth in degrees, the valid range is [0, 180].
+ * The uncertainty is represented as an absolute (single sided) value.
+ *
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_AZIMUTH_UNCERTAINTY.
+ */
+ double azimuth_uncertainty_deg;
+
+ /**
+ * Whether the GPS represented by the measurement was used for computing the most recent fix.
+ * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_USED_IN_FIX.
+ */
+ bool used_in_fix;
+} gps_measurement;
+
+/**
+ * Represents a GNSS Measurement, it contains raw and computed information.
+ *
+ * Independence - All signal measurement information (e.g. sv_time,
+ * pseudorange_rate, multipath_indicator) reported in this struct should be
+ * based on GNSS signal measurements only. You may not synthesize measurements
+ * by calculating or reporting expected measurements based on known or estimated
+ * position, velocity, or time.
+ */
+typedef struct {
+ /** A set of flags indicating the validity of the fields in this data structure. */
+ MTK_HAL_GnssMeasurementFlags flags;
+
+ /**
+ * Satellite vehicle ID number, as defined in GnssSvInfo::svid
+ * This is a mandatory value.
+ */
+ int16_t svid;
+
+ /**
+ * Defines the constellation of the given SV. Value should be one of those
+ * GNSS_CONSTELLATION_* constants
+ */
+ MTK_HAL_GnssConstellationType constellation;
+
+ /**
+ * Time offset at which the measurement was taken in nanoseconds.
+ * The reference receiver's time is specified by GpsData::clock::time_ns and should be
+ * interpreted in the same way as indicated by GpsClock::type.
+ *
+ * The sign of time_offset_ns is given by the following equation:
+ * measurement time = GpsClock::time_ns + time_offset_ns
+ *
+ * It provides an individual time-stamp for the measurement, and allows sub-nanosecond accuracy.
+ * This is a mandatory value.
+ */
+ double time_offset_ns;
+
+ /**
+ * Per satellite sync state. It represents the current sync state for the associated satellite.
+ * Based on the sync state, the 'received GPS tow' field should be interpreted accordingly.
+ *
+ * This is a mandatory value.
+ */
+ MTK_HAL_GnssMeasurementState state;
+
+ /**
+ * The received GNSS Time-of-Week at the measurement time, in nanoseconds.
+ * Ensure that this field is independent (see comment at top of
+ * GnssMeasurement struct.)
+ *
+ * For GPS & QZSS, this is:
+ * Received GPS Time-of-Week at the measurement time, in nanoseconds.
+ * The value is relative to the beginning of the current GPS week.
+ *
+ * Given the highest sync state that can be achieved, per each satellite, valid range
+ * for this field can be:
+ * Searching : [ 0 ] : GNSS_MEASUREMENT_STATE_UNKNOWN
+ * C/A code lock : [ 0 1ms ] : GNSS_MEASUREMENT_STATE_CODE_LOCK is set
+ * Bit sync : [ 0 20ms ] : GNSS_MEASUREMENT_STATE_BIT_SYNC is set
+ * Subframe sync : [ 0 6s ] : GNSS_MEASUREMENT_STATE_SUBFRAME_SYNC is set
+ * TOW decoded : [ 0 1week ] : GNSS_MEASUREMENT_STATE_TOW_DECODED is set
+ *
+ * Note well: if there is any ambiguity in integer millisecond,
+ * GNSS_MEASUREMENT_STATE_MSEC_AMBIGUOUS should be set accordingly, in the 'state' field.
+ *
+ * This value must be populated if 'state' != GNSS_MEASUREMENT_STATE_UNKNOWN.
+ *
+ * For Glonass, this is:
+ * Received Glonass time of day, at the measurement time in nanoseconds.
+ *
+ * Given the highest sync state that can be achieved, per each satellite, valid range for
+ * this field can be:
+ * Searching : [ 0 ] : GNSS_MEASUREMENT_STATE_UNKNOWN
+ * C/A code lock : [ 0 1ms ] : GNSS_MEASUREMENT_STATE_CODE_LOCK is set
+ * Symbol sync : [ 0 10ms ] : GNSS_MEASUREMENT_STATE_SYMBOL_SYNC is set
+ * Bit sync : [ 0 20ms ] : GNSS_MEASUREMENT_STATE_BIT_SYNC is set
+ * String sync : [ 0 2s ] : GNSS_MEASUREMENT_STATE_GLO_STRING_SYNC is set
+ * Time of day : [ 0 1day ] : GNSS_MEASUREMENT_STATE_GLO_TOD_DECODED is set
+ *
+ * For Beidou, this is:
+ * Received Beidou time of week, at the measurement time in nanoseconds.
+ *
+ * Given the highest sync state that can be achieved, per each satellite, valid range for
+ * this field can be:
+ * Searching : [ 0 ] : GNSS_MEASUREMENT_STATE_UNKNOWN
+ * C/A code lock: [ 0 1ms ] : GNSS_MEASUREMENT_STATE_CODE_LOCK is set
+ * Bit sync (D2): [ 0 2ms ] : GNSS_MEASUREMENT_STATE_BDS_D2_BIT_SYNC is set
+ * Bit sync (D1): [ 0 20ms ] : GNSS_MEASUREMENT_STATE_BIT_SYNC is set
+ * Subframe (D2): [ 0 0.6s ] : GNSS_MEASUREMENT_STATE_BDS_D2_SUBFRAME_SYNC is set
+ * Subframe (D1): [ 0 6s ] : GNSS_MEASUREMENT_STATE_SUBFRAME_SYNC is set
+ * Time of week : [ 0 1week ] : GNSS_MEASUREMENT_STATE_TOW_DECODED is set
+ *
+ * For Galileo, this is:
+ * Received Galileo time of week, at the measurement time in nanoseconds.
+ *
+ * E1BC code lock : [ 0 4ms ] : GNSS_MEASUREMENT_STATE_GAL_E1BC_CODE_LOCK is set
+ * E1C 2nd code lock: [ 0 100ms ] :
+ * GNSS_MEASUREMENT_STATE_GAL_E1C_2ND_CODE_LOCK is set
+ *
+ * E1B page : [ 0 2s ] : GNSS_MEASUREMENT_STATE_GAL_E1B_PAGE_SYNC is set
+ * Time of week: [ 0 1week ] : GNSS_MEASUREMENT_STATE_TOW_DECODED is set
+ *
+ * For SBAS, this is:
+ * Received SBAS time, at the measurement time in nanoseconds.
+ *
+ * Given the highest sync state that can be achieved, per each satellite,
+ * valid range for this field can be:
+ * Searching : [ 0 ] : GNSS_MEASUREMENT_STATE_UNKNOWN
+ * C/A code lock: [ 0 1ms ] : GNSS_MEASUREMENT_STATE_CODE_LOCK is set
+ * Symbol sync : [ 0 2ms ] : GNSS_MEASUREMENT_STATE_SYMBOL_SYNC is set
+ * Message : [ 0 1s ] : GNSS_MEASUREMENT_STATE_SBAS_SYNC is set
+ */
+ int64_t received_sv_time_in_ns;
+
+ /**
+ * 1-Sigma uncertainty of the Received GPS Time-of-Week in nanoseconds.
+ *
+ * This value must be populated if 'state' != GPS_MEASUREMENT_STATE_UNKNOWN.
+ */
+ int64_t received_sv_time_uncertainty_in_ns;
+
+ /**
+ * Carrier-to-noise density in dB-Hz, typically in the range [0, 63].
+ * It contains the measured C/N0 value for the signal at the antenna port.
+ *
+ * This is a mandatory value.
+ */
+ double c_n0_dbhz;
+
+ /**
+ * Pseudorange rate at the timestamp in m/s. The correction of a given
+ * Pseudorange Rate value includes corrections for receiver and satellite
+ * clock frequency errors. Ensure that this field is independent (see
+ * comment at top of GnssMeasurement struct.)
+ *
+ * It is mandatory to provide the 'uncorrected' 'pseudorange rate', and provide GpsClock's
+ * 'drift' field as well (When providing the uncorrected pseudorange rate, do not apply the
+ * corrections described above.)
+ *
+ * The value includes the 'pseudorange rate uncertainty' in it.
+ * A positive 'uncorrected' value indicates that the SV is moving away from the receiver.
+ *
+ * The sign of the 'uncorrected' 'pseudorange rate' and its relation to the sign of 'doppler
+ * shift' is given by the equation:
+ * pseudorange rate = -k * doppler shift (where k is a constant)
+ *
+ * This should be the most accurate pseudorange rate available, based on
+ * fresh signal measurements from this channel.
+ *
+ * It is mandatory that this value be provided at typical carrier phase PRR
+ * quality (few cm/sec per second of uncertainty, or better) - when signals
+ * are sufficiently strong & stable, e.g. signals from a GPS simulator at >=
+ * 35 dB-Hz.
+ */
+ double pseudorange_rate_mps;
+
+ /**
+ * 1-Sigma uncertainty of the pseudorange_rate_mps.
+ * The uncertainty is represented as an absolute (single sided) value.
+ *
+ * This is a mandatory value.
+ */
+ double pseudorange_rate_uncertainty_mps;
+
+ /**
+ * Accumulated delta range's state. It indicates whether ADR is reset or there is a cycle slip
+ * (indicating loss of lock).
+ *
+ * This is a mandatory value.
+ */
+ MTK_HAL_GnssAccumulatedDeltaRangeState accumulated_delta_range_state;
+
+ /**
+ * Accumulated delta range since the last channel reset in meters.
+ * A positive value indicates that the SV is moving away from the receiver.
+ *
+ * The sign of the 'accumulated delta range' and its relation to the sign of 'carrier phase'
+ * is given by the equation:
+ * accumulated delta range = -k * carrier phase (where k is a constant)
+ *
+ * This value must be populated if 'accumulated delta range state' != GPS_ADR_STATE_UNKNOWN.
+ * However, it is expected that the data is only accurate when:
+ * 'accumulated delta range state' == GPS_ADR_STATE_VALID.
+ */
+ double accumulated_delta_range_m;
+
+ /**
+ * 1-Sigma uncertainty of the accumulated delta range in meters.
+ * This value must be populated if 'accumulated delta range state' != GPS_ADR_STATE_UNKNOWN.
+ */
+ double accumulated_delta_range_uncertainty_m;
+
+ /**
+ * Carrier frequency at which codes and messages are modulated, it can be L1 or L2.
+ * If the field is not set, the carrier frequency is assumed to be L1.
+ *
+ * If the data is available, 'flags' must contain
+ * GNSS_MEASUREMENT_HAS_CARRIER_FREQUENCY.
+ */
+ float carrier_frequency_hz;
+
+ /**
+ * The number of full carrier cycles between the satellite and the receiver.
+ * The reference frequency is given by the field 'carrier_frequency_hz'.
+ * Indications of possible cycle slips and resets in the accumulation of
+ * this value can be inferred from the accumulated_delta_range_state flags.
+ *
+ * If the data is available, 'flags' must contain
+ * GNSS_MEASUREMENT_HAS_CARRIER_CYCLES.
+ */
+ int64_t carrier_cycles;
+
+ /**
+ * The RF phase detected by the receiver, in the range [0.0, 1.0].
+ * This is usually the fractional part of the complete carrier phase measurement.
+ *
+ * The reference frequency is given by the field 'carrier_frequency_hz'.
+ * The value contains the 'carrier-phase uncertainty' in it.
+ *
+ * If the data is available, 'flags' must contain
+ * GNSS_MEASUREMENT_HAS_CARRIER_PHASE.
+ */
+ double carrier_phase;
+
+ /**
+ * 1-Sigma uncertainty of the carrier-phase.
+ * If the data is available, 'flags' must contain
+ * GNSS_MEASUREMENT_HAS_CARRIER_PHASE_UNCERTAINTY.
+ */
+ double carrier_phase_uncertainty;
+
+ /**
+ * An enumeration that indicates the 'multipath' state of the event.
+ *
+ * The multipath Indicator is intended to report the presence of overlapping
+ * signals that manifest as distorted correlation peaks.
+ *
+ * - if there is a distorted correlation peak shape, report that multipath
+ * is GNSS_MULTIPATH_INDICATOR_PRESENT.
+ * - if there is not a distorted correlation peak shape, report
+ * GNSS_MULTIPATH_INDICATOR_NOT_PRESENT
+ * - if signals are too weak to discern this information, report
+ * GNSS_MULTIPATH_INDICATOR_UNKNOWN
+ *
+ * Example: when doing the standardized overlapping Multipath Performance
+ * test (3GPP TS 34.171) the Multipath indicator should report
+ * GNSS_MULTIPATH_INDICATOR_PRESENT for those signals that are tracked, and
+ * contain multipath, and GNSS_MULTIPATH_INDICATOR_NOT_PRESENT for those
+ * signals that are tracked and do not contain multipath.
+ */
+ MTK_HAL_GnssMultipathIndicator multipath_indicator;
+
+ /**
+ * Signal-to-noise ratio at correlator output in dB.
+ * If the data is available, 'flags' must contain GNSS_MEASUREMENT_HAS_SNR.
+ * This is the power ratio of the "correlation peak height above the
+ * observed noise floor" to "the noise RMS".
+ */
+ double snr_db;
+
+ /**
+ * Automatic gain control (AGC) level. AGC acts as a variable gain
+ * amplifier adjusting the power of the incoming signal. The AGC level
+ * may be used to indicate potential interference. When AGC is at a
+ * nominal level, this value must be set as 0. Higher gain (and/or lower
+ * input power) must be output as a positive number. Hence in cases of
+ * strong jamming, in the band of this signal, this value must go more
+ * negative.
+ */
+ double agc_level_db;
+} gnss_measurement;
+
+typedef struct {
+ /** Number of measurements. */
+ size_t measurement_count;
+
+ /** The array of measurements. */
+ gps_measurement measurements[GPS_MAX_MEASUREMENT];
+
+ /** The GPS clock time reading. */
+ gps_clock clock;
+} gps_data;
+
+/**
+ * Represents a reading of GNSS measurements. For devices where GnssSystemInfo's
+ * year_of_hw is set to 2016+, it is mandatory that these be provided, on
+ * request, when the GNSS receiver is searching/tracking signals.
+ *
+ * - Reporting of GPS constellation measurements is mandatory.
+ * - Reporting of all tracked constellations are encouraged.
+ */
+typedef struct {
+ /** Number of measurements. */
+ size_t measurement_count;
+
+ /** The array of measurements. */
+ gnss_measurement measurements[MTK_HAL_GNSS_MAX_MEASUREMENT];
+
+ /** The GPS clock time reading. */
+ gnss_clock clock;
+} gnss_data;
+
+typedef struct {
+ /**
+ * Pseudo-random number in the range of [1, 32]
+ * This is a Mandatory value.
+ */
+ int8_t prn;
+
+ /**
+ * The type of message contained in the structure.
+ * This is a Mandatory value.
+ */
+ gps_nav_msg_type type;
+
+ /**
+ * The status of the received navigation message.
+ * No need to send any navigation message that contains words with parity error and cannot be
+ * corrected.
+ */
+ nav_msg_status status;
+
+ /**
+ * Message identifier.
+ * It provides an index so the complete Navigation Message can be assembled. i.e. fo L1 C/A
+ * subframe 4 and 5, this value corresponds to the 'frame id' of the navigation message.
+ * Subframe 1, 2, 3 does not contain a 'frame id' and this value can be set to -1.
+ */
+ short message_id;
+
+ /**
+ * Sub-message identifier.
+ * If required by the message 'type', this value contains a sub-index within the current
+ * message (or frame) that is being transmitted.
+ * i.e. for L1 C/A the submessage id corresponds to the sub-frame id of the navigation message.
+ */
+ short submessage_id;
+
+ /**
+ * The length of the data (in bytes) contained in the current message.
+ * If this value is different from zero, 'data' must point to an array of the same size.
+ * e.g. for L1 C/A the size of the sub-frame will be 40 bytes (10 words, 30 bits/word).
+ * This is a Mandatory value.
+ */
+ size_t data_length;
+
+ /**
+ * The data of the reported GPS message.
+ * The bytes (or words) specified using big endian format (MSB first).
+ *
+ * For L1 C/A, each subframe contains 10 30-bit GPS words. Each GPS word (30 bits) should be
+ * fitted into the last 30 bits in a 4-byte word (skip B31 and B32), with MSB first.
+ */
+ char data[40];
+} gps_nav_msg;
+
+/** Represents a GPS navigation message (or a fragment of it). */
+typedef struct {
+ /** set to sizeof(GnssNavigationMessage) */
+ size_t size;
+
+ /**
+ * Satellite vehicle ID number, as defined in GnssSvInfo::svid
+ * This is a mandatory value.
+ */
+ int16_t svid;
+
+ /**
+ * The type of message contained in the structure.
+ * This is a mandatory value.
+ */
+ MTK_HAL_GnssNavigationMessageType type;
+
+ /**
+ * The status of the received navigation message.
+ * No need to send any navigation message that contains words with parity error and cannot be
+ * corrected.
+ */
+ MTK_HAL_NavigationMessageStatus status;
+
+ /**
+ * Message identifier. It provides an index so the complete Navigation
+ * Message can be assembled.
+ *
+ * - For GPS L1 C/A subframe 4 and 5, this value corresponds to the 'frame
+ * id' of the navigation message, in the range of 1-25 (Subframe 1, 2, 3
+ * does not contain a 'frame id' and this value can be set to -1.)
+ *
+ * - For Glonass L1 C/A, this refers to the frame ID, in the range of 1-5.
+ *
+ * - For BeiDou D1, this refers to the frame number in the range of 1-24
+ *
+ * - For Beidou D2, this refers to the frame number, in the range of 1-120
+ *
+ * - For Galileo F/NAV nominal frame structure, this refers to the subframe
+ * number, in the range of 1-12
+ *
+ * - For Galileo I/NAV nominal frame structure, this refers to the subframe
+ * number in the range of 1-24
+ */
+ int16_t message_id;
+
+ /**
+ * Sub-message identifier. If required by the message 'type', this value
+ * contains a sub-index within the current message (or frame) that is being
+ * transmitted.
+ *
+ * - For GPS L1 C/A, BeiDou D1 & BeiDou D2, the submessage id corresponds to
+ * the subframe number of the navigation message, in the range of 1-5.
+ *
+ * - For Glonass L1 C/A, this refers to the String number, in the range from
+ * 1-15
+ *
+ * - For Galileo F/NAV, this refers to the page type in the range 1-6
+ *
+ * - For Galileo I/NAV, this refers to the word type in the range 1-10+
+ */
+ int16_t submessage_id;
+
+ /**
+ * The length of the data (in bytes) contained in the current message.
+ * If this value is different from zero, 'data' must point to an array of the same size.
+ * e.g. for L1 C/A the size of the sub-frame will be 40 bytes (10 words, 30 bits/word).
+ *
+ * This is a mandatory value.
+ */
+ size_t data_length;
+
+ /**
+ * The data of the reported GPS message. The bytes (or words) specified
+ * using big endian format (MSB first).
+ *
+ * - For GPS L1 C/A, Beidou D1 & Beidou D2, each subframe contains 10 30-bit
+ * words. Each word (30 bits) should be fit into the last 30 bits in a
+ * 4-byte word (skip B31 and B32), with MSB first, for a total of 40
+ * bytes, covering a time period of 6, 6, and 0.6 seconds, respectively.
+ *
+ * - For Glonass L1 C/A, each string contains 85 data bits, including the
+ * checksum. These bits should be fit into 11 bytes, with MSB first (skip
+ * B86-B88), covering a time period of 2 seconds.
+ *
+ * - For Galileo F/NAV, each word consists of 238-bit (sync & tail symbols
+ * excluded). Each word should be fit into 30-bytes, with MSB first (skip
+ * B239, B240), covering a time period of 10 seconds.
+ *
+ * - For Galileo I/NAV, each page contains 2 page parts, even and odd, with
+ * a total of 2x114 = 228 bits, (sync & tail excluded) that should be fit
+ * into 29 bytes, with MSB first (skip B229-B232).
+ */
+ uint8_t* data;
+} gnss_nav_msg;
+
+#if 0
+void dump_gps_location(gps_location in);
+void dump_gnss_sv(gnss_sv in);
+void dump_gnss_sv_info(gnss_sv_info in);
+void dump_gps_data(gps_data in);
+void dump_gps_measurement(gps_measurement in);
+void dump_gps_clock(gps_clock in);
+void dump_gps_nav_msg(gps_nav_msg in);
+void dump_gnss_data(gnss_data in);
+void dump_gnss_measurement(gnss_measurement in);
+void dump_gnss_clock(gnss_clock in);
+void dump_gnss_nav_msg(gnss_nav_msg in);
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/src/connectivity/gps/gps_hal/inc/hardware/gps_mtk.h b/src/connectivity/gps/gps_hal/inc/hardware/gps_mtk.h
new file mode 100644
index 0000000..df13674
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/inc/hardware/gps_mtk.h
@@ -0,0 +1,698 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_INCLUDE_HARDWARE_GPS_MTK_H
+#define ANDROID_INCLUDE_HARDWARE_GPS_MTK_H
+
+#if defined (__ANDROID_OS__)
+#include <hardware/gps_internal.h>
+#elif defined (__LINUX_OS__)
+#include "gps_internal.h"
+#endif
+
+__BEGIN_DECLS
+
+// MTK extended GpsAidingData values.
+#define GPS_DELETE_HOT_STILL 0x2000
+#define GPS_DELETE_EPO 0x4000
+
+// ====================vzw debug screen API =================
+/**
+ * Name for the VZW debug interface.
+ */
+#define VZW_DEBUG_INTERFACE "vzw-debug"
+
+#define VZW_DEBUG_STRING_MAXLEN 200
+
+/** Represents data of VzwDebugData. */
+typedef struct {
+ /** set to sizeof(VzwDebugData) */
+ size_t size;
+
+ char vzw_msg_data[VZW_DEBUG_STRING_MAXLEN];
+} VzwDebugData;
+
+
+typedef void (* vzw_debug_callback)(VzwDebugData* vzw_message);
+
+/** Callback structure for the Vzw debug interface. */
+typedef struct {
+ vzw_debug_callback vzw_debug_cb;
+} VzwDebugCallbacks;
+
+
+/** Extended interface for VZW DEBUG support. */
+typedef struct {
+ /** set to sizeof(VzwDebugInterface) */
+ size_t size;
+
+ /** Registers the callbacks for Vzw debug message. */
+ int (*init)( VzwDebugCallbacks* callbacks );
+
+ /** Set Vzw debug screen enable/disable **/
+ void (*set_vzw_debug_screen)(bool enabled);
+} VzwDebugInterface;
+
+////////////////////// GNSS HIDL v1.0 ////////////////////////////
+
+/** Represents a location. */
+typedef struct {
+ GpsLocation legacyLocation;
+ /**
+ * Represents expected horizontal position accuracy, radial, in meters
+ * (68% confidence).
+ */
+ float horizontalAccuracyMeters;
+
+ /**
+ * Represents expected vertical position accuracy in meters
+ * (68% confidence).
+ */
+ float verticalAccuracyMeters;
+
+ /**
+ * Represents expected speed accuracy in meter per seconds
+ * (68% confidence).
+ */
+ float speedAccuracyMetersPerSecond;
+
+ /**
+ * Represents expected bearing accuracy in degrees
+ * (68% confidence).
+ */
+ float bearingAccuracyDegrees;
+
+} GpsLocation_ext;
+
+
+typedef struct {
+ GnssSvInfo legacySvInfo;
+
+ /// v1.0 ///
+ float carrier_frequency;
+
+} GnssSvInfo_ext;
+
+/**
+ * Represents SV status.
+ */
+typedef struct {
+ /** set to sizeof(GnssSvStatus) */
+ size_t size;
+
+ /** Number of GPS SVs currently visible, refers to the SVs stored in sv_list */
+ int num_svs;
+ /**
+ * Pointer to an array of SVs information for all GNSS constellations,
+ * except GPS, which is reported using sv_list
+ */
+ GnssSvInfo_ext gnss_sv_list[GNSS_MAX_SVS];
+
+} GnssSvStatus_ext;
+
+/**
+ * Callback with location information. Can only be called from a thread created
+ * by create_thread_cb.
+ */
+typedef void (* gps_location_ext_callback)(GpsLocation_ext* location);
+
+/**
+ * Callback with SV status information.
+ * Can only be called from a thread created by create_thread_cb.
+ */
+typedef void (* gnss_sv_status_ext_callback)(GnssSvStatus_ext* sv_info);
+
+/**
+ * The callback associated with the geofence.
+ * Parameters:
+ * geofence_id - The id associated with the add_geofence_area.
+ * location - The current GPS location.
+ * transition - Can be one of GPS_GEOFENCE_ENTERED, GPS_GEOFENCE_EXITED,
+ * GPS_GEOFENCE_UNCERTAIN.
+ * timestamp - Timestamp when the transition was detected.
+ *
+ * The callback should only be called when the caller is interested in that
+ * particular transition. For instance, if the caller is interested only in
+ * ENTERED transition, then the callback should NOT be called with the EXITED
+ * transition.
+ *
+ * IMPORTANT: If a transition is triggered resulting in this callback, the GPS
+ * subsystem will wake up the application processor, if its in suspend state.
+ */
+typedef void (*gps_geofence_transition_ext_callback) (int32_t geofence_id,
+ GpsLocation_ext* location, int32_t transition, GpsUtcTime timestamp);
+
+/**
+ * The callback associated with the availability of the GPS system for geofencing
+ * monitoring. If the GPS system determines that it cannot monitor geofences
+ * because of lack of reliability or unavailability of the GPS signals, it will
+ * call this callback with GPS_GEOFENCE_UNAVAILABLE parameter.
+ *
+ * Parameters:
+ * status - GPS_GEOFENCE_UNAVAILABLE or GPS_GEOFENCE_AVAILABLE.
+ * last_location - Last known location.
+ */
+typedef void (*gps_geofence_status_ext_callback) (int32_t status,
+ GpsLocation_ext* last_location);
+
+typedef struct {
+ gps_geofence_transition_ext_callback geofence_transition_callback;
+ gps_geofence_status_ext_callback geofence_status_callback;
+ gps_geofence_add_callback geofence_add_callback;
+ gps_geofence_remove_callback geofence_remove_callback;
+ gps_geofence_pause_callback geofence_pause_callback;
+ gps_geofence_resume_callback geofence_resume_callback;
+ gps_create_thread create_thread_cb;
+} GpsGeofenceCallbacks_ext;
+
+/** Extended interface for GPS_Geofencing support */
+typedef struct {
+ /** set to sizeof(GpsGeofencingInterface) */
+ size_t size;
+
+ /**
+ * Opens the geofence interface and provides the callback routines
+ * to the implementation of this interface.
+ */
+ void (*init)( GpsGeofenceCallbacks_ext* callbacks );
+
+ /**
+ * Add a geofence area. This api currently supports circular geofences.
+ * Parameters:
+ * geofence_id - The id for the geofence. If a geofence with this id
+ * already exists, an error value (GPS_GEOFENCE_ERROR_ID_EXISTS)
+ * should be returned.
+ * latitude, longtitude, radius_meters - The lat, long and radius
+ * (in meters) for the geofence
+ * last_transition - The current state of the geofence. For example, if
+ * the system already knows that the user is inside the geofence,
+ * this will be set to GPS_GEOFENCE_ENTERED. In most cases, it
+ * will be GPS_GEOFENCE_UNCERTAIN.
+ * monitor_transition - Which transitions to monitor. Bitwise OR of
+ * GPS_GEOFENCE_ENTERED, GPS_GEOFENCE_EXITED and
+ * GPS_GEOFENCE_UNCERTAIN.
+ * notification_responsiveness_ms - Defines the best-effort description
+ * of how soon should the callback be called when the transition
+ * associated with the Geofence is triggered. For instance, if set
+ * to 1000 millseconds with GPS_GEOFENCE_ENTERED, the callback
+ * should be called 1000 milliseconds within entering the geofence.
+ * This parameter is defined in milliseconds.
+ * NOTE: This is not to be confused with the rate that the GPS is
+ * polled at. It is acceptable to dynamically vary the rate of
+ * sampling the GPS for power-saving reasons; thus the rate of
+ * sampling may be faster or slower than this.
+ * unknown_timer_ms - The time limit after which the UNCERTAIN transition
+ * should be triggered. This parameter is defined in milliseconds.
+ * See above for a detailed explanation.
+ */
+ void (*add_geofence_area) (int32_t geofence_id, double latitude, double longitude,
+ double radius_meters, int last_transition, int monitor_transitions,
+ int notification_responsiveness_ms, int unknown_timer_ms);
+
+ /**
+ * Pause monitoring a particular geofence.
+ * Parameters:
+ * geofence_id - The id for the geofence.
+ */
+ void (*pause_geofence) (int32_t geofence_id);
+
+ /**
+ * Resume monitoring a particular geofence.
+ * Parameters:
+ * geofence_id - The id for the geofence.
+ * monitor_transitions - Which transitions to monitor. Bitwise OR of
+ * GPS_GEOFENCE_ENTERED, GPS_GEOFENCE_EXITED and
+ * GPS_GEOFENCE_UNCERTAIN.
+ * This supersedes the value associated provided in the
+ * add_geofence_area call.
+ */
+ void (*resume_geofence) (int32_t geofence_id, int monitor_transitions);
+
+ /**
+ * Remove a geofence area. After the function returns, no notifications
+ * should be sent.
+ * Parameter:
+ * geofence_id - The id for the geofence.
+ */
+ void (*remove_geofence_area) (int32_t geofence_id);
+} GpsGeofencingInterface_ext;
+
+typedef struct {
+ GnssMeasurement legacyMeasurement;
+
+ /**
+ * Automatic gain control (AGC) level. AGC acts as a variable gain
+ * amplifier adjusting the power of the incoming signal. The AGC level
+ * may be used to indicate potential interference. When AGC is at a
+ * nominal level, this value must be set as 0. Higher gain (and/or lower
+ * input power) must be output as a positive number. Hence in cases of
+ * strong jamming, in the band of this signal, this value must go more
+ * negative.
+ *
+ * Note: Different hardware designs (e.g. antenna, pre-amplification, or
+ * other RF HW components) may also affect the typical output of of this
+ * value on any given hardware design in an open sky test - the
+ * important aspect of this output is that changes in this value are
+ * indicative of changes on input signal power in the frequency band for
+ * this measurement.
+ */
+ double agc_level_db;
+} GnssMeasurement_ext;
+
+/**
+ * Represents a reading of GNSS measurements. For devices where GnssSystemInfo's
+ * year_of_hw is set to 2016+, it is mandatory that these be provided, on
+ * request, when the GNSS receiver is searching/tracking signals.
+ *
+ * - Reporting of GPS constellation measurements is mandatory.
+ * - Reporting of all tracked constellations are encouraged.
+ */
+typedef struct {
+ /** set to sizeof(GnssData) */
+ size_t size;
+
+ /** Number of measurements. */
+ size_t measurement_count;
+
+ /** The array of measurements. */
+ GnssMeasurement_ext measurements[GNSS_MAX_MEASUREMENT];
+
+ /** The GPS clock time reading. */
+ GnssClock clock;
+} GnssData_ext;
+
+/**
+ * The callback for to report measurements from the HAL.
+ *
+ * Parameters:
+ * data - A data structure containing the measurements.
+ */
+typedef void (*gnss_measurement_ext_callback) (GnssData_ext* data);
+
+typedef struct {
+ /** set to sizeof(GpsMeasurementCallbacks) */
+ size_t size;
+ gps_measurement_callback measurement_callback;
+ gnss_measurement_ext_callback gnss_measurement_callback;
+} GpsMeasurementCallbacks_ext;
+
+
+/////// Gnss debug ////
+
+/** Milliseconds since January 1, 1970 */
+typedef int64_t GnssUtcTime;
+
+typedef enum {
+ /** Ephemeris is known for this satellite. */
+ EPHEMERIS,
+ /**
+ * Ephemeris is not known, but Almanac (approximate location) is known.
+ */
+ ALMANAC_ONLY,
+ /**
+ * Both ephemeris & almanac are not known (e.g. during a cold start
+ * blind search.)
+ */
+ NOT_AVAILABLE
+} SatelliteEphemerisType;
+
+typedef enum {
+ /**
+ * The ephemeris (or almanac only) information was demodulated from the
+ * signal received on the device
+ */
+ DEMODULATED,
+ /**
+ * The ephemeris (or almanac only) information was received from a SUPL
+ * server.
+ */
+ SUPL_PROVIDED,
+ /**
+ * The ephemeris (or almanac only) information was provided by another
+ * server.
+ */
+ OTHER_SERVER_PROVIDED,
+ /**
+ * The ephemeris (or almanac only) information was provided by another
+ * method, e.g. injected via a local debug tool, from build defaults
+ * (e.g. almanac), or is from a satellite
+ * with SatelliteEphemerisType::NOT_AVAILABLE.
+ */
+ OTHER
+} SatelliteEphemerisSource;
+
+typedef enum {
+ /** The ephemeris is known good. */
+ GOOD,
+ /** The ephemeris is known bad. */
+ BAD,
+ /** The ephemeris is unknown to be good or bad. */
+ UNKNOWN
+} SatelliteEphemerisHealth;
+
+/**
+ * Provides the current best known position from any
+ * source (GNSS or injected assistance).
+ */
+typedef struct {
+ /**
+ * Validity of the data in this struct. False only if no
+ * latitude/longitude information is known.
+ */
+ bool valid;
+ /** Latitude expressed in degrees */
+ double latitudeDegrees;
+ /** Longitude expressed in degrees */
+ double longitudeDegrees;
+ /** Altitude above ellipsoid expressed in meters */
+ float altitudeMeters;
+ /** Represents horizontal speed in meters per second. */
+ float speedMetersPerSec;
+ /** Represents heading in degrees. */
+ float bearingDegrees;
+ /**
+ * Estimated horizontal accuracy of position expressed in meters,
+ * radial, 68% confidence.
+ */
+ double horizontalAccuracyMeters;
+ /**
+ * Estimated vertical accuracy of position expressed in meters, with
+ * 68% confidence.
+ */
+ double verticalAccuracyMeters;
+ /**
+ * Estimated speed accuracy in meters per second with 68% confidence.
+ */
+ double speedAccuracyMetersPerSecond;
+ /**
+ * estimated bearing accuracy degrees with 68% confidence.
+ */
+ double bearingAccuracyDegrees;
+ /**
+ * Time duration before this report that this position information was
+ * valid. This can, for example, be a previous injected location with
+ * an age potentially thousands of seconds old, or
+ * extrapolated to the current time (with appropriately increased
+ * accuracy estimates), with a (near) zero age.
+ */
+ float ageSeconds;
+} PositionDebug;
+
+/**
+ * Provides the current best known UTC time estimate.
+ * If no fresh information is available, e.g. after a delete all,
+ * then whatever the effective defaults are on the device must be
+ * provided (e.g. Jan. 1, 2017, with an uncertainty of 5 years) expressed
+ * in the specified units.
+ */
+typedef struct {
+ /** UTC time estimate. */
+ GnssUtcTime timeEstimate;
+ /** 68% error estimate in time. */
+ float timeUncertaintyNs;
+ /**
+ * 68% error estimate in local clock drift,
+ * in nanoseconds per second (also known as parts per billion - ppb.)
+ */
+ float frequencyUncertaintyNsPerSec;
+} TimeDebug;
+
+/**
+ * Provides a single satellite info that has decoded navigation data.
+ */
+typedef struct {
+ /** Satellite vehicle ID number */
+ int16_t svid;
+ /** Defines the constellation type of the given SV. */
+ GnssConstellationType constellation;
+
+ /**
+ * Defines the standard broadcast ephemeris or almanac availability for
+ * the satellite. To report status of predicted orbit and clock
+ * information, see the serverPrediction fields below.
+ */
+ SatelliteEphemerisType ephemerisType;
+ /** Defines the ephemeris source of the satellite. */
+ SatelliteEphemerisSource ephemerisSource;
+ /**
+ * Defines whether the satellite is known healthy
+ * (safe for use in location calculation.)
+ */
+ SatelliteEphemerisHealth ephemerisHealth;
+ /**
+ * Time duration from this report (current time), minus the
+ * effective time of the ephemeris source (e.g. TOE, TOA.)
+ * Set to 0 when ephemerisType is NOT_AVAILABLE.
+ */
+ float ephemerisAgeSeconds;
+
+ /**
+ * True if a server has provided a predicted orbit and clock model for
+ * this satellite.
+ */
+ bool serverPredictionIsAvailable;
+ /**
+ * Time duration from this report (current time) minus the time of the
+ * start of the server predicted information. For example, a 1 day
+ * old prediction would be reported as 86400 seconds here.
+ */
+ float serverPredictionAgeSeconds;
+} SatelliteData;
+
+/**
+ * Provides a set of debug information that is filled by the GNSS chipset
+ * when the method getDebugData() is invoked.
+ */
+typedef struct {
+ /** Current best known position. */
+ PositionDebug position;
+ /** Current best know time estimate */
+ TimeDebug time;
+ /**
+ * Provides a list of the available satellite data, for all
+ * satellites and constellations the device can track,
+ * including GnssConstellationType UNKNOWN.
+ */
+ SatelliteData satelliteDataArray[GNSS_MAX_SVS];
+} DebugData;
+
+
+/** Extended interface for DEBUG support. */
+typedef struct {
+ /** set to sizeof(GpsDebugInterface) */
+ size_t size;
+
+ /**
+ * This function should return any information that the native
+ * implementation wishes to include in a bugreport.
+ */
+ // size_t (*get_internal_state)(char* buffer, size_t bufferSize);
+ /// v1.0 ///
+ bool (*get_internal_state)(DebugData* debugData);
+} GpsDebugInterface_ext;
+
+
+////////////////////// GNSS HIDL v1.1 ////////////////////////////
+
+/**
+ * Callback for reporting driver name information.
+ */
+typedef void (* gnss_set_name_callback)(const char* name, int length);
+
+/**
+ * Callback for requesting framework NLP or Fused location injection.
+ */
+typedef void (* gnss_request_location_callback)(bool independentFromGnss);
+
+/** New GPS callback structure. */
+typedef struct {
+ /** set to sizeof(GpsCallbacks) */
+ size_t size;
+ gps_location_ext_callback location_cb;
+ gps_status_callback status_cb;
+ gps_sv_status_callback sv_status_cb;
+ gps_nmea_callback nmea_cb;
+ gps_set_capabilities set_capabilities_cb;
+ gps_acquire_wakelock acquire_wakelock_cb;
+ gps_release_wakelock release_wakelock_cb;
+ gps_create_thread create_thread_cb;
+ gps_request_utc_time request_utc_time_cb;
+
+ gnss_set_system_info set_system_info_cb;
+ gnss_sv_status_ext_callback gnss_sv_status_cb;
+
+ /////v1.1////
+ gnss_set_name_callback set_name_cb;
+ gnss_request_location_callback request_location_cb;
+} GpsCallbacks_ext;
+
+
+/** Represents the standard GPS interface. */
+typedef struct {
+ /** set to sizeof(GpsInterface) */
+ size_t size;
+ /**
+ * Opens the interface and provides the callback routines
+ * to the implementation of this interface.
+ */
+ /// v1.0 ///
+// int (*init)( GpsCallbacks* callbacks );
+ /// v1.1 ///
+ int (*init)( GpsCallbacks_ext* callbacks );
+
+ /** Starts navigating. */
+ int (*start)( void );
+
+ /** Stops navigating. */
+ int (*stop)( void );
+
+ /** Closes the interface. */
+ void (*cleanup)( void );
+
+ /** Injects the current time. */
+ int (*inject_time)(GpsUtcTime time, int64_t timeReference,
+ int uncertainty);
+
+ /**
+ * Injects current location from another location provider (typically cell
+ * ID). Latitude and longitude are measured in degrees expected accuracy is
+ * measured in meters
+ */
+ int (*inject_location)(double latitude, double longitude, float accuracy);
+
+ /**
+ * Specifies that the next call to start will not use the
+ * information defined in the flags. GPS_DELETE_ALL is passed for
+ * a cold start.
+ */
+ void (*delete_aiding_data)(GpsAidingData flags);
+
+ /**
+ * min_interval represents the time between fixes in milliseconds.
+ * preferred_accuracy represents the requested fix accuracy in meters.
+ * preferred_time represents the requested time to first fix in milliseconds.
+ *
+ * 'mode' parameter should be one of GPS_POSITION_MODE_MS_BASED
+ * or GPS_POSITION_MODE_STANDALONE.
+ * It is allowed by the platform (and it is recommended) to fallback to
+ * GPS_POSITION_MODE_MS_BASED if GPS_POSITION_MODE_MS_ASSISTED is passed in, and
+ * GPS_POSITION_MODE_MS_BASED is supported.
+ */
+ /// v1.0 ///
+// int (*set_position_mode)(GpsPositionMode mode, GpsPositionRecurrence recurrence,
+// uint32_t min_interval, uint32_t preferred_accuracy, uint32_t preferred_time);
+ /// v1.1 ///
+ int (*set_position_mode)(GpsPositionMode mode, GpsPositionRecurrence recurrence,
+ uint32_t min_interval, uint32_t preferred_accuracy, uint32_t preferred_time,
+ bool lowPowerMode);
+
+
+ /** Get a pointer to extension information. */
+ const void* (*get_extension)(const char* name);
+
+ /// v1.1 ///
+ int (*inject_fused_location)(double latitude, double longitude, float accuracy);
+
+} GpsInterface_ext;
+
+
+/**
+ * Extended interface for GPS Measurements support.
+ */
+typedef struct {
+ /** Set to sizeof(GpsMeasurementInterface_ext) */
+ size_t size;
+
+ /**
+ * Initializes the interface and registers the callback routines with the HAL.
+ * After a successful call to 'init' the HAL must begin to provide updates at its own phase.
+ *
+ * Status:
+ * GPS_MEASUREMENT_OPERATION_SUCCESS
+ * GPS_MEASUREMENT_ERROR_ALREADY_INIT - if a callback has already been registered without a
+ * corresponding call to 'close'
+ * GPS_MEASUREMENT_ERROR_GENERIC - if any other error occurred, it is expected that the HAL
+ * will not generate any updates upon returning this error code.
+ */
+ /// v1.0 ///
+// int (*init) (GpsMeasurementCallbacks* callbacks);
+ /// v1.1 ///
+ int (*init) (GpsMeasurementCallbacks_ext* callbacks, bool enableFullTracking);
+
+ /**
+ * Stops updates from the HAL, and unregisters the callback routines.
+ * After a call to stop, the previously registered callbacks must be considered invalid by the
+ * HAL.
+ * If stop is invoked without a previous 'init', this function should perform no work.
+ */
+ void (*close) ();
+
+} GpsMeasurementInterface_ext;
+
+
+/**
+ * Interface for passing GNSS configuration contents from platform to HAL.
+ */
+typedef struct {
+ /** Set to sizeof(GnssConfigurationInterface) */
+ size_t size;
+
+ /**
+ * Deliver GNSS configuration contents to HAL.
+ * Parameters:
+ * config_data - a pointer to a char array which holds what usually is expected from
+ file(/etc/gps.conf), i.e., a sequence of UTF8 strings separated by '\n'.
+ * length - total number of UTF8 characters in configuraiton data.
+ *
+ * IMPORTANT:
+ * GPS HAL should expect this function can be called multiple times. And it may be
+ * called even when GpsLocationProvider is already constructed and enabled. GPS HAL
+ * should maintain the existing requests for various callback regardless the change
+ * in configuration data.
+ */
+ void (*configuration_update) (const char* config_data, int32_t length);
+
+ //// v1.1 ////
+ void (*setBlacklist) (long long* blacklist, int32_t size);
+} GnssConfigurationInterface_ext;
+
+
+#if defined (__ANDROID_OS__)
+struct gps_device_t_ext {
+ struct hw_device_t common;
+
+ /**
+ * Set the provided lights to the provided values.
+ *
+ * Returns: 0 on succes, error code on failure.
+ */
+ const GpsInterface_ext* (*get_gps_interface)(struct gps_device_t_ext* dev);
+};
+#elif defined (__LINUX_OS__)
+struct gps_device_t_ext {
+ /**
+ * Set the provided lights to the provided values.
+ *
+ * Returns: 0 on succes, error code on failure.
+ */
+ const GpsInterface_ext* (*get_gps_interface)(struct gps_device_t_ext* dev);
+};
+#endif
+
+__END_DECLS
+
+#endif /* ANDROID_INCLUDE_HARDWARE_GPS_MTK_H */
+
diff --git a/src/connectivity/gps/gps_hal/inc/mtk_auto_log.h b/src/connectivity/gps/gps_hal/inc/mtk_auto_log.h
new file mode 100644
index 0000000..edf1775
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/inc/mtk_auto_log.h
@@ -0,0 +1,186 @@
+/*
+* Copyright Statement:
+*
+* This software/firmware and related documentation ("MediaTek Software") are
+* protected under relevant copyright laws. The information contained herein is
+* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
+* the prior written permission of MediaTek inc. and/or its licensors, any
+* reproduction, modification, use or disclosure of MediaTek Software, and
+* information contained herein, in whole or in part, shall be strictly
+* prohibited.
+*
+* MediaTek Inc. (C) 2017. All rights reserved.
+*
+* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
+* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
+* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
+* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
+* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
+* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
+* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
+* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
+* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
+* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
+* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
+* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
+* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
+* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
+* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
+* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
+* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
+*/
+#ifndef MTK_AUTO_LOG_H
+#define MTK_AUTO_LOG_H
+
+/**
+ * @enum LOG_LEVEL
+ * @brief Define Log Level
+ */
+typedef enum {
+ L_VERBOSE = 0, L_DEBUG, L_INFO, L_WARN, L_ERROR, L_ASSERT, L_SUPPRESS
+} LOG_LEVEL;
+
+#ifndef UNUSED
+#define UNUSED(x) (x)=(x)
+#endif
+
+#ifdef LOGD
+#undef LOGD
+#endif
+#ifdef LOGW
+#undef LOGW
+#endif
+#ifdef LOGE
+#undef LOGE
+#endif
+
+#ifndef LOG_TAG
+#undef LOG_TAG
+#define LOG_TAG "gnss_hal"
+#endif
+
+#include <string.h>
+
+int set_log_level(int *dst_level, int src_level);
+
+extern int log_dbg_level;
+#define LOG_IS_ENABLED(level) (log_dbg_level <= level)
+
+#define FILE_NAME(x) strrchr(x, '/')?strrchr(x, '/') + 1 : x
+
+#if defined(__ANDROID_OS__)
+
+#define ANDROID_MNLD_PROP_SUPPORT 1
+
+#include <cutils/sockets.h>
+#include <log/log.h> /*logging in logcat*/
+#include <cutils/android_filesystem_config.h>
+#include <cutils/properties.h>
+
+#define PRINT_LOG(loglevel, fmt, args...) \
+ do {\
+ if (LOG_IS_ENABLED(loglevel)) {\
+ switch (loglevel){\
+ case L_ASSERT:\
+ {\
+ ALOG_ASSERT("%s %s %d " fmt, FILE_NAME(__FILE__), __FUNCTION__, __LINE__, ##args);\
+ break;\
+ }\
+ case L_ERROR:\
+ {\
+ ALOGE("%s %s %d " fmt, FILE_NAME(__FILE__), __FUNCTION__, __LINE__, ##args);\
+ break;\
+ }\
+ case L_WARN:\
+ {\
+ ALOGW("%s %s %d " fmt, FILE_NAME(__FILE__), __FUNCTION__, __LINE__, ##args);\
+ break;\
+ }\
+ case L_INFO:\
+ {\
+ ALOGI("%s %s %d " fmt, FILE_NAME(__FILE__), __FUNCTION__, __LINE__, ##args);\
+ break;\
+ }\
+ case L_DEBUG:\
+ {\
+ ALOGD("%s %s %d " fmt, FILE_NAME(__FILE__), __FUNCTION__, __LINE__, ##args);\
+ break;\
+ }\
+ case L_VERBOSE:\
+ {\
+ ALOGV("%s %s %d " fmt, FILE_NAME(__FILE__), __FUNCTION__, __LINE__, ##args);\
+ break;\
+ }\
+ }\
+ }\
+ } while (0)
+
+#define LOGA(fmt, args...) PRINT_LOG(L_ASSERT, fmt, ##args)
+#define LOGE(fmt, args...) PRINT_LOG(L_ERROR, fmt, ##args)
+#define LOGW(fmt, args...) PRINT_LOG(L_WARN, fmt, ##args)
+#define LOGI(fmt, args...) PRINT_LOG(L_INFO, fmt, ##args)
+#define LOGD(fmt, args...) PRINT_LOG(L_DEBUG, fmt, ##args)
+#define LOGV(fmt, args...) PRINT_LOG(L_VERBOSE, fmt, ##args)
+
+#define TRC(f) ALOGD("%s", __func__)
+
+#elif defined(__LINUX_OS__)
+
+#include <stdio.h>
+#define ANDROID_MNLD_PROP_SUPPORT 0
+
+
+char time_buff[64];
+int get_time_str(char* buf, int len);
+
+#ifndef gettid
+#include <unistd.h>
+#include <sys/syscall.h>
+#define gettid() syscall(__NR_gettid)
+#define getpid() syscall(__NR_getpid)
+#endif
+
+#define PRINT_LOG(loglevel, tag, fmt, args...) \
+ do {\
+ if (LOG_IS_ENABLED(loglevel)) {\
+ get_time_str(time_buff, sizeof(time_buff));\
+ printf("%ld %ld [%s]" LOG_TAG tag "%s %s %d " fmt "\n",\
+ getpid(), gettid(),time_buff, FILE_NAME(__FILE__), __FUNCTION__, __LINE__, ##args);\
+ fflush(stdout);\
+ }\
+ } while (0)
+
+#define LOGA(fmt, args...) PRINT_LOG(L_ASSERT, "[ASSERT]: ", fmt, ##args)
+#define LOGE(fmt, args...) PRINT_LOG(L_ERROR, "[ERROR]: ", fmt, ##args)
+#define LOGW(fmt, args...) PRINT_LOG(L_WARN, "[WARNING]: ", fmt, ##args)
+#define LOGI(fmt, args...) PRINT_LOG(L_INFO, "[INFO]: ", fmt, ##args)
+#define LOGD(fmt, args...) PRINT_LOG(L_DEBUG, "[DEBUG]: ", fmt, ##args)
+#define LOGV(fmt, args...) PRINT_LOG(L_VERBOSE, "[VERBOSE]: ", fmt, ##args)
+
+#define TRC(f) ((void)0)
+
+#elif defined(__TIZEN_OS__)
+
+#include <dlog/dlog.h>
+
+#define PRINT_LOG(loglevel, tag, fmt, args...) \
+ do {\
+ if (LOG_IS_ENABLED(loglevel)) {\
+ dlog_print(DLOG_DEBUG, fmt "\n", ##args);\
+ printf(fmt "\n", ##args);
+ fflush(stdout);\
+ }\
+ } while (0)
+
+#define LOGA(fmt, args...) PRINT_LOG(L_ASSERT, "[ASSERT]: ", fmt, ##args)
+#define LOGE(fmt, args...) PRINT_LOG(L_ERROR, "[ERROR]: ", fmt, ##args)
+#define LOGW(fmt, args...) PRINT_LOG(L_WARN, "[WARNING]: ", fmt, ##args)
+#define LOGI(fmt, args...) PRINT_LOG(L_INFO, "[INFO]: ", fmt, ##args)
+#define LOGD(fmt, args...) PRINT_LOG(L_DEBUG, "[DEBUG]: ", fmt, ##args)
+#define LOGV(fmt, args...) PRINT_LOG(L_VERBOSE, "[VERBOSE]: ", fmt, ##args)
+
+#endif
+
+#endif
diff --git a/src/connectivity/gps/gps_hal/inc/mtk_lbs_utility.h b/src/connectivity/gps/gps_hal/inc/mtk_lbs_utility.h
new file mode 100644
index 0000000..3d8fafd
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/inc/mtk_lbs_utility.h
@@ -0,0 +1,87 @@
+#ifndef __MTK_LBS_UTILITY_H__
+#define __MTK_LBS_UTILITY_H__
+
+#include <time.h>
+#include <stdint.h>
+//#include "mtk_auto_log.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*************************************************
+* Basic Utilities
+**************************************************/
+#define MTK_GPS_NVRAM 0
+
+#if defined(__ANDROID_OS__)
+#define ANDROID_MNLD_PROP_SUPPORT 1
+#elif defined(__LINUX_OS__)
+#define ANDROID_MNLD_PROP_SUPPORT 0
+#endif
+
+void msleep(int interval);
+
+#define MNLD_STRNCPY(dst,src,size) do{\
+ strncpy((char *)(dst), (src), (size - 1));\
+ (dst)[size - 1] = '\0';\
+ }while(0)
+
+/*************************************************
+* Timer
+**************************************************/
+typedef void (* timer_callback)();
+
+
+// in millisecond
+time_t get_tick();
+
+// in millisecond
+time_t get_time_in_millisecond();
+
+/*************************************************
+* Epoll
+**************************************************/
+// -1 means failure
+int epoll_add_fd(int epfd, int fd);
+
+// -1 failed
+int epoll_add_fd2(int epfd, int fd, uint32_t events);
+
+// -1 failed
+int epoll_del_fd(int epfd, int fd);
+
+int epoll_mod_fd(int epfd, int fd, uint32_t events);
+
+/*************************************************
+* Local UDP Socket
+**************************************************/
+// -1 means failure
+int socket_bind_udp(const char* path);
+
+// -1 means failure
+int socket_set_blocking(int fd, int blocking);
+
+// -1 means failure
+int safe_sendto(const char* path, const char* buff, int len);
+
+// -1 means failure
+int safe_recvfrom(int fd, char* buff, int len);
+
+// -1 means failure
+int start_timer(timer_t timerid, int milliseconds);
+
+// -1 means failure
+int stop_timer(timer_t timerid);
+
+// -1 means failure
+timer_t init_timer(timer_callback cb);
+
+// -1 means failure
+int deinit_timer(timer_t timerid);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/connectivity/gps/gps_hal/src/agpsinf.c b/src/connectivity/gps/gps_hal/src/agpsinf.c
new file mode 100644
index 0000000..c1ba646
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/src/agpsinf.c
@@ -0,0 +1,181 @@
+/* Copyright Statement:
+ *
+ * This software/firmware and related documentation ("MediaTek Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to MediaTek Inc. and/or its licensors.
+ * Without the prior written permission of MediaTek inc. and/or its licensors,
+ * any reproduction, modification, use or disclosure of MediaTek Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ *
+ * MediaTek Inc. (C) 2016. All rights reserved.
+ *
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
+ * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
+ * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
+ *
+ * The following software/firmware and/or related documentation ("MediaTek Software")
+ * have been modified by MediaTek Inc. All revisions are subject to any receiver's
+ * applicable license agreements with MediaTek Inc.
+ */
+
+#include <string.h>
+
+#include "gpshal.h"
+#include "hal2mnl_interface.h"
+#include "mtk_lbs_utility.h"
+#include "mtk_auto_log.h"
+
+#ifdef LOG_TAG
+#undef LOG_TAG
+#define LOG_TAG "agpsinf"
+#endif
+
+//=========================================================
+// Agps Interface
+#ifndef __unused
+#define __unused
+#endif
+
+static void agpsinf_init(AGpsCallbacks* callbacks) {
+ g_gpshal_ctx.agps_cbs = callbacks;
+}
+
+static int agpsinf_set_server(AGpsType type, const char* hostname, int port) {
+ hal2mnl_set_server(type, hostname, port);
+ return 0; // 0:ok, non-zero: error; but GPS JNI will ignore it
+}
+
+static int agpsinf_data_conn_open_with_apn_ip_type(
+ const char* apn,
+ ApnIpType apnIpType) {
+ hal2mnl_data_conn_open_with_apn_ip_type(apn, apnIpType);
+ return 0; // 0:ok, non-zero: error; but GPS JNI will ignore it
+}
+
+const AGpsInterface mtk_agps_inf = {
+ sizeof(AGpsInterface),
+ agpsinf_init,
+ hal2mnl_data_conn_open, // GPS JNI will ignore its ret value
+ hal2mnl_data_conn_closed, // GPS JNI will ignore its ret value
+ hal2mnl_data_conn_failed, // GPS JNI will ignore its ret value
+ agpsinf_set_server,
+ agpsinf_data_conn_open_with_apn_ip_type
+};
+
+
+//=========================================================
+// Gps Ni Interface
+
+static void gpsni_init(GpsNiCallbacks *callbacks) {
+ g_gpshal_ctx.gpsni_cbs = callbacks;
+}
+
+static void gpsni_respond(int notif_id, GpsUserResponseType user_response) {
+ hal2mnl_ni_respond(notif_id, user_response);
+}
+
+const GpsNiInterface mtk_gps_ni_inf = {
+ sizeof(GpsNiInterface),
+ gpsni_init,
+ gpsni_respond
+};
+
+
+//=========================================================
+// Agps Ril Interface
+
+static void agps_ril_init(AGpsRilCallbacks* callbacks) {
+ g_gpshal_ctx.agpsril_cbs = callbacks;
+}
+
+static void agps_ril_set_ref_location(
+ const AGpsRefLocation *agps_reflocation,
+ __unused size_t sz_struct) {
+ // UNUSED(sz_struct);
+ uint16_t type = agps_reflocation->type;
+ switch (type) {
+ case AGPS_REF_LOCATION_TYPE_GSM_CELLID:
+ case AGPS_REF_LOCATION_TYPE_UMTS_CELLID: {
+ const AGpsRefLocationCellID cell = agps_reflocation->u.cellID;
+ hal2mnl_set_ref_location(
+ type, cell.mcc, cell.mnc, cell.lac, cell.cid);
+ break;
+ }
+ // case AGPS_REG_LOCATION_TYPE_MAC:
+ // TODO: to support MAC when GPS JNI can support it
+ // break;
+ default:
+ LOGW("%s: unsupported ref loc type: %d", __func__, type);
+ }
+}
+
+static void agps_ril_set_set_id(AGpsSetIDType type, const char* setid) {
+ hal2mnl_set_id(type, setid);
+}
+
+static void agps_ril_ni_message(uint8_t *msg, size_t len) {
+ hal2mnl_ni_message((char*)msg, len);
+}
+
+static void agps_ril_update_network_state(int connected, int type, int roaming, const char* extra_info) {
+ hal2mnl_update_network_state(connected, type, roaming, extra_info);
+}
+
+static void agps_ril_update_network_availability(int available, const char* apn) {
+ hal2mnl_update_network_availability(available, apn);
+}
+
+const AGpsRilInterface mtk_agps_ril_inf = {
+ sizeof(AGpsRilInterface),
+ agps_ril_init,
+ agps_ril_set_ref_location,
+ agps_ril_set_set_id,
+ agps_ril_ni_message,
+ agps_ril_update_network_state,
+ agps_ril_update_network_availability
+};
+
+//=========================================================
+// Supl Certificate Interface
+
+#if 0 // not ready, even in GPS JNI
+static int suplcert_install_certificates(
+ __unused const DerEncodedCertificate* certificates,
+ __unused size_t length) {
+ UNUSED_VAR(certificates);
+ UNUSED_VAR(length);
+ // TODO: to use the new hal2mnl lib
+ return -1;
+}
+
+static int suplcert_revoke_certificates(
+ __unused const Sha1CertificateFingerprint* fingerprints,
+ __unused size_t length) {
+ UNUSED_VAR(fingerprints);
+ UNUSED_VAR(length);
+ // TODO: to use the new hal2mnl lib
+ return -1;
+}
+
+const SuplCertificateInterface mtk_supl_cert_inf = {
+ sizeof(SuplCertificateInterface),
+ suplcert_install_certificates,
+ suplcert_revoke_certificates,
+};
+#endif
+
diff --git a/src/connectivity/gps/gps_hal/src/data_coder.c b/src/connectivity/gps/gps_hal/src/data_coder.c
new file mode 100644
index 0000000..ab67b38
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/src/data_coder.c
@@ -0,0 +1,154 @@
+#include <string.h>
+
+#ifndef MAX
+#define MAX(A,B) ((A)>(B)?(A):(B))
+#endif
+#ifndef MIN
+#define MIN(A,B) ((A)<(B)?(A):(B))
+#endif
+
+//===============================================================
+// get
+char get_byte(char* buff, int* offset, int src_len) {
+ char ret = 0;
+ if (*offset >= 0 && *offset < src_len) {
+ ret = buff[*offset];
+ *offset += 1;
+ }
+ return ret;
+}
+
+short get_short(char* buff, int* offset, int src_len) {
+ short ret = 0;
+ ret |= get_byte(buff, offset, src_len) & 0xff;
+ ret |= (get_byte(buff, offset, src_len) << 8);
+ return ret;
+}
+
+int get_int(char* buff, int* offset, int src_len) {
+ int ret = 0;
+ ret |= get_short(buff, offset, src_len) & 0xffff;
+ ret |= (get_short(buff, offset, src_len) << 16);
+ return ret;
+}
+
+long long get_long(char* buff, int* offset, int src_len) {
+ long long ret = 0;
+ ret |= get_int(buff, offset, src_len) & 0xffffffffL;
+ ret |= ((long long)get_int(buff, offset, src_len) << 32);
+ return ret;
+}
+
+float get_float(char* buff, int* offset, int src_len) {
+ float ret;
+ int tmp = get_int(buff, offset, src_len);
+ ret = *((float*)&tmp);
+ return ret;
+}
+
+double get_double(char* buff, int* offset, int src_len) {
+ double ret;
+ long long tmp = get_long(buff, offset, src_len);
+ ret = *((double*)&tmp);
+ return ret;
+}
+
+char* get_string(char* buff, int* offset, int src_len) {
+ char ret = get_byte(buff, offset, src_len);
+ if (ret == 0) {
+ return NULL;
+ } else {
+ char* p = NULL;
+ int len = get_int(buff, offset, src_len);
+ if (*offset < 0 || *offset >= src_len) {
+ *offset = 0;
+ }
+ if ((len > src_len - *offset) || len < 0) {
+ len = src_len - *offset;
+ }
+ if (len <= 0) {
+ return NULL;
+ }
+ p = &buff[*offset];
+ p[len-1] = 0;
+ *offset += len;
+ return p;
+ }
+}
+
+char* get_string2(char* buff, int* offset, int src_len) {
+ char* output = get_string(buff, offset, src_len);
+ if (output == NULL) {
+ return "";
+ } else {
+ return output;
+ }
+}
+
+int get_binary(char* buff, int* offset, char* output, int src_len, int des_len) {
+ int len = 0;
+ if (*offset >= 0 && *offset <= src_len) {
+ len = get_int(buff, offset, src_len);
+ if (len > MIN((src_len-(*offset)), des_len)) {
+ len = MIN((src_len-(*offset)), des_len);
+ }
+ if (len > 0) {
+ memcpy(output, &buff[*offset], len);
+ *offset += len;
+ }
+ }
+ return len;
+}
+
+//===============================================================
+// put
+void put_byte(char* buff, int* offset, const char input) {
+ *((char*)&buff[*offset]) = input;
+ *offset += 1;
+}
+
+void put_short(char* buff, int* offset, const short input) {
+ put_byte(buff, offset, input & 0xff);
+ put_byte(buff, offset, (input >> 8) & 0xff);
+}
+
+void put_int(char* buff, int* offset, const int input) {
+ put_short(buff, offset, input & 0xffff);
+ put_short(buff, offset, (input >> 16) & 0xffff);
+}
+
+void put_long(char* buff, int* offset, const long long input) {
+ put_int(buff, offset, input & 0xffffffffL);
+ put_int(buff, offset, ((input >> 32L) & 0xffffffffL));
+}
+
+void put_float(char* buff, int* offset, const float input) {
+ int* data = (int*)&input;
+ put_int(buff, offset, *data);
+}
+
+void put_double(char* buff, int* offset, const double input) {
+ long long* data = (long long*)&input;
+ put_long(buff, offset, *data);
+}
+
+void put_string(char* buff, int* offset, const char* input) {
+ if (input == NULL) {
+ put_byte(buff, offset, 0);
+ } else {
+ int len = strlen(input) + 1;
+ put_byte(buff, offset, 1);
+ put_int(buff, offset, len);
+ memcpy(&buff[*offset], input, len);
+ *offset += len;
+ }
+}
+
+void put_binary(char* buff, int* offset, const char* input, const int len) {
+ put_int(buff, offset, len);
+ if (len > 0) {
+ memcpy(&buff[*offset], input, len);
+ *offset += len;
+ }
+}
+
diff --git a/src/connectivity/gps/gps_hal/src/geofenceinf.c b/src/connectivity/gps/gps_hal/src/geofenceinf.c
new file mode 100644
index 0000000..78c229f
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/src/geofenceinf.c
@@ -0,0 +1,153 @@
+#include "gpshal.h"
+#include "geofencehal_worker.h"
+#include "mtk_auto_log.h"
+#include <stdio.h>
+#include <inttypes.h>
+
+#ifndef UNUSED
+#define UNUSED(x) (x)=(x)
+#endif
+
+/**********************************************************
+ * Global Variables *
+ **********************************************************/
+extern unsigned int gConfigHalGeofence;
+
+/*********************************************************/
+/* FLP Geofence Interface implementation */
+/*********************************************************/
+void mtk_hal_geofence_init(GpsGeofenceCallbacks* callbacks) {
+ hal2_geofence_init();
+ LOGD("init geofence, cb function : %p",callbacks);
+ g_gpshal_ctx.geofence_cbs= callbacks;
+ return;
+}
+
+void mtk_hal_geofence_add_geofences(int32_t geofence_id, double latitude, double longitude,
+ double radius_meters, int last_transition, int monitor_transitions,
+ int notification_responsiveness_ms, int unknown_timer_ms) {
+ MTK_GEOFENCE_PROPERTY_T dbg_fence;
+
+ if(!is_gfc_exist()) {
+ LOGE("gfc not exist");
+ return;
+ }
+ dbg_fence.geofence_id = geofence_id;
+ dbg_fence.latitude = latitude;
+ dbg_fence.longitude = longitude;
+ dbg_fence.radius = radius_meters;
+ dbg_fence.last_transition = last_transition;
+ dbg_fence.monitor_transition = monitor_transitions;
+ dbg_fence.notification_period = notification_responsiveness_ms;
+ dbg_fence.unknown_timer = unknown_timer_ms;
+ dbg_fence.alive = 1;
+ dbg_fence.latest_state = last_transition >> 1;
+ dbg_fence.config = gConfigHalGeofence;
+ mtk_geo_inject_info_get(dbg_fence.geofence_id, &dbg_fence.coordinate_dn, &dbg_fence.coordinate_de);
+ hal2_geofence_add_geofences(dbg_fence);
+ return;
+}
+
+void mtk_hal_geofence_pause_geofence(int32_t geofence_id) {
+ if(!is_gfc_exist()) {
+ LOGE("gfc not exist");
+ return;
+ }
+ hal2_geofence_pause_geofence(geofence_id);
+ return;
+}
+
+void mtk_hal_geofence_resume_geofence(int32_t geofence_id, int monitor_transitions) {
+ if(!is_gfc_exist()) {
+ LOGE("gfc not exist");
+ return;
+ }
+ hal2_geofence_resume_geofence(geofence_id,monitor_transitions);
+ return;
+}
+
+void mtk_hal_geofence_remove_geofences(int32_t geofence_id) {
+ if(!is_gfc_exist()) {
+ LOGE("gfc not exist");
+ return;
+ }
+ hal2_geofence_remove_geofences(geofence_id);
+ return;
+}
+
+/*************************************************************/
+/* Handle message from mnl to GPS/Geofence HAL */
+/*************************************************************/
+void mtk_geofence_transition_callbacks_proc(MTK_FLP_MSG_T *prmsg) {
+ int32_t geofence_id, transition;
+ GpsLocation location;
+ int64_t timestamp;
+ #ifdef MTK_64_PLATFORM
+ unsigned char ratio = 2; //32 to 64-bits
+ unsigned char padding_diff = 4;
+ unsigned char loc_in[128] = {0};
+ unsigned int sizeof_loc_in = sizeof(GpsLocation) - sizeof(size_t)/ratio - padding_diff;
+ #else
+ uint32_t sizeof_loc_in = sizeof(GpsLocation);
+ #endif
+ memcpy(&geofence_id, (((char*)prmsg)+sizeof(MTK_FLP_MSG_T)), sizeof(int32_t));
+ #ifdef MTK_64_PLATFORM
+ memcpy(loc_in, (((char*)prmsg)+sizeof(MTK_FLP_MSG_T)+sizeof(int32_t)), sizeof_loc_in);
+ mtk_loc_rearrange(loc_in, &location);
+ #else
+ memcpy(&location, (((char*)prmsg)+sizeof(MTK_FLP_MSG_T)+sizeof(int32_t)), sizeof_loc_in);
+ #endif
+ memcpy(&transition, (((char*)prmsg)+sizeof(MTK_FLP_MSG_T)+sizeof(int32_t)+sizeof_loc_in), sizeof(int32_t));
+ memcpy(×tamp, (((char*)prmsg)+sizeof(MTK_FLP_MSG_T)+sizeof(int32_t)+sizeof_loc_in+sizeof(int32_t)), sizeof(int64_t));
+ LOGD("geo transition: id=%"PRId32", transition=%"PRId32", latlon=%lf,%lf",geofence_id,transition,location.latitude,location.longitude);
+
+ if(g_gpshal_ctx.geofence_cbs == NULL) {
+ LOGE("mtk_geofence_transition_callbacks_proc: NO geofence callbacks assigned");
+ return;
+ }
+
+ //geofence CB for transition ntf
+ if (set_buff_transition_fence(geofence_id, transition) == 0) {
+ g_gpshal_ctx.geofence_cbs->geofence_transition_callback(geofence_id, &location, transition, timestamp);
+ }
+}
+
+void mtk_geofence_callbacks_proc(MTK_FLP_MSG_T *prmsg) {
+ MTK_GEOFENCE_CALLBACK_T cbs;
+
+ memcpy(&cbs,(char*)prmsg+sizeof(MTK_FLP_MSG_T),sizeof(MTK_GEOFENCE_CALLBACK_T));
+ //LOGD("geo_cb_proc: id=%d, result=%d",cbs.cb_id,cbs.result);
+
+ if(g_gpshal_ctx.geofence_cbs == NULL) {
+ LOGE("mtk_geofence_callbacks_proc: NO geofence callbacks assigned");
+ return;
+ }
+ switch(cbs.cb_id) {
+ case GEOFENCE_ADD_CALLBACK:
+ g_gpshal_ctx.geofence_cbs->geofence_add_callback(cbs.geofence_id, cbs.result);
+ break;
+ case GEOFENCE_REMOVE_CALLBACK:
+ g_gpshal_ctx.geofence_cbs->geofence_remove_callback(cbs.geofence_id, cbs.result);
+ break;
+ case GEOFENCE_PAUSE_CALLBACK:
+ g_gpshal_ctx.geofence_cbs->geofence_pause_callback(cbs.geofence_id, cbs.result);
+ break;
+ case GEOFENCE_RESUME_CALLBACK:
+ g_gpshal_ctx.geofence_cbs->geofence_resume_callback(cbs.geofence_id, cbs.result);
+ break;
+ default:
+ LOGE("mtk_geofence_callbacks_proc: Unknown callback id:%d", cbs.cb_id);
+ break;
+ }
+}
+
+const GpsGeofencingInterface mtkGeofence_inf = {
+ sizeof(GpsGeofencingInterface),
+ mtk_hal_geofence_init,
+ mtk_hal_geofence_add_geofences,
+ mtk_hal_geofence_pause_geofence,
+ mtk_hal_geofence_resume_geofence,
+ mtk_hal_geofence_remove_geofences,
+};
+
+
diff --git a/src/connectivity/gps/gps_hal/src/gfchal_mnl_interface.c b/src/connectivity/gps/gps_hal/src/gfchal_mnl_interface.c
new file mode 100644
index 0000000..5215818
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/src/gfchal_mnl_interface.c
@@ -0,0 +1,717 @@
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/un.h>
+#include <errno.h>
+#include <inttypes.h>
+
+#include "geofencehal_worker.h"
+#include "mtk_auto_log.h"
+
+#ifdef LOG_TAG
+#undef LOG_TAG
+#define LOG_TAG "GFC_INF"
+#endif
+
+/**********************************************************
+ * Define *
+ **********************************************************/
+typedef void*(*threadptr)(void*);
+#define GEOFENCE_INJECT_LOC_ENUM 600
+
+#define MNLD_STRNCPY(dst,src,size) do{\
+ strncpy((char *)(dst), (src), (size - 1));\
+ (dst)[size - 1] = '\0';\
+ }while(0)
+
+
+/**********************************************************
+ * Global Variables *
+ **********************************************************/
+static MTK_GEOFENCE_PROPERTY_T geofence_property[MAX_GOEFENCE];
+static float injectFenceInfo[MAX_GOEFENCE][3];
+static int gTotalFence = 0; /*current fence number, must < MAX_GEOFENCE*/
+static int g_ThreadExitGfcJniSocket = 0, isgfc_exist = 0;
+static pthread_t geofence_hal_jni_thread_id;
+static char g_gfc2mnl_path[128] = GEOFENCE_TO_MNL;
+int g_gfc_server_socket_fd;
+unsigned int gConfigHalGeofence = 0;
+
+/**********************************************************
+ * Function Declaration *
+ **********************************************************/
+void mnl2gfchal_jni_thread(void);
+
+
+/**********************************************************
+ * Socket Function *
+ **********************************************************/
+static int safe_recvfrom(int sockfd, char* buf, int len) {
+ int ret = 0;
+ int retry = 10;
+
+ while ((ret = recvfrom(sockfd, buf, len, 0, NULL, NULL)) == -1) {
+ //LOGW("ret=%d len=%d\n", ret, len);
+ if (errno == EINTR) continue;
+ if (errno == EAGAIN) {
+ if (retry-- > 0) {
+ usleep(100 * 1000);
+ continue;
+ }
+ }
+ LOGE("sendto reason=[%s]\n", strerror(errno));
+ break;
+ }
+ return ret;
+}
+
+// -1 means failure
+static int safe_sendto(int sockfd, const char* dest, const char* buf, int size) {
+ int len = 0;
+ struct sockaddr_un soc_addr;
+ int retry = 10;
+
+ memset(&soc_addr, 0, sizeof(soc_addr));
+ soc_addr.sun_path[0] = 0;
+ MNLD_STRNCPY(soc_addr.sun_path + 1, dest,sizeof(soc_addr.sun_path) - 1);
+ soc_addr.sun_family = AF_UNIX;
+
+ while ((len = sendto(sockfd, buf, size, 0, (const struct sockaddr *)&soc_addr, sizeof(soc_addr))) == -1) {
+ if (errno == EINTR) continue;
+ if (errno == EAGAIN) {
+ if (retry-- > 0) {
+ usleep(100 * 1000);
+ continue;
+ }
+ }
+ LOGE("sendto dest=[%s] len=%d reason=[%s]\n",dest, size, strerror(errno));
+ break;
+ }
+ return len;
+}
+
+static int gfc_send2mnl(const char* buff, int len) {
+ int ret = 0;
+ int sockfd = socket(PF_LOCAL, SOCK_DGRAM, 0);
+
+ if (sockfd < 0) {
+ LOGE("gfc_send2mnl() socket() failed reason=[%s]%d",
+ strerror(errno), errno);
+ return -1;
+ }
+
+ if (safe_sendto(sockfd, g_gfc2mnl_path, buff, len) < 0) {
+ LOGE("gfc_send2mnl safe_sendto failed\n");
+ ret = -1;
+ }
+ close(sockfd);
+ return ret;
+}
+
+static int bind_udp_socket(char* path) {
+ int sockfd;
+ struct sockaddr_un soc_addr;
+
+ sockfd = socket(PF_LOCAL, SOCK_DGRAM, 0);
+ if (sockfd < 0) {
+ LOGE("socket failed reason=[%s]\n", strerror(errno));
+ return -1;
+ }
+ memset(&soc_addr, 0, sizeof(soc_addr));
+ soc_addr.sun_path[0] = 0;
+ MNLD_STRNCPY(soc_addr.sun_path + 1, path,sizeof(soc_addr.sun_path) - 1);
+ soc_addr.sun_family = AF_UNIX;
+ unlink(soc_addr.sun_path);
+
+ if (bind(sockfd, (struct sockaddr *)&soc_addr, sizeof(soc_addr)) < 0) {
+ LOGE("bind failed path=[%s] reason=[%s]\n", path, strerror(errno));
+ close(sockfd);
+ return -1;
+ }
+
+ return sockfd;
+}
+
+
+/**********************************************************
+ * Geofence sub-Functions *
+ **********************************************************/
+static void set_buff_init_fence() {
+ int i;
+ memset(&geofence_property, 0, MAX_GOEFENCE*sizeof(MTK_GEOFENCE_PROPERTY_T));
+ for(i = 0; i < MAX_GOEFENCE; i++) {
+ geofence_property[i].geofence_id = -1;
+ }
+ gTotalFence = 0;
+ return;
+}
+
+static int set_buff_pause_fence(const int item) {
+ geofence_property[item].alive = 0;
+ geofence_property[item].last_transition = GPS_GEOFENCE_UNCERTAIN;
+ geofence_property[item].latest_state = uncertain;
+ return MTK_GFC_SUCCESS;
+}
+
+static int set_buff_resume_fence(const int item, const int transition) {
+ geofence_property[item].monitor_transition = transition;
+ geofence_property[item].alive = 1;
+ return MTK_GFC_SUCCESS;
+}
+
+static int set_buff_remove_fence(const int item) {
+ geofence_property[item].alive = 0;
+ memset(&geofence_property[item],0,sizeof(MTK_GEOFENCE_PROPERTY_T));
+ geofence_property[item].geofence_id = -1;
+ if(gTotalFence > 0) {
+ gTotalFence--;
+ }
+ return MTK_GFC_SUCCESS;
+}
+
+int set_buff_transition_fence(const int32_t fence_id, const int transition) {
+ int item;
+
+ if (transition != GPS_GEOFENCE_ENTERED &&
+ transition != GPS_GEOFENCE_EXITED &&
+ transition != GPS_GEOFENCE_UNCERTAIN) {
+ LOGE("transition type is invalid %d", transition);
+ return MTK_GFC_ERROR;
+ }
+
+ item = check_buff_fence_exist(fence_id);
+ if (item < 0) {
+ LOGE("transition fence id not exist");
+ return MTK_GFC_ERROR;
+ }
+ geofence_property[item].last_transition = transition;
+ geofence_property[item].latest_state = transition >> 1;
+ return MTK_GFC_SUCCESS;
+}
+
+void mtk_geo_inject_info_init() {
+ memset(injectFenceInfo, 0, sizeof(injectFenceInfo[0][0]) * MAX_GOEFENCE * 3);
+ //LOGD("GEO_JNI: init fence info\n");
+}
+
+static void mtk_geo_set_project_config() {
+ const char flp_prop_path[] = "/vendor/etc/geo.prop";
+ char propbuf[512];
+ FILE *fp = fopen(flp_prop_path, "rb");
+
+ gConfigHalGeofence = 0;
+ if(!fp) {
+ LOGE("mtk_flp_set_project_config - open fd fail! %d (%s)", errno, strerror(errno));
+ return;
+ }
+ while(fgets(propbuf, sizeof(propbuf), fp)) {
+ if(strstr(propbuf, "lowpower.geofence=no")) {
+ gConfigHalGeofence |= GEO_CONFIG_MASK_DISABLE_SMD;
+ }
+ }
+ LOGD("mtk_flp_set_project_config %u", gConfigHalGeofence);
+ fclose(fp);
+ return;
+}
+
+void mtk_geo_inject_info_set(int fence_id, float dn, float de) {
+ if (fence_id < MAX_GOEFENCE) {
+ injectFenceInfo[fence_id][0] = 1; //valid
+ injectFenceInfo[fence_id][1] = dn;
+ injectFenceInfo[fence_id][2] = de;
+ LOGD("GEO_JNI :set fence info, %d %f %f", fence_id, dn, de);
+ }
+}
+
+void mtk_geo_inject_info_reset(int fence_id) {
+ if (fence_id < MAX_GOEFENCE) {
+ injectFenceInfo[fence_id][0] = 0; //valid
+ injectFenceInfo[fence_id][1] = 0;
+ injectFenceInfo[fence_id][2] = 0;
+ LOGD("GEO_JNI: reset fence id %d\n", fence_id);
+ }
+}
+
+void mtk_geo_inject_info_get(int fence_id, float* dn, float* de) {
+ *dn = 0;
+ *de = 0;
+ if (fence_id < MAX_GOEFENCE) {
+ if (injectFenceInfo[fence_id][0]) {
+ *dn = injectFenceInfo[fence_id][1];
+ *de = injectFenceInfo[fence_id][2];
+ LOGD("GEO_JNI: get fence info %d %f %f\n", fence_id, *dn, *de);
+ }
+ }
+}
+
+static int check_buff_full_of_fence() {
+ if(gTotalFence >= MAX_GOEFENCE) {
+ return MTK_GFC_ERROR;
+ } else {
+ return MTK_GFC_SUCCESS;
+ }
+}
+
+int check_buff_fence_exist(const int32_t fence_id) {
+ int i;
+
+ for(i = 0; i < MAX_GOEFENCE; i++) {
+ if(geofence_property[i].geofence_id == fence_id ) {
+ return i;
+ }
+ }
+ return MTK_GFC_ERROR;
+}
+
+static int check_valid_transition(const int transition) {
+ switch(transition) {
+ case GPS_GEOFENCE_ENTERED:
+ case GPS_GEOFENCE_EXITED:
+ case GPS_GEOFENCE_ENTERED|GPS_GEOFENCE_EXITED:
+ case GPS_GEOFENCE_ENTERED|GPS_GEOFENCE_EXITED|GPS_GEOFENCE_UNCERTAIN:
+ return MTK_GFC_SUCCESS;
+ default:
+ return MTK_GFC_ERROR;
+ }
+}
+
+static int get_buff_avalibale_item() {
+ int i = 0;
+
+ while(i < MAX_GOEFENCE && geofence_property[i].alive == 1) {
+ i++;
+ }
+
+ if(i == MAX_GOEFENCE) {
+ return MTK_GFC_ERROR;
+ }
+ return i;
+}
+
+static int check_fence_vadility(const MTK_GEOFENCE_PROPERTY_T fence) {
+ int ret;
+ int ret2;
+
+ ret = check_buff_full_of_fence();
+ if(ret < 0) {
+ LOGE("too many fences\n");
+ ret2 = -1;
+ return ret2;
+ }
+ ret = check_buff_fence_exist(fence.geofence_id);
+ if(ret >= 0) {
+ LOGE("fence has been added before\n");
+ ret2 = -2;
+ return ret2;
+ }
+ ret = check_valid_transition(fence.monitor_transition);
+ if(ret < 0) {
+ LOGE("fence is invalid\n");
+ ret2 = -3;
+ return ret2;
+ }
+ ret2 = 0;
+ return ret2;
+}
+
+static int set_buff_add_fence(const MTK_GEOFENCE_PROPERTY_T fence) {
+ int item;
+
+ item = get_buff_avalibale_item();
+ if(item < 0) {
+ LOGE("out of range\n");
+ return MTK_GFC_ERROR;
+ }
+ //LOGD("new fenece will be added into item %d\n", item);
+
+ memcpy(&geofence_property[item], &fence, sizeof(MTK_GEOFENCE_PROPERTY_T));
+ geofence_property[item].alive = 1;
+ gTotalFence++;
+ return MTK_GFC_SUCCESS;
+}
+
+#ifdef MTK_64_PLATFORM
+void mtk_loc_rearrange(unsigned char *loc_in, GpsLocation *loc_out) {
+ unsigned char ratio = 2; //32 to 64-bits
+ unsigned char padding_diff = 4;
+ unsigned int sizeof_loc_in = sizeof(GpsLocation) - sizeof(size_t)/ratio - padding_diff;
+
+ memset(loc_out, 0, sizeof(GpsLocation));
+ loc_out->size = sizeof(GpsLocation);
+ memcpy(&loc_out->flags, loc_in + sizeof(size_t)/ratio, sizeof(uint16_t));
+ memcpy(&loc_out->latitude, loc_in + sizeof(size_t), sizeof_loc_in - sizeof(size_t));
+}
+#endif
+
+/*************************************************************/
+/* mnl to FLP HAL socket, -1 means failure */
+/*************************************************************/
+int create_mnl2gfchal_fd() {
+ int fd = bind_udp_socket(MNL_TO_GEOFENCE);
+ return fd;
+}
+
+int is_gfc_exist() {
+ return isgfc_exist;
+}
+
+
+/*********************************************************/
+/* GPS Geofence Interface implementation */
+/*********************************************************/
+void hal2_geofence_init() {
+ int ret;
+ #if 0
+ int offset = 0;
+ char buff[HAL_GFC_BUFF_SIZE] = {0};
+ MTK_FLP_MSG_T *geo_header =NULL;
+ MTK_FLP_MSG_T geo_msg;
+ #endif
+
+ //Init client socket thread
+ if(isgfc_exist) {
+ LOGE("geofence init before");
+ return;
+ }
+ ret = pthread_create(&geofence_hal_jni_thread_id, NULL, (threadptr)mnl2gfchal_jni_thread, NULL);
+ if(ret < 0) {
+ LOGE("Create mnl2gfchal_jni_thread error\n");
+ }
+ isgfc_exist = 1;
+ #if 0
+ geo_header = malloc(sizeof(MTK_FLP_MSG_T) + sizeof(MTK_FLP_MSG_T));
+ if(geo_header == NULL) {
+ LOGE("init fence malloc error");
+ return;
+ }
+
+ geo_header->type = MTK_FLP_MSG_OFL_GEOFENCE_CMD;
+ geo_header->length = sizeof(MTK_FLP_MSG_T) + sizeof(MTK_FLP_MSG_T);
+ geo_msg.type = INIT_GEOFENCE;
+ geo_msg.length = sizeof(MTK_FLP_MSG_T);
+ memcpy( ((char*)geo_header)+sizeof(MTK_FLP_MSG_T),&geo_msg, sizeof(MTK_FLP_MSG_T));
+ put_binary(buff, &offset, (const char*)&geo_header, geo_header->length);
+ ret = gfc_send2mnl(buff, offset);
+ free(geo_header);
+ if(ret < 0) {
+ LOGE("MTK_HAL2GFC send error return error");
+ return;
+ }
+ #endif
+ set_buff_init_fence();
+ mtk_geo_inject_info_init();
+ mtk_geo_set_project_config();
+ return;
+}
+
+void hal2_geofence_add_geofences(const MTK_GEOFENCE_PROPERTY_T dbg_fence) {
+ int ret, offset = 0;
+ char buff[HAL_GFC_BUFF_SIZE] = {0};
+ int32_t partial_size = 1;
+ MTK_FLP_MSG_T *geo_header=NULL;
+ MTK_FLP_MSG_T geo_msg;
+
+ /* For geofence recover mechanism */
+ ret = check_fence_vadility(dbg_fence);
+ if (ret == 0) {
+ set_buff_add_fence(dbg_fence);
+ } else {
+ return;
+ }
+
+ //construct add fence cmd
+ geo_header = malloc(2*sizeof(MTK_FLP_MSG_T)+sizeof(int32_t) + sizeof(MTK_GEOFENCE_PROPERTY_T));
+ if(geo_header == NULL) {
+ LOGE("add fence malloc error");
+ return;
+ }
+
+ geo_header->type = MTK_FLP_MSG_OFL_GEOFENCE_CMD;
+ geo_header->length = sizeof(MTK_FLP_MSG_T) + sizeof(MTK_FLP_MSG_T) + sizeof(int32_t) + sizeof(MTK_GEOFENCE_PROPERTY_T);
+ geo_msg.type = ADD_GEOFENCE_AREA;
+ geo_msg.length = sizeof(MTK_FLP_MSG_T) + sizeof(int32_t) + sizeof(MTK_GEOFENCE_PROPERTY_T);
+ memcpy( ((char*)geo_header)+sizeof(MTK_FLP_MSG_T),&geo_msg, sizeof(MTK_FLP_MSG_T));
+ memcpy( ((char*)geo_header)+2*sizeof(MTK_FLP_MSG_T),&partial_size, sizeof(int32_t));
+ memcpy( ((char*)geo_header)+2*sizeof(MTK_FLP_MSG_T)+sizeof(int32_t),&dbg_fence, sizeof(MTK_GEOFENCE_PROPERTY_T));
+ #if 1
+ LOGD("HAL Add fence, id=%d, ll=%lf,%lf, last=%d, monitor=%d, notsec=%d, unksec=%d, ned=%f,%f, con=%u",
+ dbg_fence.geofence_id, dbg_fence.latitude, dbg_fence.longitude,
+ dbg_fence.last_transition, dbg_fence.monitor_transition,
+ dbg_fence.notification_period, dbg_fence.unknown_timer,
+ dbg_fence.coordinate_dn, dbg_fence.coordinate_de, dbg_fence.config);
+ #endif
+ put_binary(buff, &offset, (const char*)geo_header, geo_header->length);
+ ret = gfc_send2mnl(buff, offset);
+ free(geo_header);
+ if(ret < 0) {
+ LOGE("MTK_HAL2GFC send error return error");
+ return;
+ }
+ return;
+}
+
+void hal2_geofence_pause_geofence(const int32_t geofence_id) {
+ int ret, offset = 0;
+ char buff[HAL_GFC_BUFF_SIZE] = {0};
+ MTK_FLP_MSG_T *geo_header=NULL;
+ MTK_FLP_MSG_T geo_msg;
+
+ /* For geofence recover mechanism */
+ ret = check_buff_fence_exist(geofence_id);
+ if (ret != MTK_GFC_ERROR) {
+ set_buff_pause_fence(ret);
+ } else {
+ return;
+ }
+
+ //LOGD("hal2_geofence_pause_geofence, id: %d fence",geofence_id);
+ //construct pause fence cmd
+ geo_header = malloc(2*sizeof(MTK_FLP_MSG_T) + sizeof(int32_t));
+ if(geo_header == NULL) {
+ LOGE("pause fence malloc error");
+ return;
+ }
+
+ geo_header->type = MTK_FLP_MSG_OFL_GEOFENCE_CMD;
+ geo_header->length = sizeof(MTK_FLP_MSG_T) + sizeof(MTK_FLP_MSG_T) + sizeof(int32_t);
+ geo_msg.type = PAUSE_GEOFENCE;
+ geo_msg.length = sizeof(MTK_FLP_MSG_T) + sizeof(int32_t);
+ memcpy( ((char*)geo_header)+sizeof(MTK_FLP_MSG_T),&geo_msg, sizeof(MTK_FLP_MSG_T));
+ memcpy( ((char*)geo_header)+2*sizeof(MTK_FLP_MSG_T),&geofence_id, sizeof(int32_t));
+ put_binary(buff, &offset, (const char*)geo_header, geo_header->length);
+ ret = gfc_send2mnl(buff, offset);
+ free(geo_header);
+ if(ret < 0) {
+ LOGD("MTK_HAL2GFC send error return error");
+ return;
+ }
+ return;
+}
+
+
+void hal2_geofence_resume_geofence(const int32_t geofence_id, const int monitor_transitions) {
+ int ret, offset = 0;
+ char buff[HAL_GFC_BUFF_SIZE] = {0};
+ MTK_FLP_MSG_T *geo_header=NULL;
+ MTK_FLP_MSG_T geo_msg;
+
+ /* For geofence recover mechanism */
+ ret = check_buff_fence_exist(geofence_id);
+ if(ret != MTK_GFC_ERROR) {
+ set_buff_resume_fence(ret, monitor_transitions);
+ } else {
+ return;
+ }
+
+ //LOGD("hal2_geofence_resume_geofence, id: %d fence",geofence_id);
+ //construct resume fence cmd
+ geo_header = malloc(2*sizeof(MTK_FLP_MSG_T) + sizeof(int32_t) + sizeof(int));
+ if(geo_header == NULL) {
+ LOGE("resume fence malloc error");
+ return;
+ }
+ geo_header->type = MTK_FLP_MSG_OFL_GEOFENCE_CMD;
+ geo_header->length = 2*sizeof(MTK_FLP_MSG_T) + sizeof(int32_t) + sizeof(int);
+ geo_msg.type = RESUME_GEOFENCE;
+ geo_msg.length = sizeof(MTK_FLP_MSG_T) + sizeof(int32_t) + sizeof(int);
+ memcpy( ((char*)geo_header)+sizeof(MTK_FLP_MSG_T),&geo_msg, sizeof(MTK_FLP_MSG_T));
+ memcpy( ((char*)geo_header)+2*sizeof(MTK_FLP_MSG_T),&geofence_id, sizeof(int32_t));
+ memcpy( ((char*)geo_header)+2*sizeof(MTK_FLP_MSG_T)+sizeof(int32_t),&monitor_transitions, sizeof(int));
+ put_binary(buff, &offset, (const char*)geo_header, geo_header->length);
+ ret = gfc_send2mnl(buff, offset);
+ free(geo_header);
+ if(ret < 0) {
+ LOGE("MTK_HAL2GFC send error return error");
+ return;
+ }
+ return;
+}
+
+void hal2_geofence_remove_geofences(const int32_t geofence_id) {
+ int ret, offset = 0;
+ char buff[HAL_GFC_BUFF_SIZE] = {0};
+ MTK_FLP_MSG_T *geo_header=NULL;
+ MTK_FLP_MSG_T geo_msg;
+
+ /* For geofence recover mechanism */
+ ret = check_buff_fence_exist(geofence_id);
+ if(ret != MTK_GFC_ERROR) {
+ mtk_geo_inject_info_reset(geofence_id);
+ set_buff_remove_fence(ret);
+ } else {
+ return;
+ }
+
+ //LOGD("hal2_geofence_remove_geofences, fence id =%d",geofence_id);
+ //construct remove fence cmd
+ geo_header = malloc(2*sizeof(MTK_FLP_MSG_T) + sizeof(int32_t));
+ if(geo_header == NULL) {
+ LOGE("resume fence malloc error");
+ return;
+ }
+
+ geo_header->type = MTK_FLP_MSG_OFL_GEOFENCE_CMD;
+ geo_header->length = sizeof(MTK_FLP_MSG_T) + sizeof(MTK_FLP_MSG_T) + sizeof(int32_t);
+ geo_msg.type = REMOVE_GEOFENCE;
+ geo_msg.length = sizeof(MTK_FLP_MSG_T) + sizeof(int32_t);
+ memcpy( ((char*)geo_header)+sizeof(MTK_FLP_MSG_T),&geo_msg, sizeof(MTK_FLP_MSG_T));
+ memcpy( ((char*)geo_header)+2*sizeof(MTK_FLP_MSG_T),&geofence_id, sizeof(int32_t));
+ put_binary(buff, &offset, (const char*)geo_header, geo_header->length);
+ ret = gfc_send2mnl(buff, offset);
+ free(geo_header);
+ if(ret < 0) {
+ LOGE("MTK_HAL2GFC send error return error");
+ return;
+ }
+ return;
+}
+
+void hal2_geofence_recover_geofences() {
+ int ret, offset = 0;
+ char buff[HAL_GFC_BUFF_SIZE] = {0};
+ int i;
+ int partial_size = 1;
+ MTK_FLP_MSG_T* geo_header = NULL;
+ MTK_FLP_MSG_T geo_msg;
+
+ LOGE("FLP HAL RECOVER: recover total fence = %d", gTotalFence);
+ for(i = 0; i < MAX_GOEFENCE; i++) {
+ if(geofence_property[i].alive == 1) {
+ geo_header = malloc( sizeof(MTK_FLP_MSG_T)+ sizeof(MTK_FLP_MSG_T) + sizeof(int32_t) + sizeof(MTK_GEOFENCE_PROPERTY_T));
+ geo_header->type = MTK_FLP_MSG_OFL_GEOFENCE_CMD;
+ geo_header->length = sizeof(MTK_FLP_MSG_T)+ sizeof(MTK_FLP_MSG_T)+ sizeof(int32_t) + sizeof(MTK_GEOFENCE_PROPERTY_T);
+ geo_msg.type = RECOVER_GEOFENCE;
+ geo_msg.length = sizeof(MTK_FLP_MSG_T)+ sizeof(int32_t) + sizeof(MTK_GEOFENCE_PROPERTY_T);
+ memcpy(((char*)geo_header)+sizeof(MTK_FLP_MSG_T), &geo_msg, sizeof(MTK_FLP_MSG_T));
+ memcpy((((char*)geo_header)+sizeof(MTK_FLP_MSG_T)+sizeof(MTK_FLP_MSG_T)), &partial_size, sizeof(int32_t));
+ memcpy((((char*)geo_header)+sizeof(MTK_FLP_MSG_T)+sizeof(MTK_FLP_MSG_T)+sizeof(int32_t)),&geofence_property[i],sizeof(MTK_GEOFENCE_PROPERTY_T));
+ LOGE("FLP HAL RECOVER: id=%"PRId32",type=%d,%d,%d,%lf,%d",geofence_property[i].geofence_id,geofence_property[i].last_transition,geofence_property[i].monitor_transition,
+ geofence_property[i].notification_period,geofence_property[i].latitude,geofence_property[i].unknown_timer);
+ offset = 0;
+ put_binary(buff, &offset, (const char*)geo_header, geo_header->length);
+ ret = gfc_send2mnl(buff, offset);
+ free(geo_header);
+ if(ret < 0) {
+ LOGE("MTK_HAL2GFC send error return error");
+ return;
+ }
+ }
+ }
+ return;
+}
+
+int mnl2gfchal_hdlr (char *buff) {
+ char data[1024] = {0};
+ int offset = 0;
+ int ret = MTK_GFC_ERROR, len;
+ unsigned int cmd, msg_len;
+ float geo_inject[3] = {0};
+ MTK_FLP_MSG_T *prmsg = NULL;
+
+ if(buff == NULL) {
+ LOGE("mnl2gfchal_hdlr, recv prmsg is null pointer\r\n");
+ return MTK_GFC_ERROR;
+ }
+ len = get_binary(buff, &offset, data, HAL_GFC_BUFF_SIZE, sizeof(data));
+ if((len > 0) && (len<=1024)) {
+ prmsg = (MTK_FLP_MSG_T *)&data[0];
+ } else {
+ LOGE("len err:%d",len);
+ return ret;
+ }
+ cmd = prmsg->type;
+ msg_len = prmsg->length;
+
+ LOGD("msg_len, recv prmsg, type %d, len %d\r\n", cmd, msg_len);
+ switch (cmd) {
+ case MTK_FLP_MSG_SYS_FLPD_RESET_NTF:
+ hal2_geofence_recover_geofences();
+ break;
+ case MTK_FLP_MSG_OFL_GEOFENCE_CALLBACK_NTF:
+ mtk_geofence_transition_callbacks_proc(prmsg);
+ break;
+ case MTK_FLP_MSG_HAL_GEOFENCE_CALLBACK_NTF:
+ mtk_geofence_callbacks_proc(prmsg);
+ break;
+ case GEOFENCE_INJECT_LOC_ENUM:
+ if(msg_len< 3*sizeof(float)) {
+ LOGE("GEOFENCE_INJECT_LOC_ENUM incrorrect size %d",msg_len);
+ return MTK_GFC_ERROR;
+ }
+ memcpy(geo_inject, (char *)prmsg + sizeof(MTK_FLP_MSG_T), 3*sizeof(float));
+ mtk_geo_inject_info_set((int)geo_inject[0],geo_inject[1],geo_inject[2]);
+ break;
+ default:
+ LOGE("invalid geofence cmd:0x%02x",cmd);
+ break;
+ }
+ return MTK_GFC_SUCCESS;
+}
+
+
+/*************************************************************/
+/* mnl to GPS/Geofence HAL main thread */
+/*************************************************************/
+void mnl2gfchal_jni_thread(void) {
+
+ int ret = MTK_GFC_SUCCESS;
+ int offset = 0;
+ int read_len;
+ char buff[HAL_GFC_BUFF_SIZE] = {0};
+ MTK_FLP_MSG_T gfc_header;
+
+ LOGD("mtk_gfc_hal_jni_thread, Create\n");
+
+ g_gfc_server_socket_fd = create_mnl2gfchal_fd();
+
+ ///TODO: add system timer function here
+ //mtk_flp_sys_timer_create(FLP_TIMER_ID_CHECKCNN);
+ //Send SYS_INIT to HAL
+ gfc_header.type = MTK_FLP_MSG_HAL_INIT_CMD;
+ gfc_header.length = 0;
+ put_binary(buff, &offset, (const char*)&gfc_header, sizeof(MTK_FLP_MSG_T));
+ ret = gfc_send2mnl(buff, offset);
+ //LOGD("gfc:MTK_FLP_MSG_HAL_INIT_CMD");
+ if(ret < 0) {
+ LOGE("MTK_HAL2GFC send error return error");
+ }
+
+ if (g_gfc_server_socket_fd >= 0) {
+ while(!g_ThreadExitGfcJniSocket) {
+ // - recv msg from socket interface
+ read_len = safe_recvfrom(g_gfc_server_socket_fd, buff, sizeof(buff));
+ if ((read_len <= 0) || (read_len>HAL_GFC_BUFF_SIZE)) {
+ LOGE("mnl2gfc safe_recvfrom failed read_len=%d", read_len);
+ }
+
+ if (!g_ThreadExitGfcJniSocket) {
+ // Process received message
+ mnl2gfchal_hdlr(buff);
+ } else {
+ LOGE("mtk_flp_hal_jni_thread, read msg fail,exit socket thread\n");
+ //read msg fail...
+ g_ThreadExitGfcJniSocket = 1;
+ }
+ }
+ }
+
+ //close socket
+ LOGD("Closing server_fd,%d\r\n",g_gfc_server_socket_fd);
+ if(g_gfc_server_socket_fd >= 0) {
+ close(g_gfc_server_socket_fd);
+ }
+
+ LOGD("mnl2gfchal_jni_thread, exit\n");
+
+ g_ThreadExitGfcJniSocket = 1;
+ pthread_exit(NULL);
+
+ return;
+}
+
+
diff --git a/src/connectivity/gps/gps_hal/src/gpshal.c b/src/connectivity/gps/gps_hal/src/gpshal.c
new file mode 100644
index 0000000..41ac6a9
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/src/gpshal.c
@@ -0,0 +1,221 @@
+/* Copyright Statement:
+ *
+ * This software/firmware and related documentation ("MediaTek Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to MediaTek Inc. and/or its licensors.
+ * Without the prior written permission of MediaTek inc. and/or its licensors,
+ * any reproduction, modification, use or disclosure of MediaTek Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ *
+ * MediaTek Inc. (C) 2016. All rights reserved.
+ *
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
+ * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
+ * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
+ *
+ * The following software/firmware and/or related documentation ("MediaTek Software")
+ * have been modified by MediaTek Inc. All revisions are subject to any receiver's
+ * applicable license agreements with MediaTek Inc.
+ */
+#include "gpshal.h"
+#include <sys/epoll.h> // epoll_create, epoll_event
+#include <errno.h> // errno
+#include <string.h> // strerror
+
+#include "hal2mnl_interface.h"
+#include "mtk_lbs_utility.h"
+#include "gpshal_param_check.h"
+#include "mtk_auto_log.h"
+
+#if ANDROID_MNLD_PROP_SUPPORT
+#include <cutils/properties.h>
+#endif
+
+#ifdef LOG_TAG
+#undef LOG_TAG
+#define LOG_TAG "gpshal"
+#endif
+
+#define GPSHAL_WORKER_THREAD_NAME "gpshal_worker_thread"
+
+//=========================================================
+
+gpshal_context_t g_gpshal_ctx = {
+ .fd_mnl2hal = -1,
+ .fd_worker_epoll = -1,
+ .thd_worker = 0,
+ .mutex_gps_state_intent = PTHREAD_MUTEX_INITIALIZER,
+ .gps_state_intent = GPSHAL_STATE_UNKNOWN,
+ .gps_state = GPSHAL_STATE_UNKNOWN,
+ .gps_cbs = NULL,
+ .agps_cbs = NULL,
+ .gpsni_cbs = NULL,
+ .agpsril_cbs = NULL,
+ .meas_cbs = NULL,
+ .navimsg_cbs = NULL,
+ .geofence_cbs = NULL,
+ .vzw_debug_cbs = NULL,
+};
+
+//=========================================================
+
+const char* gpshal_state_to_string(gpshal_state state) {
+ switch (state) {
+ case GPSHAL_STATE_UNKNOWN: return "UNKNOWN";
+ case GPSHAL_STATE_RESOURCE: return "RESOURCE_INIT";
+ case GPSHAL_STATE_CLEANUP: return "CLEANUP";
+ case GPSHAL_STATE_INIT: return "INIT";
+ case GPSHAL_STATE_STOP: return "STOP";
+ case GPSHAL_STATE_START: return "START";
+ default: return "INVALID";
+ }
+}
+
+static void gpshal_set_gps_state(gpshal_state newState) {
+ /*LOGD("gps_state: %s -> %s (intent: %s)",
+ gpshal_state_to_string(g_gpshal_ctx.gps_state),
+ gpshal_state_to_string(newState),
+ gpshal_state_to_string(g_gpshal_ctx.gps_state_intent));*/
+ g_gpshal_ctx.gps_state = newState;
+}
+
+void gpshal_set_gps_state_intent(gpshal_state newState) {
+ /*LOGD("gps_state: %s (intent: %s -> %s)",
+ gpshal_state_to_string(g_gpshal_ctx.gps_state),
+ gpshal_state_to_string(g_gpshal_ctx.gps_state_intent),
+ gpshal_state_to_string(newState));*/
+ g_gpshal_ctx.gps_state_intent = newState;
+}
+
+static void gpshal_check_capability(unsigned int *capabilities, unsigned int *year) {
+ #if ANDROID_MNLD_PROP_SUPPORT
+ char chip_id[PROPERTY_VALUE_MAX]={0};
+ property_get("persist.vendor.connsys.chipid", chip_id, NULL);
+ #else
+ char chip_id[100]={0};
+ strncpy(chip_id, "0x6630",sizeof(chip_id));
+ #endif
+ LOGI("chip id = %s", chip_id);
+ if (strcmp(chip_id, "0x6739") == 0 || strcmp(chip_id, "0x6765") == 0 ||
+ strcmp(chip_id, "0x6761") == 0) {
+ /*our HIDL version is 1.0, if the year is 2018, CTS GnssHardwareInfoTest#testHardwareModelName will fail*/
+ //*year = 2018;
+ *year = 2017;
+ *capabilities = (GPS_CAP_MEASUREMENTS | GPS_CAP_MSB | GPS_CAP_MSA);
+ } else {
+ /*our HIDL version is 1.0, if the year is 2018, CTS GnssHardwareInfoTest#testHardwareModelName will fail*/
+ *year = 2017;
+ *capabilities = (GPS_CAP_MEASUREMENTS | GPS_CAP_MSB | GPS_CAP_MSA);
+ }
+}
+//=========================================================
+
+// Design policy
+// Init resources at most once (no retry)
+// Because we can not save an unstable system,
+// we think "less system call is better" for an unstable system
+// Do not deinit resources
+// We want to have a simple design for a built-in service
+// "Deinit" is for an installable / removable service
+static void gpshal_resource_init(GpsCallbacks_ext* src) {
+ unsigned int capabilities = 0;
+ unsigned int year = 0;
+ g_gpshal_ctx.gps_cbs = (GpsCallbacks_ext*)src;
+ if (GPSHAL_STATE_UNKNOWN != g_gpshal_ctx.gps_state_intent) return; // at most once
+
+ gpshal_check_capability(&capabilities, &year);
+ LOGI("year = %d, capabilities = %d", year, capabilities);
+ g_gpshal_ctx.gps_cbs->set_capabilities_cb(capabilities);
+
+ GnssSystemInfo system_info;
+ system_info.year_of_hw = year;
+ system_info.size = sizeof(GnssSystemInfo);
+ g_gpshal_ctx.gps_cbs->set_system_info_cb(&system_info);
+
+ g_gpshal_ctx.fd_mnl2hal = create_mnl2hal_fd();
+ if (-1 == g_gpshal_ctx.fd_mnl2hal) return; // error
+
+ g_gpshal_ctx.fd_worker_epoll = epoll_create(MAX_EPOLL_EVENT);
+ if (-1 == g_gpshal_ctx.fd_worker_epoll) {
+ LOGE("Fail to create epoll reason=[%s]%d",
+ strerror(errno), errno);
+ return; // error
+ }
+
+ if (epoll_add_fd(
+ g_gpshal_ctx.fd_worker_epoll,
+ g_gpshal_ctx.fd_mnl2hal) == -1) {
+ LOGE("Fail to add fd_mnl2hal");
+ return; // error
+ }
+
+ g_gpshal_ctx.thd_worker = g_gpshal_ctx.gps_cbs->create_thread_cb(
+ GPSHAL_WORKER_THREAD_NAME, gpshal_worker_thread, NULL);
+ if (!g_gpshal_ctx.thd_worker) {
+ LOGE("Fail to create %s", GPSHAL_WORKER_THREAD_NAME);
+ return; // error
+ }
+
+ gpshal_set_gps_state(GPSHAL_STATE_RESOURCE);
+}
+
+int gpshal_gpscbs_save(GpsCallbacks_ext* src) {
+// assert(NULL != src);
+ if (sizeof(GpsCallbacks_ext) == src->size) {
+ LOGD("Use GpsCallbacks");
+ gpshal_resource_init(src);
+ return 0;
+ }
+ LOGE("Bad callback, size: %zd, expected: %zd",
+ src->size, sizeof(GpsCallbacks_ext));
+ return -1; // error
+}
+
+//=========================================================
+
+void gpshal2mnl_gps_init() {
+ if (GPSHAL_STATE_RESOURCE <= g_gpshal_ctx.gps_state) { // Check this for unstable system
+ if (hal2mnl_gps_init() > 0) {
+ gpshal_set_gps_state(GPSHAL_STATE_INIT);
+ }
+ }
+}
+
+void gpshal2mnl_gps_start() {
+ if (GPSHAL_STATE_RESOURCE <= g_gpshal_ctx.gps_state) {
+ if (hal2mnl_gps_start() > 0) {
+ gpshal_set_gps_state(GPSHAL_STATE_START);
+ }
+ }
+}
+
+void gpshal2mnl_gps_stop() {
+ if (GPSHAL_STATE_RESOURCE <= g_gpshal_ctx.gps_state) {
+ if (hal2mnl_gps_stop() > 0) {
+ gpshal_set_gps_state(GPSHAL_STATE_STOP);
+ }
+ }
+}
+
+void gpshal2mnl_gps_cleanup() {
+ if (GPSHAL_STATE_RESOURCE <= g_gpshal_ctx.gps_state) {
+ if (hal2mnl_gps_cleanup() > 0) {
+ gpshal_set_gps_state(GPSHAL_STATE_CLEANUP);
+ }
+ }
+}
diff --git a/src/connectivity/gps/gps_hal/src/gpshal_worker.c b/src/connectivity/gps/gps_hal/src/gpshal_worker.c
new file mode 100644
index 0000000..e4012e5
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/src/gpshal_worker.c
@@ -0,0 +1,476 @@
+/* Copyright Statement:
+ *
+ * This software/firmware and related documentation ("MediaTek Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to MediaTek Inc. and/or its licensors.
+ * Without the prior written permission of MediaTek inc. and/or its licensors,
+ * any reproduction, modification, use or disclosure of MediaTek Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ *
+ * MediaTek Inc. (C) 2016. All rights reserved.
+ *
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
+ * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
+ * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
+ *
+ * The following software/firmware and/or related documentation ("MediaTek Software")
+ * have been modified by MediaTek Inc. All revisions are subject to any receiver's
+ * applicable license agreements with MediaTek Inc.
+ */
+#include "gpshal.h"
+#include <sys/epoll.h> // epoll_create, epoll_event
+#include <errno.h> // errno
+#include <string.h> // strerror
+// #include <linux/in.h> // INADDR_NONE
+#include "hal2mnl_interface.h"
+#include "mtk_lbs_utility.h"
+#include "mtk_auto_log.h"
+
+#ifdef LOG_TAG
+#undef LOG_TAG
+#define LOG_TAG "gpshal_worker"
+#endif
+
+//=========================================================
+
+#define GPSHAL_WORKER_THREAD_TIMEOUT (30*1000)
+
+#define fieldp_copy(dst, src, f) (dst)->f = (src)->f
+#define field_copy(dst, src, f) (dst).f = (src).f
+
+DebugData mnlDebugData; //for GNSS HIDL v1.1 GPS debug interface
+
+//=========================================================
+
+static void update_mnld_reboot() {
+// GPSHAL_DEBUG_FUNC_SCOPE2(g_gpshal_ctx.mutex_gps_state_intent);
+ gpshal_state state = g_gpshal_ctx.gps_state_intent;
+ LOGD("state: (%d)", state);
+ switch (state) {
+ case GPSHAL_STATE_INIT:
+ case GPSHAL_STATE_STOP:
+ gpshal2mnl_gps_init();
+ break;
+ case GPSHAL_STATE_START:
+ gpshal2mnl_gps_init();
+ gpshal2mnl_gps_start();
+ break;
+ case GPSHAL_STATE_CLEANUP:
+ default:
+ LOGW("Current gps_state_intent: %s (%d)",
+ gpshal_state_to_string(state), state);
+ }
+}
+static void update_location(gps_location location) {
+ // Use mutex or not ?
+ // If no, the issue may occur.
+ // If yes, there will be a little performance impact.
+ // GPSHAL_DEBUG_FUNC_SCOPE;
+ GpsLocation_ext loc;
+ //dump_gps_location(location);
+ gpshal_state state = g_gpshal_ctx.gps_state;
+ //LOGD("state: (%d)", state);
+ if (GPSHAL_STATE_START == state) {
+ loc.legacyLocation.size = sizeof(loc);
+ loc.legacyLocation.flags = location.flags;
+ loc.legacyLocation.latitude = location.lat;
+ loc.legacyLocation.longitude = location.lng;
+ loc.legacyLocation.altitude = location.alt;
+ loc.legacyLocation.speed = location.speed;
+ loc.legacyLocation.bearing = location.bearing;
+ loc.legacyLocation.accuracy = loc.horizontalAccuracyMeters = location.h_accuracy;
+ loc.verticalAccuracyMeters = location.v_accuracy;
+ loc.speedAccuracyMetersPerSecond = location.s_accuracy;
+ loc.bearingAccuracyDegrees = location.b_accuracy;
+ loc.legacyLocation.timestamp = location.timestamp;
+ LOGD("hacc=%f,vacc=%f,sacc=%f,bacc=%f", loc.horizontalAccuracyMeters, loc.verticalAccuracyMeters,
+ loc.speedAccuracyMetersPerSecond, loc.bearingAccuracyDegrees);
+ g_gpshal_ctx.gps_cbs->location_cb(&loc);
+ //For GNSS HIDL v1.1 Gps debug interface
+ mnlDebugData.position.valid = true;
+ mnlDebugData.position.latitudeDegrees = location.lat;
+ mnlDebugData.position.longitudeDegrees = location.lng;
+ mnlDebugData.position.altitudeMeters = location.alt;
+ mnlDebugData.position.speedMetersPerSec = location.speed;
+ mnlDebugData.position.bearingDegrees = location.bearing;
+ mnlDebugData.position.horizontalAccuracyMeters = location.h_accuracy;
+ mnlDebugData.position.verticalAccuracyMeters = location.v_accuracy;
+ mnlDebugData.position.speedAccuracyMetersPerSecond = location.s_accuracy;
+ mnlDebugData.position.bearingAccuracyDegrees = location.b_accuracy;
+ } else {
+ // Do not report this location to GLP to avoid strange TTFF time issue
+ LOGW("we have a location when gps_state_intent: %s (%d)",
+ gpshal_state_to_string(state), state);
+ }
+}
+static void update_gps_status(gps_status status) {
+ GpsStatus s;
+ LOGD(" status=%d", status);
+ s.size = sizeof(s);
+ s.status = status;
+ g_gpshal_ctx.gps_cbs->status_cb(&s);
+}
+
+static void update_gps_sv(gnss_sv_info sv) {
+
+ // GPSHAL_DEBUG_FUNC_SCOPE;
+ int i;
+ GnssSvStatus_ext gss;
+ //dump_gnss_sv_info(sv);
+ gss.size = sizeof(gss);
+ gss.num_svs = sv.num_svs;
+ if (gss.num_svs > GNSS_MAX_SVS) {
+ gss.num_svs = GNSS_MAX_SVS;
+ }
+ for (i = 0; i < gss.num_svs; i++) {
+ GnssSvInfo* dst = &gss.gnss_sv_list[i].legacySvInfo;
+ gnss_sv* src = &sv.sv_list[i];
+ dst->size = sizeof(*dst);
+ fieldp_copy(dst, src, svid);
+ fieldp_copy(dst, src, constellation);
+ fieldp_copy(dst, src, c_n0_dbhz);
+ fieldp_copy(dst, src, elevation);
+ fieldp_copy(dst, src, azimuth);
+ fieldp_copy(dst, src, flags);
+ fieldp_copy(&gss.gnss_sv_list[i], src, carrier_frequency);
+ mnlDebugData.satelliteDataArray[i].svid = gss.gnss_sv_list[i].legacySvInfo.svid;
+ mnlDebugData.satelliteDataArray[i].constellation = gss.gnss_sv_list[i].legacySvInfo.constellation;
+ }
+ g_gpshal_ctx.gps_cbs->gnss_sv_status_cb(&gss);
+}
+
+static void update_nmea(int64_t timestamp, const char* nmea, int length) {
+ /*LOGD(" timestamp=%lld nmea=[%s] length=%d",
+ timestamp, nmea, length);*/
+ g_gpshal_ctx.gps_cbs->nmea_cb(timestamp, nmea, length);
+}
+static void update_gps_capabilities(gps_capabilites capabilities) {
+ LOGD(" capabilities=0x%x", capabilities);
+ g_gpshal_ctx.gps_cbs->set_capabilities_cb(capabilities);
+}
+
+static void update_gps_measurements(gps_data data) {
+ // GPSHAL_DEBUG_FUNC_SCOPE;
+ size_t i;
+ GpsData gd;
+ //dump_gps_data(data);
+ gd.size = sizeof(gd);
+ field_copy(gd, data, measurement_count);
+ for (i = 0; i < GPS_MAX_MEASUREMENT; i++) {
+ GpsMeasurement* dst = &gd.measurements[i];
+ gps_measurement* src = &data.measurements[i];
+ dst->size = sizeof(*dst);
+ fieldp_copy(dst, src, flags);
+ fieldp_copy(dst, src, prn);
+ fieldp_copy(dst, src, time_offset_ns);
+ fieldp_copy(dst, src, state);
+ fieldp_copy(dst, src, received_gps_tow_ns);
+ fieldp_copy(dst, src, received_gps_tow_uncertainty_ns);
+ fieldp_copy(dst, src, c_n0_dbhz);
+ fieldp_copy(dst, src, pseudorange_rate_mps);
+ fieldp_copy(dst, src, pseudorange_rate_uncertainty_mps);
+ fieldp_copy(dst, src, accumulated_delta_range_state);
+ fieldp_copy(dst, src, accumulated_delta_range_m);
+ fieldp_copy(dst, src, accumulated_delta_range_uncertainty_m);
+ fieldp_copy(dst, src, pseudorange_m);
+ fieldp_copy(dst, src, pseudorange_uncertainty_m);
+ fieldp_copy(dst, src, code_phase_chips);
+ fieldp_copy(dst, src, code_phase_uncertainty_chips);
+ fieldp_copy(dst, src, carrier_frequency_hz);
+ fieldp_copy(dst, src, carrier_cycles);
+ fieldp_copy(dst, src, carrier_phase);
+ fieldp_copy(dst, src, carrier_phase_uncertainty);
+ fieldp_copy(dst, src, loss_of_lock);
+ fieldp_copy(dst, src, bit_number);
+ fieldp_copy(dst, src, time_from_last_bit_ms);
+ fieldp_copy(dst, src, doppler_shift_hz);
+ fieldp_copy(dst, src, doppler_shift_uncertainty_hz);
+ fieldp_copy(dst, src, multipath_indicator);
+ fieldp_copy(dst, src, snr_db);
+ fieldp_copy(dst, src, elevation_deg);
+ fieldp_copy(dst, src, elevation_uncertainty_deg);
+ fieldp_copy(dst, src, azimuth_deg);
+ fieldp_copy(dst, src, azimuth_uncertainty_deg);
+ fieldp_copy(dst, src, used_in_fix);
+ }
+
+ // To do things like field_copy(gd, data, clock)
+ {
+ GpsClock* dst = &gd.clock;
+ gps_clock* src = &data.clock;
+ dst->size = sizeof(*dst);
+ fieldp_copy(dst, src, flags);
+ fieldp_copy(dst, src, leap_second);
+ fieldp_copy(dst, src, type);
+ fieldp_copy(dst, src, time_ns);
+ fieldp_copy(dst, src, time_uncertainty_ns);
+ fieldp_copy(dst, src, full_bias_ns);
+ fieldp_copy(dst, src, bias_ns);
+ fieldp_copy(dst, src, bias_uncertainty_ns);
+ fieldp_copy(dst, src, drift_nsps);
+ fieldp_copy(dst, src, drift_uncertainty_nsps);
+ }
+ g_gpshal_ctx.meas_cbs->measurement_callback(&gd);
+}
+
+static void update_gnss_measurements(gnss_data data) {
+ size_t i;
+ GnssData_ext gd;
+ //dump_gnss_data(data);
+ gd.size = sizeof(gd);
+ field_copy(gd, data, measurement_count);
+ for (i = 0; i < MTK_HAL_GNSS_MAX_MEASUREMENT; i++) {
+ GnssMeasurement* dst = &gd.measurements[i].legacyMeasurement;
+ gnss_measurement* src = &data.measurements[i];
+ dst->size = sizeof(*dst);
+ fieldp_copy(dst, src, flags);
+ fieldp_copy(dst, src, svid);
+ fieldp_copy(dst, src, constellation);
+ fieldp_copy(dst, src, time_offset_ns);
+ fieldp_copy(dst, src, state);
+ fieldp_copy(dst, src, received_sv_time_in_ns);
+ fieldp_copy(dst, src, received_sv_time_uncertainty_in_ns);
+ fieldp_copy(dst, src, c_n0_dbhz);
+ fieldp_copy(dst, src, pseudorange_rate_mps);
+ fieldp_copy(dst, src, pseudorange_rate_uncertainty_mps);
+ fieldp_copy(dst, src, accumulated_delta_range_state);
+ fieldp_copy(dst, src, accumulated_delta_range_m);
+ fieldp_copy(dst, src, accumulated_delta_range_uncertainty_m);
+ fieldp_copy(dst, src, carrier_frequency_hz);
+ fieldp_copy(dst, src, carrier_cycles);
+ fieldp_copy(dst, src, carrier_phase);
+ fieldp_copy(dst, src, carrier_phase_uncertainty);
+ fieldp_copy(dst, src, multipath_indicator);
+ fieldp_copy(dst, src, snr_db);
+ fieldp_copy(&gd.measurements[i], src, agc_level_db);
+ }
+ // To do things like field_copy(gd, data, clock)
+ {
+ GnssClock* dst = &gd.clock;
+ gnss_clock* src = &data.clock;
+ dst->size = sizeof(*dst);
+ fieldp_copy(dst, src, flags);
+ fieldp_copy(dst, src, leap_second);
+ fieldp_copy(dst, src, time_ns);
+ fieldp_copy(dst, src, time_uncertainty_ns);
+ fieldp_copy(dst, src, full_bias_ns);
+ fieldp_copy(dst, src, bias_ns);
+ fieldp_copy(dst, src, bias_uncertainty_ns);
+ fieldp_copy(dst, src, drift_nsps);
+ fieldp_copy(dst, src, drift_uncertainty_nsps);
+ fieldp_copy(dst, src, hw_clock_discontinuity_count);
+ }
+
+ g_gpshal_ctx.meas_cbs->gnss_measurement_callback(&gd);
+}
+static void update_gps_navigation(gps_nav_msg msg) {
+ // GPSHAL_DEBUG_FUNC_SCOPE;
+ GpsNavigationMessage gnm;
+ //dump_gps_nav_msg(msg);
+ gnm.size = sizeof(gnm);
+ field_copy(gnm, msg, prn);
+ field_copy(gnm, msg, type);
+ field_copy(gnm, msg, status);
+ field_copy(gnm, msg, message_id);
+ field_copy(gnm, msg, submessage_id);
+ field_copy(gnm, msg, data_length);
+ gnm.data = (uint8_t*) msg.data;
+ g_gpshal_ctx.navimsg_cbs->navigation_message_callback(&gnm);
+}
+
+static void update_gnss_navigation(gnss_nav_msg msg) {
+ GnssNavigationMessage gnm;
+ //dump_gnss_nav_msg(msg);
+ gnm.size = sizeof(gnm);
+ field_copy(gnm, msg, svid);
+ field_copy(gnm, msg, type);
+ field_copy(gnm, msg, status);
+ field_copy(gnm, msg, message_id);
+ field_copy(gnm, msg, submessage_id);
+ field_copy(gnm, msg, data_length);
+ gnm.data = (uint8_t*) msg.data;
+ g_gpshal_ctx.navimsg_cbs->gnss_navigation_message_callback(&gnm);
+}
+
+static void request_wakelock() {
+ // GPSHAL_DEBUG_FUNC_SCOPE;
+ g_gpshal_ctx.gps_cbs->acquire_wakelock_cb();
+}
+static void release_wakelock() {
+ // GPSHAL_DEBUG_FUNC_SCOPE;
+ g_gpshal_ctx.gps_cbs->release_wakelock_cb();
+}
+static void request_utc_time() {
+ // GPSHAL_DEBUG_FUNC_SCOPE;
+ g_gpshal_ctx.gps_cbs->request_utc_time_cb();
+}
+static void request_data_conn(struct sockaddr_storage* addr) {
+ // GPSHAL_DEBUG_FUNC_SCOPE;
+ UNUSED(addr);
+ AGpsStatus as;
+ as.size = sizeof(AGpsStatus); // our imp supports v3
+ as.type = AGPS_TYPE_SUPL;
+ as.status = GPS_REQUEST_AGPS_DATA_CONN;
+ // as.ipaddr = INADDR_NONE; // not used in v3
+ as.addr = *addr;
+ g_gpshal_ctx.agps_cbs->status_cb(&as);
+}
+static void release_data_conn() {
+ // GPSHAL_DEBUG_FUNC_SCOPE;
+ AGpsStatus as;
+ as.size = sizeof(AGpsStatus_v1); // use v1 size to omit optional fields
+ as.type = AGPS_TYPE_SUPL;
+ as.status = GPS_RELEASE_AGPS_DATA_CONN;
+ g_gpshal_ctx.agps_cbs->status_cb(&as);
+}
+static void request_ni_notify(int session_id, agps_notify_type type, const char* requestor_id,
+ const char* client_name, ni_encoding_type requestor_id_encoding,
+ ni_encoding_type client_name_encoding) {
+ /*LOGD(" session_id=%d type=%d requestor_id=[%s] client_name=[%s] requestor_id_encoding=%d client_name_encoding=%d",
+ session_id, type, requestor_id, client_name, requestor_id_encoding, client_name_encoding);*/
+ GpsNiNotification gnn;
+ gnn.size = sizeof(gnn);
+ gnn.notification_id = session_id;
+ gnn.ni_type = GPS_NI_TYPE_UMTS_SUPL;
+ switch (type) {
+ case AGPS_NOTIFY_TYPE_NOTIFY_ONLY:
+ gnn.notify_flags = GPS_NI_NEED_NOTIFY;
+ break;
+ case AGPS_NOTIFY_TYPE_NOTIFY_ALLOW_NO_ANSWER:
+ gnn.notify_flags = GPS_NI_NEED_NOTIFY|GPS_NI_NEED_VERIFY;
+ break;
+ case AGPS_NOTIFY_TYPE_NOTIFY_DENY_NO_ANSWER:
+ gnn.notify_flags = GPS_NI_NEED_NOTIFY|GPS_NI_NEED_VERIFY;
+ break;
+ case AGPS_NOTIFY_TYPE_PRIVACY:
+ gnn.notify_flags = GPS_NI_PRIVACY_OVERRIDE;
+ break;
+ default:
+ gnn.notify_flags = 0;
+ }
+ gnn.timeout = 8;
+ gnn.default_response = GPS_NI_RESPONSE_NORESP;
+ MNLD_STRNCPY(gnn.requestor_id, requestor_id,sizeof(gnn.requestor_id));
+ MNLD_STRNCPY(gnn.text,client_name,sizeof(gnn.text));
+ gnn.requestor_id_encoding = requestor_id_encoding;
+ gnn.text_encoding = client_name_encoding;
+ gnn.extras[0] = 0; // be an empty string ""
+ g_gpshal_ctx.gpsni_cbs->notify_cb(&gnn);
+}
+static void request_set_id(request_setid flags) {
+ //LOGD(" flags=0x%x", flags);
+ if (g_gpshal_ctx.agpsril_cbs) {
+ g_gpshal_ctx.agpsril_cbs->request_setid(flags);
+ }
+}
+static void request_ref_loc(request_refloc flags) {
+ //LOGD(" flags=0x%x", flags);
+ if (g_gpshal_ctx.agpsril_cbs) {
+ g_gpshal_ctx.agpsril_cbs->request_refloc(flags);
+ }
+}
+static void output_vzw_debug(const char* str) {
+ int len;
+ len = strlen(str)+1;
+ if (len > VZW_DEBUG_STRING_MAXLEN) {
+ len = VZW_DEBUG_STRING_MAXLEN;
+ }
+ LOGD("len=%d str=%s", len, str);
+ VzwDebugData vzwdebugdata;
+ vzwdebugdata.size = sizeof(VzwDebugData);
+ memcpy(vzwdebugdata.vzw_msg_data, str, len);
+ vzwdebugdata.vzw_msg_data[VZW_DEBUG_STRING_MAXLEN - 1] = 0;
+
+ if (g_gpshal_ctx.vzw_debug_cbs) {
+ g_gpshal_ctx.vzw_debug_cbs->vzw_debug_cb(&vzwdebugdata);
+ }
+}
+
+static void update_gnss_name(const char* name, int length) {
+ LOGD("length=%d, name=%s", length, name);
+ if (g_gpshal_ctx.gps_cbs) {
+ g_gpshal_ctx.gps_cbs->set_name_cb(name, length);
+ }
+}
+
+static void request_nlp(bool independentFromGnss) {
+ LOGD("request nlp[%d]", independentFromGnss);
+ if (g_gpshal_ctx.gps_cbs) {
+ g_gpshal_ctx.gps_cbs->request_location_cb(independentFromGnss);
+ }
+}
+
+static mnl2hal_interface gpshal_mnl2hal_interface = {
+ update_mnld_reboot,
+ update_location,
+ update_gps_status,
+ update_gps_sv,
+ update_nmea,
+ update_gps_capabilities,
+ update_gps_measurements,
+ update_gps_navigation,
+ update_gnss_measurements,
+ update_gnss_navigation,
+ request_wakelock,
+ release_wakelock,
+ request_utc_time,
+ request_data_conn,
+ release_data_conn,
+ request_ni_notify,
+ request_set_id,
+ request_ref_loc,
+ output_vzw_debug,
+ update_gnss_name,
+ request_nlp,
+};
+
+//=========================================================
+
+void gpshal_worker_thread(void *arg) {
+ // GPSHAL_DEBUG_FUNC_SCOPE;
+ struct epoll_event events[MAX_EPOLL_EVENT];
+ UNUSED(arg);
+
+ while (true) {
+ int i;
+ int n;
+
+ n = epoll_wait(g_gpshal_ctx.fd_worker_epoll, events, MAX_EPOLL_EVENT, -1);
+
+ if (n == -1) {
+ if (errno == EINTR) {
+ continue;
+ } else {
+ LOGE("epoll_wait failure reason=[%s]%d", strerror(errno), errno);
+ return;
+ }
+ }
+
+ for (i = 0; i < n; i++) {
+ if (events[i].data.fd == g_gpshal_ctx.fd_mnl2hal) {
+ if (events[i].events & EPOLLIN) {
+ mnl2hal_hdlr(g_gpshal_ctx.fd_mnl2hal,
+ &gpshal_mnl2hal_interface);
+ }
+ } else {
+ LOGE("%s() unknown fd=%d",
+ __func__, events[i].data.fd);
+ }
+ }
+ } // of while (true)
+}
diff --git a/src/connectivity/gps/gps_hal/src/gpsinf.c b/src/connectivity/gps/gps_hal/src/gpsinf.c
new file mode 100644
index 0000000..b8cb228
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/src/gpsinf.c
@@ -0,0 +1,395 @@
+/* Copyright Statement:
+ *
+ * This software/firmware and related documentation ("MediaTek Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to MediaTek Inc. and/or its licensors.
+ * Without the prior written permission of MediaTek inc. and/or its licensors,
+ * any reproduction, modification, use or disclosure of MediaTek Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ *
+ * MediaTek Inc. (C) 2016. All rights reserved.
+ *
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
+ * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
+ * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
+ *
+ * The following software/firmware and/or related documentation ("MediaTek Software")
+ * have been modified by MediaTek Inc. All revisions are subject to any receiver's
+ * applicable license agreements with MediaTek Inc.
+ */
+#include "gpshal.h"
+#include "hal2mnl_interface.h"
+#include "mtk_lbs_utility.h"
+#include "gpshal_param_check.h"
+#include "mtk_auto_log.h"
+
+#ifdef LOG_TAG
+#undef LOG_TAG
+#define LOG_TAG "gpsinf"
+#endif
+
+extern DebugData mnlDebugData; //for GNSS HIDL v1.1 GPS debug interface
+
+//=========================================================
+
+extern struct hw_module_t HAL_MODULE_INFO_SYM;
+
+//=========================================================
+// Gps Measurement Interface
+
+// Thread: BackgroundThread
+// GpsMeasurementsProvider uses GpsLocationProvider's handler
+static int measinf_init(GpsMeasurementCallbacks_ext* callbacks, bool enableFullTracking) {
+ g_gpshal_ctx.meas_cbs = callbacks;
+ int ret = hal2mnl_set_gps_measurement(true, enableFullTracking);
+ return (ret > 0)?
+ GPS_GEOFENCE_OPERATION_SUCCESS :
+ GPS_GEOFENCE_ERROR_GENERIC;
+}
+
+// Thread: BackgroundThread
+// GpsMeasurementsProvider uses GpsLocationProvider's handler
+static void measinf_close(void) {
+ hal2mnl_set_gps_measurement(false, false);
+}
+
+const GpsMeasurementInterface_ext mtk_gps_meas_inf = {
+ sizeof(GpsMeasurementInterface_ext),
+ measinf_init,
+ measinf_close
+};
+
+//=========================================================
+// Gps Navigation Message Interface
+
+// Thread: BackgroundThread
+// GpsNavigationMessageProvider uses GpsLocationProvider's handler
+static int navimsginf_init(GpsNavigationMessageCallbacks* callbacks) {
+ g_gpshal_ctx.navimsg_cbs = callbacks;
+ int ret = hal2mnl_set_gps_navigation(true);
+ return (ret > 0)?
+ GPS_NAVIGATION_MESSAGE_OPERATION_SUCCESS :
+ GPS_NAVIGATION_MESSAGE_ERROR_GENERIC;
+}
+
+// Thread: BackgroundThread
+// GpsNavigationMessageProvider uses GpsLocationProvider's handler
+static void navimsginf_close(void) {
+ hal2mnl_set_gps_navigation(false);
+}
+
+const GpsNavigationMessageInterface mtk_navi_msg_inf = {
+ sizeof(GpsNavigationMessageInterface),
+ navimsginf_init,
+ navimsginf_close
+};
+
+static int vzwdebuginf_init(VzwDebugCallbacks* callbacks) {
+ g_gpshal_ctx.vzw_debug_cbs = callbacks;
+ return 0;
+}
+
+static void vzwdebuginf_set(bool enabled) {
+ hal2mnl_set_vzw_debug(enabled);
+}
+
+const VzwDebugInterface mtk_vzw_debug_inf = {
+ sizeof(VzwDebugInterface),
+ vzwdebuginf_init,
+ vzwdebuginf_set
+};
+
+static void gnss_configuration_update(const char* config_data, int32_t length) {
+ hal2mnl_update_gnss_config(config_data, length);
+}
+
+static void gnss_setBlacklist(long long* blacklist, int32_t size) {
+ //hal2mnl_setBlacklist(blacklist, size);
+ UNUSED(blacklist);
+ UNUSED(size);
+}
+
+const GnssConfigurationInterface_ext mtk_gnss_config_inf = {
+ sizeof(GnssConfigurationInterface_ext),
+ gnss_configuration_update,
+ gnss_setBlacklist
+};
+
+static bool get_internal_state(DebugData* debugData) {
+ memcpy(debugData, &mnlDebugData, sizeof(DebugData));
+ return true;
+}
+
+const GpsDebugInterface_ext mtk_gps_debug_inf = {
+ sizeof(GpsDebugInterface_ext),
+ get_internal_state
+};
+
+//=========================================================
+// Implementation of
+// Gps Iterface
+
+// Thread: Main thread of system server
+// Call seq:
+// LocationManagerService.systemRunning
+// LocationManagerService.loadProvidersLocked
+// GpsLocationProvider.static
+// android_location_GpsLocationProvider_class_init_native
+// sGpsInterface->get_extension
+static const void* gpsinf_get_extension(const char* name) {
+#ifndef CONFIG_GPS_MT3303
+ if (strcmp(name, AGPS_INTERFACE) == 0) {
+ return &mtk_agps_inf;
+ }
+ if (strcmp(name, GPS_NI_INTERFACE) == 0) {
+ return &mtk_gps_ni_inf;
+ }
+ if (strcmp(name, AGPS_RIL_INTERFACE) == 0) {
+ return &mtk_agps_ril_inf;
+ }
+#endif
+ if (strcmp(name, GPS_MEASUREMENT_INTERFACE) == 0) {
+ return &mtk_gps_meas_inf;
+ }
+ if (strcmp(name, GPS_NAVIGATION_MESSAGE_INTERFACE) == 0) {
+ return &mtk_navi_msg_inf;
+ }
+
+ if (strcmp(name, VZW_DEBUG_INTERFACE) == 0) {
+ return &mtk_vzw_debug_inf;
+ }
+
+#if 0
+ if (strcmp(name, GPS_GEOFENCING_INTERFACE) == 0) {
+ return &mtkGeofence_inf;
+ }
+#endif
+
+#if 0 // not supported, even in our MP branches
+ if (!strcmp(name, GPS_GEOFENCING_INTERFACE))
+ return &mtk_gps_geofencing_inf;
+#endif
+
+ if (!strcmp(name, GNSS_CONFIGURATION_INTERFACE))
+ return &mtk_gnss_config_inf;
+
+#if 0 // not ready, even in Google's GPS JNI
+ if (strcmp(name, SUPL_CERTIFICATE_INTERFACE) == 0) {
+ return &mtk_supl_cert_inf;
+ }
+#endif
+#if 0 // Similar to our EPO but we will do it in mnld.
+ if (!strcmp(name, GPS_XTRA_INTERFACE))
+ return &mtk_gps_xtra_inf;
+#endif
+ if (!strcmp(name, GPS_DEBUG_INTERFACE)) {
+ return &mtk_gps_debug_inf;
+ }
+ return NULL; // unsupported extension
+}
+
+// Thread: BackgroundThread
+// Its looper is shared by a lot of services including
+// LocationManagerService's handler
+// GpsLocationProvider's handler
+// GpsLocationProvider's broadcast receiver
+// Call seq:
+// GpsLocationProvider.ProviderHandler.handleMessage
+// GpsLocationProvider.handleEnable
+// GpsLocationProvider.native_init
+// android_location_GpsLocationProvider_init
+// sGpsInterface->init
+static int gpsinf_init(GpsCallbacks_ext* callbacks) {
+ // GPSHAL_DEBUG_FUNC_SCOPE2(g_gpshal_ctx.mutex_gps_state_intent);
+ if (gpshal_gpscbs_save(callbacks) != 0) {
+ return -1; // error
+ }
+
+ gpshal_set_gps_state_intent(GPSHAL_STATE_INIT);
+ gpshal2mnl_gps_init();
+ return 0; // OK to init
+}
+
+// Thread: BackgroundThread
+static int gpsinf_start(void) {
+ // GPSHAL_DEBUG_FUNC_SCOPE2(g_gpshal_ctx.mutex_gps_state_intent);
+ gpshal_set_gps_state_intent(GPSHAL_STATE_START);
+ gpshal2mnl_gps_start();
+ return 0; // OK to start
+}
+
+// Thread: BackgroundThread
+static int gpsinf_stop(void) {
+ // GPSHAL_DEBUG_FUNC_SCOPE2(g_gpshal_ctx.mutex_gps_state_intent);
+ gpshal_set_gps_state_intent(GPSHAL_STATE_STOP);
+ gpshal2mnl_gps_stop();
+ return 0; // OK to stop
+}
+
+// Thread: BackgroundThread
+static void gpsinf_cleanup(void) {
+ // GPSHAL_DEBUG_FUNC_SCOPE2(g_gpshal_ctx.mutex_gps_state_intent);
+ gpshal_set_gps_state_intent(GPSHAL_STATE_CLEANUP);
+ gpshal2mnl_gps_cleanup();
+}
+
+// Thread: BackgroundThread
+static int gpsinf_inject_time(GpsUtcTime time, int64_t timeReference, int uncertainty) {
+ hal2mnl_gps_inject_time(time, timeReference, uncertainty);
+ return 0; // 0:ok, non-zero: error; but GPS JNI will ignore it
+}
+
+// Thread: BackgroundThread
+// NetworkLocationListener uses the looper of GpsLocationProvider's handler
+static int gpsinf_inject_location(
+ double latitude,
+ double longitude,
+ float accuracy) {
+ hal2mnl_gps_inject_location(latitude, longitude, accuracy);
+ return 0; // 0:ok, non-zero: error; but GPS JNI will ignore it
+}
+
+// Thread: Binder Thread of LocationManagerService
+//
+// Call seq:
+// LocationManagerService.sendExtraCommand
+// GpsLocationProvider.sendExtraCommand
+// GpsLocationProvider.deleteAidingData
+// GpsLocationProvider.native_delete_aiding_data
+// android_location_GpsLocationProvider_delete_aiding_data
+// sGpsInterface->delete_aiding_data
+static void gpsinf_delete_aiding_data(GpsAidingData flags) {
+ hal2mnl_gps_delete_aiding_data(flags);
+}
+
+// Thread: BackgroundThread or ???
+// GpsLocationProvider's handler may call it
+// GpsLocationProvider's mBroadcastReceiver may call it (PowerManager's intent)
+static int gpsinf_set_position_mode(
+ GpsPositionMode mode,
+ GpsPositionRecurrence recurrence,
+ uint32_t min_interval,
+ uint32_t preferred_accuracy,
+ uint32_t preferred_time,
+ bool lowPowerMode) {
+ hal2mnl_gps_set_position_mode(
+ mode,
+ recurrence,
+ min_interval,
+ preferred_accuracy,
+ preferred_time,
+ lowPowerMode);
+ return 0; // 0:ok, non-zero: error; GLP will show log if error
+}
+
+static int gpsinf_inject_fused_location(
+ double latitude,
+ double longitude,
+ float accuracy) {
+ // TODO: hal2mnl_gps_inject_fused_location(latitude, longitude, accuracy);
+ UNUSED(latitude);
+ UNUSED(longitude);
+ UNUSED(accuracy);
+ return 0; // 0:ok, non-zero: error; but GPS JNI will ignore it
+}
+
+static const GpsInterface_ext mtk_gps_inf = {
+ sizeof(GpsInterface_ext),
+ gpsinf_init,
+ gpsinf_start,
+ gpsinf_stop,
+ gpsinf_cleanup,
+ gpsinf_inject_time,
+ gpsinf_inject_location,
+ gpsinf_delete_aiding_data,
+ gpsinf_set_position_mode,
+ gpsinf_get_extension,
+ gpsinf_inject_fused_location,
+};
+
+#ifdef __ANDROID_OS__
+//=========================================================
+// Between
+// Gps Interface
+// Hardware Module Interface
+
+static const GpsInterface_ext* gps_device__get_gps_interface(
+ __unused struct gps_device_t_ext* device) {
+ GPS_DEVICE__GET_GPS_INTERFACE__CHECK_PARAM;
+ hal2mnl_hal_reboot();
+ return &mtk_gps_inf;
+}
+
+static const struct gps_device_t_ext gps_device = {
+ .common = { // hw_device_t
+ .tag = HARDWARE_DEVICE_TAG,
+ .version = 0, // GPS JNI will not use it
+ .module = &HAL_MODULE_INFO_SYM,
+ .reserved = {0},
+ .close = NULL // GPS JNI will not call it
+ },
+ .get_gps_interface = gps_device__get_gps_interface
+};
+
+//=========================================================
+// Implementation of
+// Hardware Module Interface
+
+static int gps_hw_module_open(
+ __unused const struct hw_module_t* module,
+ __unused char const* id,
+ struct hw_device_t** device) {
+ GPS_HW_MODULE_OPEN__CHECK_PARAM;
+ *device = (struct hw_device_t*)&gps_device;
+ return 0; // OK: refer to the cpp of GPS JNI
+}
+
+static struct hw_module_methods_t gps_hw_module_methods = {
+ .open = gps_hw_module_open
+};
+
+struct hw_module_t HAL_MODULE_INFO_SYM = {
+ .tag = HARDWARE_MODULE_TAG,
+ .version_major = 1,
+ .version_minor = 0,
+ .id = GPS_HARDWARE_MODULE_ID,
+ .name = "MediaTek GPS Hardware Module",
+ .author = "MediaTek, Inc.",
+ .methods = &gps_hw_module_methods,
+ .dso = NULL,
+ .reserved = {0}
+};
+#else
+//=========================================================
+// Between
+// Gps Interface
+// Hardware Module Interface
+
+const GpsInterface_ext* gps_device__get_gps_interface(struct gps_device_t_ext* device)
+{
+ LOGD("welcome enter libgpshal world\n");
+ hal2mnl_hal_reboot();
+
+ return &mtk_gps_inf;
+}
+
+const struct gps_device_t_ext linux_gps_device = {
+ .get_gps_interface = gps_device__get_gps_interface
+};
+
+#endif //__ANDROID_OS__
diff --git a/src/connectivity/gps/gps_hal/src/gpsinf3337.c b/src/connectivity/gps/gps_hal/src/gpsinf3337.c
new file mode 100644
index 0000000..d59291c
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/src/gpsinf3337.c
@@ -0,0 +1,2290 @@
+/* Copyright Statement:
+ *
+ * This software/firmware and related documentation ("MediaTek Software") are
+ * protected under relevant copyright laws. The information contained herein
+ * is confidential and proprietary to MediaTek Inc. and/or its licensors.
+ * Without the prior written permission of MediaTek inc. and/or its licensors,
+ * any reproduction, modification, use or disclosure of MediaTek Software,
+ * and information contained herein, in whole or in part, shall be strictly prohibited.
+ *
+ * MediaTek Inc. (C) 2010. All rights reserved.
+ *
+ * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+ * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
+ * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
+ * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
+ * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
+ * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
+ * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
+ * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
+ * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
+ * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
+ * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+ * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
+ * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
+ * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
+ * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
+ * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
+ *
+ * The following software/firmware and/or related documentation ("MediaTek Software")
+ * have been modified by MediaTek Inc. All revisions are subject to any receiver's
+ * applicable license agreements with MediaTek Inc.
+ */
+#include <errno.h>
+#include <pthread.h>
+#include <fcntl.h>
+#include <sys/epoll.h>
+#include <math.h>
+#include <time.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <netdb.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <semaphore.h>
+#include <sys/ioctl.h>
+#include <sys/time.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <signal.h>
+#include <linux/mtk_agps_common.h>
+#include <cutils/android_filesystem_config.h>
+
+#include "hardware/gps_mtk.h"
+#include "gpshal.h"
+#include "mtk_lbs_utility.h"
+#include "data_coder.h"
+#include <termios.h>
+#include "mtk_auto_log.h"
+
+#define LOCATION_NLP_FIX MTK_GPS_DATA_PATH"LOCATION.DAT"
+#define LOG_TAG "gps_mtk_3337"
+
+#if ANDROID_MNLD_PROP_SUPPORT
+#include <cutils/properties.h>
+#endif
+
+#ifdef HAVE_LIBC_SYSTEM_PROPERTIES
+#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
+#include <sys/_system_properties.h>
+#endif
+
+
+
+/* the name of the controlled socket */
+#define GPS_POWER_NAME "/dev/gps"
+#define GPS_TTY_NAME "/dev/ttyMT1"
+
+#define MNLD_HAL2GPS "/dev/mt3337_gpsonly"
+#define MNL_CONFIG_STATUS "persist.vendor.radio.mnl.prop"
+
+#define PMTK_SOCKET_COM_PORT 49995
+#define PMTK_SERVER_BACKLOG 5
+#define INVALID_SOCKET -1
+#define INVALID_FD -1
+#define GPS_OP "AT%GPS"
+#define GNSS_OP "AT%GNSS"
+#define GPS_AT_ACK_SIZE 60
+
+#define MTKEPO_SV_NUMBER 32
+#define MTKEPO_RECORD_SIZE 72
+#define MTKEPO_SEGMENT_NUM (30 * 4)
+
+#define GPS_DEBUG 1
+#define NEMA_DEBUG 0 /*the flag works if GPS_DEBUG is defined*/
+#if GPS_DEBUG
+#define TRC(f) ALOGD("%s", __func__)
+#define ERR(f, ...) ALOGE("%s: line = %d" f, __func__,__LINE__, ##__VA_ARGS__)
+#define WAN(f, ...) ALOGW("%s: line = %d" f, __func__, __LINE__,##__VA_ARGS__)
+#define DBG(f, ...) ALOGD("%s: line = %d" f, __func__, __LINE__,##__VA_ARGS__)
+#define VER(f, ...) ((void)0) //((void)0)//
+#else
+# define DBG(...) ((void)0)
+# define VER(...) ((void)0)
+#endif
+
+#define GPS_POWER_IOCTL _IOW('G', 0, int)
+static int flag_unlock = 0;
+GpsStatus sta;
+
+extern struct hw_module_t HAL_MODULE_INFO_SYM;
+
+typedef unsigned int UINT4;
+typedef signed int INT4;
+typedef unsigned char UINT8;
+typedef signed char INT8;
+typedef unsigned short int UINT16;
+typedef signed short int INT16;
+typedef unsigned int UINT32;
+typedef signed int INT32;
+typedef signed long long INT64;
+
+#pragma pack(4) // Align by 4 byte
+typedef struct
+{
+ UINT32 size;
+ UINT16 flag;
+ INT16 leapsecond;
+ UINT8 type;
+ INT64 TimeInNs;
+ double TimeUncertaintyInNs;
+ INT64 FullBiasInNs;
+ double BiasInNs;
+ double BiasUncertaintyInNs;
+ double DriftInNsPerSec;
+ double DriftUncertaintyInNsPerSec;
+}MTK_GPS_CLOCK;
+#pragma pack()
+
+typedef struct{
+ GpsUtcTime time;
+ int64_t timeReference;
+ int uncertainty;
+} ntp_context;
+
+typedef struct{
+ double latitude;
+ double longitude;
+ float accuracy;
+ struct timespec ts;
+ unsigned char type;
+ unsigned char started;
+} nlp_context;
+
+/*****************************************************************************/
+/* MTK device control */
+/*****************************************************************************/
+enum {
+ MNL_CMD_UNKNOWN = -1,
+ /*command send from GPS HAL*/
+ MNL_CMD_INIT = 0x00,
+ MNL_CMD_CLEANUP = 0x01,
+ MNL_CMD_STOP = 0x02,
+ MNL_CMD_START = 0x03,
+ MNL_CMD_RESTART = 0x04, /*restart MNL process*/
+ MNL_CMD_RESTART_HOT = 0x05, /*restart MNL by PMTK command: hot start*/
+ MNL_CMD_RESTART_WARM = 0x06, /*restart MNL by PMTK command: warm start*/
+ MNL_CMD_RESTART_COLD = 0x07, /*restart MNL by PMTK command: cold start*/
+ MNL_CMD_RESTART_FULL = 0x08, /*restart MNL by PMTK command: full start*/
+ MNL_CMD_RESTART_AGPS = 0x09, /*restart MNL by PMTK command: AGPS start*/
+ MNL_CMD_GPSMEASUREMENT_INIT = 0x15,
+ MNL_CMD_GPSMEASUREMENT_CLOSE = 0x16,
+
+
+ MNL_CMD_GPSNAVIGATION_INIT = 0x17,
+ MNL_CMD_GPSNAVIGATION_CLOSE = 0x18,
+ MNL_CMD_GPS_LOG_WRITE = 0x40,
+
+ MNL_CMD_ENABLE_AGPS_DEBUG = 0x42,
+ MNL_CMD_DISABLE_AGPS_DEBUG = 0x43,
+};
+
+enum {
+ HAL_CMD_STOP_UNKNOWN = -1,
+ HAL_CMD_MNL_DIE = 0x41,
+ HAL_CMD_GPS_ICON = 0x42,
+
+ MNL_CMD_GPS_INJECT_TIME = 0x46,
+ MNL_CMD_GPS_INJECT_LOCATION = 0x47,
+ MNL_CMD_GPS_INJECT_TIME_REQ = 0x48,
+ MNL_CMD_GPS_INJECT_LOCATION_REQ = 0x49,
+
+ MNL_CMD_GPS_NLP_LOCATION_REQ = 0x4a,
+ HAL_CMD_MEASUREMENT= 0x76,
+ HAL_CMD_NAVIGATION= 0x77,
+ HAL_CMD_SWITCH_AGPS_DEBUG_DONE = 0x44,
+ HAL_CMD_SWITCH_AGPS_DEBUG_FAIL = 0X45,
+};
+
+
+
+#define M_START 0
+#define M_STOP 1
+#define M_CLEANUP 2
+#define M_INIT 3
+#define M_THREAD_EXIT 4
+#define M_MNLDIE 5
+typedef struct sync_lock
+{
+ pthread_mutex_t mutx;
+ pthread_cond_t con;
+ int condtion;
+}SYNC_LOCK_T;
+
+static SYNC_LOCK_T lock_for_sync[] = {{PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER, 0},
+ {PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER, 0},
+ {PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER, 0},
+ {PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER, 0},
+ {PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER, 0},
+ {PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER, 0}};
+
+const char* gps_native_thread = "GPS NATIVE THREAD";
+const char* gps_pmtk_thread = "GPS PMTK THREAD";
+const char* gps_nmea_read_thread = "GPS NMEA READ THREAD";
+const char* gps_send_epo_thread = "GPS SEND EPO THREAD";
+static GpsCallbacks callback_backup;
+static int start_flag = 0;
+static int g_delete_aiding_data_flag = 0;
+
+//for different SV parse
+typedef enum{
+ UNKNOWN_SV = 0,
+ GPS_SV,
+ GLONASS_SV,
+ BDS_SV,
+ GALILEO_SV,
+}SV_TYPE;
+static float report_time_interval = 0;
+static int started = 0;
+
+//#define NMEA_MAX_SIZE 83
+#define NMEA_MAX_SIZE 255
+/*maximum number of SV information in GPGSV*/
+#define NMEA_MAX_SV_INFO 4
+#define LOC_FIXED(pNmeaReader) ((pNmeaReader->fix_mode == 2) || (pNmeaReader->fix_mode ==3))
+typedef struct {
+ int pos;
+ int overflow;
+ int utc_year;
+ int utc_mon;
+ int utc_day;
+ int utc_diff;
+ GpsLocation fix;
+
+ /*
+ * The fix flag extracted from GPGSA setence: 1: No fix; 2 = 2D; 3 = 3D
+ * if the fix mode is 0, no location will be reported via callback
+ * otherwise, the location will be reported via callback
+ */
+ int fix_mode;
+ /*
+ * Indicate that the status of callback handling.
+ * The flag is used to report GPS_STATUS_SESSION_BEGIN or GPS_STATUS_SESSION_END:
+ * (0) The flag will be set as true when callback setting is changed via nmea_reader_set_callback
+ * (1) GPS_STATUS_SESSION_BEGIN: receive location fix + flag set + callback is set
+ * (2) GPS_STATUS_SESSION_END: receive location fix + flag set + callback is null
+ */
+ int cb_status_changed;
+ int sv_count; /*used to count the number of received SV information*/
+ GnssSvStatus sv_status;
+ GpsCallbacks callbacks;
+ char in[ NMEA_MAX_SIZE + 1 ];
+} NmeaReader;
+
+typedef struct {
+ pthread_t thread;
+ int server_fd;
+}PMTKThread;
+
+/* this is the state of our connection to the daemon */
+typedef struct {
+ int init; // to check whether, have been initialized
+ int pow_fd; //power ctrl
+ int tty_fd; //for read nmea
+ GpsCallbacks callbacks; // up layer callback
+ pthread_t thread;
+ PMTKThread pmtk_thread[1];
+ pthread_t nmea_read_thread;
+ int control[2];
+ int test_time;
+ int epoll_hd;
+ int flag;
+ int start_flag;
+} GpsState;
+
+static GpsState _gps_state[1];
+
+/*****************************************************************/
+/*****************************************************************/
+/***** *****/
+/***** C O N N E C T I O N S T A T E *****/
+/***** *****/
+/*****************************************************************/
+/*****************************************************************/
+
+/* commands sent to the gps thread */
+enum {
+ CMD_QUIT = 0,
+ CMD_START = 1,
+ CMD_STOP = 2,
+ CMD_RESTART = 3,
+ CMD_DOWNLOAD = 4,
+
+ CMD_TEST_START = 10,
+ CMD_TEST_STOP = 11,
+ CMD_TEST_SMS_NO_RESULT = 12,
+ CMD_EPO_DOWNLOAD_DONE = 13,
+};
+
+
+static int gps_nmea_end_tag = 0;
+
+int sv_used_in_fix[256] = {0}; // for multiple sv display
+
+unsigned char calc_nmea_checksum( const char* sentence);
+void send_assistance_data (int iYr, int iMo, int iDay, int iHr, char * timeInfo, int iTimeLen);
+
+static void get_condition(SYNC_LOCK_T *lock)
+{
+ int ret = 0;
+
+ ret = pthread_mutex_lock(&(lock->mutx));
+ DBG("ret get_mutex lock = %d\n",ret);
+
+ while (!lock->condtion)
+ {
+ DBG("ret get_cond wait = %d\n" ,ret);
+ ret = pthread_cond_wait(&(lock->con), &(lock->mutx));
+ }
+
+ lock->condtion = 0;
+ DBG("ret get_mutex unlock = %d\n",ret);
+ ret = pthread_mutex_unlock(&(lock->mutx));
+ DBG("test");
+
+ return;
+}
+
+static void release_condition(SYNC_LOCK_T *lock)
+{
+ int ret = 0;
+
+
+ ret = pthread_mutex_lock(&(lock->mutx));
+ DBG("ret release_mutex lock = %d\n",ret);
+
+ lock->condtion= 1;
+ ret = pthread_cond_signal(&(lock->con));
+ DBG ("ret release_cond_signal = %d\n",ret);
+
+ ret = pthread_mutex_unlock(&(lock->mutx));
+ DBG("ret release_unlock= %d\n",ret);
+
+ return;
+}
+
+int mtk_restart(unsigned char cmd)
+{
+ char buf[] = {cmd};
+ TRC();
+ return 0;
+}
+
+/*****************************************************************/
+/*****************************************************************/
+/***** *****/
+/***** N M E A T O K E N I Z E R *****/
+/***** *****/
+/*****************************************************************/
+/*****************************************************************/
+
+typedef struct {
+ const char* p;
+ const char* end;
+} Token;
+
+#define MAX_NMEA_TOKENS 24
+
+typedef struct {
+ int count;
+ Token tokens[ MAX_NMEA_TOKENS ];
+} NmeaTokenizer;
+
+static int
+nmea_tokenizer_init( NmeaTokenizer* t, const char* p, const char* end ) {
+ int count = 0;
+ char* q;
+
+ // the initial '$' is optional
+ if (p < end && p[0] == '$')
+ p += 1;
+
+ // remove trailing newline
+ if (end > p && end[-1] == '\n') {
+ end -= 1;
+ if (end > p && end[-1] == '\r')
+ end -= 1;
+ }
+
+ // get rid of checksum at the end of the sentecne
+ if (end >= p+3 && end[-3] == '*') {
+ end -= 3;
+ }
+
+ while (p < end) {
+ const char* q = p;
+
+ q = memchr(p, ',', end-p);
+ if (q == NULL)
+ q = end;
+
+ if (q >= p) {
+ if (count < MAX_NMEA_TOKENS) {
+ t->tokens[count].p = p;
+ t->tokens[count].end = q;
+ count += 1;
+ }
+ }
+ if (q < end)
+ q += 1;
+
+ p = q;
+ }
+
+ t->count = count;
+ DBG(" t->count is %d", t->count);
+ return count;
+}
+
+static Token
+nmea_tokenizer_get( NmeaTokenizer* t, int index )
+{
+ Token tok;
+ static const char* dummy = "";
+
+ if (index < 0 || index >= t->count) {
+ tok.p = tok.end = dummy;
+ } else
+ tok = t->tokens[index];
+
+ return tok;
+}
+
+
+static int
+str2int( const char* p, const char* end )
+{
+ int result = 0;
+ int len = end - p;
+ int sign = 1;
+
+ if (*p == '-')
+ {
+ sign = -1;
+ p++;
+ len = end - p;
+ }
+
+ for ( ; len > 0; len--, p++ )
+ {
+ int c;
+
+ if (p >= end)
+ goto Fail;
+
+ c = *p - '0';
+ if ((unsigned)c >= 10)
+ goto Fail;
+
+ result = result*10 + c;
+ }
+ return sign*result;
+
+Fail:
+ return -1;
+}
+
+static double
+str2float( const char* p, const char* end )
+{
+ int result = 0;
+ int len = end - p;
+ char temp[16];
+
+ if (len >= (int)sizeof(temp))
+ return 0.;
+
+ memcpy( temp, p, len );
+ temp[len] = 0;
+ return strtod( temp, NULL );
+}
+
+static void mtk_gps_update_location(nlp_context * location)
+{
+ FILE *fp = NULL;
+
+ fp = fopen(LOCATION_NLP_FIX, "w");
+ if (fp != NULL)
+ {
+ size_t count = 0;
+ count = fwrite(location, sizeof(nlp_context), 1, fp);
+ if (count != 1)
+ {
+ DBG("write count:%d, errno:%s\n", count, strerror(errno));
+ }
+ fclose(fp);
+ }
+}
+
+static bool g_EpoSend = false;
+static void mtk_gps_send_EPO()
+{
+ time_t timep;
+ struct tm* pq;
+ time(&timep);
+ pq = gmtime(&timep);
+ char strBuf[200], outBuf[200];
+ memset(strBuf, 0, sizeof(strBuf));
+ memset(outBuf, 0, sizeof(outBuf));
+ sprintf(strBuf, "PMTK740,%d,%d,%d,%d,%d,%d",pq->tm_year + 1900, pq->tm_mon + 1, pq->tm_mday, pq->tm_hour, pq->tm_min, pq->tm_sec);
+ sprintf(outBuf, "$%s*%02X\r\n", strBuf, calc_nmea_checksum(strBuf));
+ DBG("final PMTK is %s, size is %d, len is %d", outBuf, sizeof(outBuf), strlen(outBuf));
+ send_assistance_data(pq->tm_year + 1900, pq->tm_mon + 1, pq->tm_mday, pq->tm_hour, outBuf, strlen(outBuf));
+}
+
+/*****************************************/
+/*****************************************/
+/***** *****/
+/***** PowerGPS PMTK handle *****/
+/***** *****/
+/****************************************/
+/****************************************/
+
+static bool g_ThreadExitPMTKIn = false;//flag for PowerGPS thread exist
+static int g_hPowerGPS = INVALID_FD;//PowerGPS socket handle
+static NmeaReader g_NmeaReader[1];
+
+/***************Receive From PowerGPS********************/
+void * pmtk_input_func(void * arg)
+{
+ int bytes = 0;
+ int ret = 0;
+ char pmtk_buf[200];
+ char cmd = CMD_RESTART;
+ GpsState* state = (GpsState*) arg;
+
+ while(g_ThreadExitPMTKIn)
+ {
+ memset(pmtk_buf, 0, sizeof(pmtk_buf));
+ bytes = read(g_hPowerGPS, pmtk_buf, 200);
+
+ if (bytes > 0)
+ {
+ DBG("!!!!!!!!!! PowerGPS pass : %s, lenth is %d", pmtk_buf, bytes);
+
+ do {
+ ret=write( state->control[0], &cmd, 1);
+ }
+ while (ret < 0 && errno == EINTR);
+ do {
+ ret=write( state->tty_fd, pmtk_buf, bytes);
+ }while (ret < 0 && errno == EINTR);
+ if (ret < 0)
+ DBG("!!!!!!!!!!!PowerGPS write FAIL, errno is %d (%s)", errno, strerror(errno));
+ else
+ DBG("!!!!!!!!!!!!!!PowerGPS write succeed, ret is %d", ret);
+ if (strstr(pmtk_buf, "PMTK101")
+ || strstr(pmtk_buf, "PMTK102")
+ || strstr(pmtk_buf, "PMTK103")
+ || strstr(pmtk_buf, "PMTK104"))
+ {
+ g_EpoSend = true;
+ DBG("!!!!!!!PowerGPS got A START %s", pmtk_buf);
+ }
+ }
+ else
+ {
+ if (bytes == 0)
+ { //client close
+ DBG("!!!!!!socket client close");
+ break;
+ }
+ else
+ {
+ usleep(200000); // sleep 200 ms
+ DBG("!!!!!!socket error = %d (%s)\r\n", errno, strerror(errno));
+ }
+ }
+ }
+ return NULL;
+}
+
+/***************Output To PowerGPS********************/
+void pmtk_output_func(char * buf, int * length)
+{
+ if (buf[(*length) - 2] != '\r'){
+ buf[(*length) - 1] = '\r';
+ buf[(*length)] = '\n';
+ (*length) += 1;
+ }
+ int len = (*length);
+ int ret = 0;
+ int written = 0;
+ int retry = 0;
+ if (g_hPowerGPS != INVALID_FD)
+ {
+ while( (written != len) && (retry <5))
+ {
+ ret = write(g_hPowerGPS, buf + written, len - written);
+ if (ret < 0)
+ {
+ retry++;
+ }
+ else
+ {
+ written += ret;
+ }
+ }
+ }
+}
+
+void powergps_thread_exit(int sig_no, int server_fd)
+{
+ if(server_fd != INVALID_SOCKET)
+ {
+ close(server_fd);
+ server_fd == INVALID_SOCKET;
+ }
+ pthread_exit((void *)0);
+}
+
+void signal_action_handle(int signum, siginfo_t * info, void *myact)
+{
+ DBG("######got Signal : %d", signum);
+}
+
+/*
+ *Create Socket Server to listen PMTK from PowerGPS
+ */
+void* powergps_pmtk_receive_thread( void* arg )
+{
+ TRC();
+ g_ThreadExitPMTKIn = true;
+ GpsState* state = (GpsState*) arg;
+ int server_fd = state->pmtk_thread->server_fd;
+
+ int conn_fd = INVALID_SOCKET, on;
+ struct sockaddr_in server_addr;
+ struct sockaddr_in client_addr;
+ socklen_t size;
+ int hdlsig = SIGUSR1;
+ struct sigaction sa;
+ char buf[128];
+
+ if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+ {
+ DBG("socket error = %d (%s)\r\n", errno, strerror(errno));
+ pthread_exit((void *)0);
+ return NULL;
+ }
+ DBG("########### socket create SUCCESS - pid == %d, fd == %d", getpid(), server_fd);
+
+ /* Enable address reuse */
+ on = 1;
+ if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)))
+ {
+ close(server_fd);
+ pthread_exit((void *)0);
+ return NULL;
+ }
+ DBG("########### socket set SUCCESS");
+
+ server_addr.sin_family = AF_INET; /*host byte order*/
+ server_addr.sin_port = htons(PMTK_SOCKET_COM_PORT); /*short, network byte order*/
+ server_addr.sin_addr.s_addr = htonl(INADDR_ANY); /*automatically fill with my IP*/
+ memset(server_addr.sin_zero, 0x00, sizeof(server_addr.sin_zero));
+
+ if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1)
+ {
+ close(server_fd);
+ pthread_exit((void *)0);
+ return NULL;
+ }
+ DBG("########### socket bind SUCCESS");
+
+ if (listen(server_fd, PMTK_SERVER_BACKLOG) == -1)
+ {
+ close(server_fd);
+ pthread_exit((void *)0);
+ return NULL;
+ }
+ DBG("########### socket listen SUCCESS");
+
+ sa.sa_handler = SIG_IGN;
+ sa.sa_sigaction = signal_action_handle;
+ sa.sa_flags = (0 | SA_SIGINFO);
+ sigemptyset(&sa.sa_mask);
+ if (sigaction(SIGPIPE, &sa, NULL) < 0)
+ {
+ DBG("sigaction error \r\n");
+ }
+
+ while (g_ThreadExitPMTKIn)
+ {
+ size = sizeof(client_addr);
+ DBG("########### waiting the client..........");
+ conn_fd = accept(server_fd, (struct sockaddr*)&client_addr, &size);
+ DBG("########### client comes in..........");
+
+ if (conn_fd <= 0)
+ {
+ DBG("######### no client");
+ close(server_fd);
+ break;
+ }
+ else
+ {
+ g_hPowerGPS = conn_fd;
+ pmtk_input_func(state);
+ }
+ }
+ powergps_thread_exit(0, server_fd);//call pthread_exit() in this function, the code after this sentence will not be executed
+ return NULL;
+}
+
+/*****************************************************************/
+/*****************************************************************/
+/***** *****/
+/***** N M E A P A R S E R *****/
+/***** *****/
+/*****************************************************************/
+/*****************************************************************/
+
+static void
+nmea_reader_update_utc_diff( NmeaReader* const r )
+{
+ time_t now = time(NULL);
+ struct tm tm_local;
+ struct tm tm_utc;
+ unsigned long time_local, time_utc;
+
+ gmtime_r( &now, &tm_utc );
+ localtime_r( &now, &tm_local );
+
+ time_local = mktime(&tm_local);
+ time_utc = mktime(&tm_utc);
+ r->utc_diff = time_utc - time_local;
+}
+
+
+static void
+nmea_reader_init( NmeaReader* const r )
+{
+ memset( r, 0, sizeof(*r) );
+
+ r->pos = 0;
+ r->overflow = 0;
+ r->utc_year = -1;
+ r->utc_mon = -1;
+ r->utc_day = -1;
+ r->utc_diff = 0;
+ r->callbacks.location_cb= NULL;
+ r->callbacks.status_cb= NULL;
+ r->callbacks.gnss_sv_status_cb= NULL;
+ r->sv_count = 0;
+ r->fix_mode = 0; /*no fix*/
+ r->cb_status_changed = 0;
+ memset((void*)&r->sv_status, 0x00, sizeof(r->sv_status));
+ memset((void*)&r->in, 0x00, sizeof(r->in));
+
+ nmea_reader_update_utc_diff( r );
+ r->fix.flags |= GPS_LOCATION_HAS_ACCURACY;
+ r->fix.accuracy = 10;
+}
+
+static void
+nmea_reader_set_callback( NmeaReader* const r, GpsCallbacks* const cbs)
+{
+ if (!r) { /*this should not happen*/
+ return;
+ } else if (!cbs) { /*unregister the callback */
+ return ;
+ } else {/*register the callback*/
+ r->sv_count = r->sv_status.num_svs = 0;
+ r->fix.flags |= GPS_LOCATION_HAS_ACCURACY;
+ r->fix.accuracy = 10;
+ }
+}
+
+
+static int
+nmea_reader_update_time( NmeaReader* const r, Token tok ) {
+ int hour, minute;
+ double seconds;
+ struct tm tm;
+ time_t fix_time;
+
+ if (tok.p + 6 > tok.end)
+ return -1;
+
+ memset((void*)&tm, 0x00, sizeof(tm));
+ if (r->utc_year < 0) {
+ // no date yet, get current one
+ time_t now = time(NULL);
+ gmtime_r( &now, &tm );
+ r->utc_year = tm.tm_year + 1900;
+ r->utc_mon = tm.tm_mon + 1;
+ r->utc_day = tm.tm_mday;
+ }
+
+ hour = str2int(tok.p, tok.p+2);
+ minute = str2int(tok.p+2, tok.p+4);
+ seconds = str2float(tok.p+4, tok.end);
+
+ tm.tm_hour = hour;
+ tm.tm_min = minute;
+ tm.tm_sec = (int) seconds;
+ tm.tm_year = r->utc_year - 1900;
+ tm.tm_mon = r->utc_mon - 1;
+ tm.tm_mday = r->utc_day;
+ tm.tm_isdst = -1;
+
+ if (mktime(&tm) == (time_t)-1)
+ ERR("mktime error: %d %s\n", errno, strerror(errno));
+
+ nmea_reader_update_utc_diff(r);
+
+ fix_time = mktime(&tm) - r->utc_diff;
+ DBG("fix_time: %d\n",fix_time);
+ r->fix.timestamp = (long long)fix_time * 1000;
+ return 0;
+}
+
+static int
+nmea_reader_update_date( NmeaReader* const r, Token date, Token time )
+{
+ Token tok = date;
+ int day, mon, year;
+
+ if (tok.p + 6 != tok.end) {
+ ERR("date not properly formatted: '%.*s'", tok.end-tok.p, tok.p);
+ return -1;
+ }
+ day = str2int(tok.p, tok.p+2);
+ mon = str2int(tok.p+2, tok.p+4);
+ year = str2int(tok.p+4, tok.p+6) + 2000;
+
+ if ((day|mon|year) < 0) {
+ ERR("date not properly formatted: '%.*s'", tok.end-tok.p, tok.p);
+ return -1;
+ }
+
+ r->utc_year = year;
+ r->utc_mon = mon;
+ r->utc_day = day;
+
+ return nmea_reader_update_time( r, time );
+}
+
+
+static double
+convert_from_hhmm( Token tok )
+{
+ double val = str2float(tok.p, tok.end);
+ int degrees = (int)(floor(val) / 100);
+ double minutes = val - degrees*100.;
+ double dcoord = degrees + minutes / 60.0;
+ return dcoord;
+}
+
+
+static int
+nmea_reader_update_latlong( NmeaReader* const r,
+ Token latitude,
+ char latitudeHemi,
+ Token longitude,
+ char longitudeHemi ) {
+ double lat, lon;
+ Token tok;
+
+ tok = latitude;
+ if (tok.p + 6 > tok.end) {
+ return -1;
+ }
+ lat = convert_from_hhmm(tok);
+ if (latitudeHemi == 'S')
+ lat = -lat;
+
+ tok = longitude;
+ if (tok.p + 6 > tok.end) {
+ return -1;
+ }
+ lon = convert_from_hhmm(tok);
+ if (longitudeHemi == 'W')
+ lon = -lon;
+
+ r->fix.flags |= GPS_LOCATION_HAS_LAT_LONG;
+ r->fix.latitude = lat;
+ r->fix.longitude = lon;
+ return 0;
+}
+
+static int
+nmea_reader_update_altitude( NmeaReader* const r,
+ Token altitude,
+ Token units ) {
+ double alt;
+ Token tok = altitude;
+
+ if (tok.p >= tok.end)
+ return -1;
+
+ r->fix.flags |= GPS_LOCATION_HAS_ALTITUDE;
+ r->fix.altitude = str2float(tok.p, tok.end);
+ return 0;
+}
+
+
+static int
+nmea_reader_update_bearing( NmeaReader* const r,
+ Token bearing )
+{
+ double alt;
+ Token tok = bearing;
+
+ if (tok.p >= tok.end)
+ return -1;
+
+ r->fix.flags |= GPS_LOCATION_HAS_BEARING;
+ r->fix.bearing = str2float(tok.p, tok.end);
+ return 0;
+}
+
+
+static int
+nmea_reader_update_speed( NmeaReader* const r,
+ Token speed )
+{
+ double alt;
+ Token tok = speed;
+
+ if (tok.p >= tok.end)
+ return -1;
+
+ r->fix.flags |= GPS_LOCATION_HAS_SPEED;
+
+ //Modify by ZQH to convert the speed unit from knot to m/s
+ //r->fix.speed = str2float(tok.p, tok.end);
+ r->fix.speed = str2float(tok.p, tok.end) / 1.942795467;
+ return 0;
+}
+
+//Add by LCH for accuracy
+static int
+nmea_reader_update_accuracy( NmeaReader* const r,
+ Token accuracy )
+{
+ double alt;
+ Token tok = accuracy;
+
+ if (tok.p >= tok.end)
+ return -1;
+
+ r->fix.flags |= GPS_LOCATION_HAS_ACCURACY;
+ r->fix.accuracy = str2float(tok.p, tok.end);
+ return 0;
+}
+
+static int
+nmea_reader_update_sv_status( NmeaReader* r, int sv_index,
+ int id, Token elevation,
+ Token azimuth, Token snr)
+{
+ //int prn = str2int(id.p, id.end);
+ int prn = id;
+
+ if ((prn <= 0) || (prn < 65 && prn > GPS_MAX_SVS)|| ((prn > 96) && (prn < 200)) || (prn > 232) || (r->sv_count >= GNSS_MAX_SVS)) {
+ VER("sv_status: ignore (%d)", prn);
+ return 0;
+ }
+ sv_index = r->sv_count+r->sv_status.num_svs;
+ if(GNSS_MAX_SVS <= sv_index)
+ {
+ ERR("ERR: sv_index=[%d] is larger than GNSS_MAX_SVS.\n", sv_index);
+ return 0;
+ }
+
+ if ((prn > 0) && (prn < 32)) {
+ r->sv_status.gnss_sv_list[sv_index].svid = prn;
+ r->sv_status.gnss_sv_list[sv_index].constellation = GPS_SV;
+ } else if ((prn >= 65) && (prn <= 96)) {
+ r->sv_status.gnss_sv_list[sv_index].svid = prn-64;
+ r->sv_status.gnss_sv_list[sv_index].constellation = GLONASS_SV;
+ } else if ((prn >= 201) && (prn <= 237)) {
+ r->sv_status.gnss_sv_list[sv_index].svid = prn-200;
+ r->sv_status.gnss_sv_list[sv_index].constellation = BDS_SV;
+ } else if ((prn >= 401) && (prn <= 436)) {
+ r->sv_status.gnss_sv_list[sv_index].svid = prn-400;
+ r->sv_status.gnss_sv_list[sv_index].constellation = GALILEO_SV;
+ } else {
+ DBG("sv_status: ignore (%d)", prn);
+ return 0;
+ }
+
+ r->sv_status.gnss_sv_list[sv_index].c_n0_dbhz = str2float(snr.p, snr.end);
+ r->sv_status.gnss_sv_list[sv_index].elevation = str2int(elevation.p, elevation.end);
+ r->sv_status.gnss_sv_list[sv_index].azimuth = str2int(azimuth.p, azimuth.end);
+ if(1 == sv_used_in_fix[prn]){
+ r->sv_status.gnss_sv_list[sv_index].flags |= 0x04;;
+ }else{
+ r->sv_status.gnss_sv_list[sv_index].flags &= 0xFB;
+ }
+ r->sv_count++;
+ DBG("sv_status(%2d): %2d, %d, %2f, %3f, %2f, %d",
+ sv_index, r->sv_status.gnss_sv_list[sv_index].svid, r->sv_status.gnss_sv_list[sv_index].constellation,
+ r->sv_status.gnss_sv_list[sv_index].elevation, r->sv_status.gnss_sv_list[sv_index].azimuth,
+ r->sv_status.gnss_sv_list[sv_index].c_n0_dbhz, r->sv_status.gnss_sv_list[sv_index].flags);
+ return 0;
+}
+
+static int
+nmea_reader_parse( NmeaReader* const r )
+{
+ /* we received a complete sentence, now parse it to generate
+ * a new GPS fix...
+ */
+ NmeaTokenizer tzer[1];
+ Token tok;
+ Token mtok;
+ SV_TYPE sv_type = 0;
+
+ /*
+ if (r->pos < 9) {
+ ERR("Too short. discarded. '%.*s'", r->pos, r->in);
+ return;
+ }
+ */
+
+ nmea_tokenizer_init(tzer, r->in, r->in + r->pos);
+
+#if NEMA_DEBUG
+ {
+ int n;
+ DBG("Found %d tokens", tzer->count);
+ for (n = 0; n < tzer->count; n++) {
+ Token tok = nmea_tokenizer_get(tzer,n);
+ DBG("%2d: '%.*s'", n, tok.end-tok.p, tok.p);
+ }
+ }
+#endif
+
+ tok = nmea_tokenizer_get(tzer, 0);
+ if (tok.p + 5 > tok.end) {
+ ERR("sentence id '%.*s' too short, ignored.", tok.end-tok.p, tok.p);
+ return -1;
+ }
+
+ // ignore first two characters.
+ mtok.p = tok.p; //Mark the first two char for GPS,GLONASS,BDS SV parse.
+ if(!memcmp(mtok.p, "BD", 2)){
+ sv_type = BDS_SV;
+ DBG("BDS SV type");
+ } else if (!memcmp(mtok.p, "GP", 2)) {
+ sv_type = GPS_SV;
+ } else if (!memcmp(mtok.p, "GL", 2)) {
+ sv_type = GLONASS_SV;
+ } else if (!memcmp(mtok.p, "GA", 2)) {
+ sv_type = GALILEO_SV;
+ }
+ #if NEMA_DEBUG
+ LOGD("SV type: %d", sv_type);
+ #endif
+ tok.p += 2;
+ if ( !memcmp(tok.p, "GGA", 3) )
+ {
+ if (tzer->count < 14)
+ return 0;
+ // GPS fix
+ Token tok_time = nmea_tokenizer_get(tzer,1);
+ Token tok_latitude = nmea_tokenizer_get(tzer,2);
+ Token tok_latitudeHemi = nmea_tokenizer_get(tzer,3);
+ Token tok_longitude = nmea_tokenizer_get(tzer,4);
+ Token tok_longitudeHemi = nmea_tokenizer_get(tzer,5);
+ Token tok_altitude = nmea_tokenizer_get(tzer,9);
+ Token tok_altitudeUnits = nmea_tokenizer_get(tzer,10);
+
+ nmea_reader_update_time(r, tok_time);
+ nmea_reader_update_latlong(r, tok_latitude,
+ tok_latitudeHemi.p[0],
+ tok_longitude,
+ tok_longitudeHemi.p[0]);
+ nmea_reader_update_altitude(r, tok_altitude, tok_altitudeUnits);
+
+ }
+ else if ( !memcmp(mtok.p, "GPGSA", 5)||!memcmp(mtok.p, "BDGSA", 5)||!memcmp(mtok.p, "GLGSA", 5)) {
+ if (tzer->count < 18)
+ return 0;
+ Token tok_fix = nmea_tokenizer_get(tzer, 2);
+ int idx, max = 12; /*the number of satellites in GPGSA*/
+
+ r->fix_mode = str2int(tok_fix.p, tok_fix.end);
+
+ if (LOC_FIXED(r)) { /* 1: No fix; 2: 2D; 3: 3D*/
+ for (idx = 0; idx < max; idx++) {
+ Token tok_satellite = nmea_tokenizer_get(tzer, idx+3);
+ if (tok_satellite.p == tok_satellite.end) {
+ break;
+ }
+ int sate_id = str2int(tok_satellite.p, tok_satellite.end);
+ if (sv_type == BDS_SV){
+ sate_id += 200;
+ }
+ if (sate_id >= 1 && sate_id <= 32) { //GP
+ sv_used_in_fix[sate_id] = 1;
+ }else if(sate_id >= 193 && sate_id <= 197){
+ sv_used_in_fix[sate_id] = 0;
+ continue;
+ }else if(sate_id >= 65 && sate_id <= 96){ //GL
+ sv_used_in_fix[sate_id] = 1;
+ }else if(sate_id >= 201 && sate_id <= 232){ //BD
+ sv_used_in_fix[sate_id] = 1;
+
+ }
+ else{
+ break;
+ }
+ }
+ }
+ }
+ //VER("GPGSA: mask 0x%x", r->sv_status.used_in_fix_mask);
+ else if ( !memcmp(tok.p, "RMC", 3) ) {
+ if (tzer->count < 13)
+ return 0;
+ Token tok_time = nmea_tokenizer_get(tzer,1);
+ Token tok_fixStatus = nmea_tokenizer_get(tzer,2);
+ Token tok_latitude = nmea_tokenizer_get(tzer,3);
+ Token tok_latitudeHemi = nmea_tokenizer_get(tzer,4);
+ Token tok_longitude = nmea_tokenizer_get(tzer,5);
+ Token tok_longitudeHemi = nmea_tokenizer_get(tzer,6);
+ Token tok_speed = nmea_tokenizer_get(tzer,7);
+ Token tok_bearing = nmea_tokenizer_get(tzer,8);
+ Token tok_date = nmea_tokenizer_get(tzer,9);
+
+ if (tok_fixStatus.p[0] == 'A') {
+ nmea_reader_update_date( r, tok_date, tok_time );
+ nmea_reader_update_latlong( r, tok_latitude,
+ tok_latitudeHemi.p[0],
+ tok_longitude,
+ tok_longitudeHemi.p[0] );
+ nmea_reader_update_bearing( r, tok_bearing );
+ nmea_reader_update_speed( r, tok_speed );
+ }
+ }
+ else if ( !memcmp(tok.p, "GSV", 3) ) {
+ if (tzer->count < 4)
+ return 0;
+ Token tok_num = nmea_tokenizer_get(tzer,1); //number of messages
+ Token tok_seq = nmea_tokenizer_get(tzer,2); //sequence number
+ Token tok_cnt = nmea_tokenizer_get(tzer,3); //Satellites in view
+ int num = str2int(tok_num.p, tok_num.end);
+ int seq = str2int(tok_seq.p, tok_seq.end);
+ int cnt = str2int(tok_cnt.p, tok_cnt.end);
+ int sv_base = (seq - 1)*NMEA_MAX_SV_INFO;
+ int sv_num = cnt - sv_base;
+ int idx, base = 4, base_idx;
+ if (sv_num > NMEA_MAX_SV_INFO)
+ sv_num = NMEA_MAX_SV_INFO;
+ if (seq == 1) /*if sequence number is 1, a new set of GSV will be parsed*/
+ r->sv_count = 0;
+ for (idx = 0; idx < sv_num; idx++) {
+ base_idx = base*(idx+1);
+ Token tok_id = nmea_tokenizer_get(tzer, base_idx+0);
+ int sv_id = str2int(tok_id.p, tok_id.end);
+ if (sv_type == BDS_SV)
+ sv_id += 200;
+ else if (sv_type == GALILEO_SV)
+ sv_id += 400;
+ Token tok_ele = nmea_tokenizer_get(tzer, base_idx+1);
+ Token tok_azi = nmea_tokenizer_get(tzer, base_idx+2);
+ Token tok_snr = nmea_tokenizer_get(tzer, base_idx+3);
+ nmea_reader_update_sv_status(r, sv_base+idx, sv_id, tok_ele, tok_azi, tok_snr);
+ }
+ if (seq == num) {
+ if (r->sv_count <= cnt) {
+ r->sv_status.num_svs += r->sv_count;
+ }
+ else {
+ ERR("GPGSV incomplete (%d/%d), ignored!", r->sv_count, cnt);
+ r->sv_count = r->sv_status.num_svs = 0;
+ }
+ }
+ }
+ //Add for Accuracy
+ else if ( !memcmp(tok.p, "ACCURACY", 8)) {
+ if((r->fix_mode == 3)||(r->fix_mode == 2)) {
+ Token tok_accuracy = nmea_tokenizer_get(tzer,1);
+ nmea_reader_update_accuracy(r, tok_accuracy);
+ }
+ }
+ else if ( !(memcmp(mtok.p, "GPBOD", 5)
+ && memcmp(mtok.p, "GPBWC", 5)
+ && memcmp(mtok.p, "GPGLL", 5)
+ && memcmp(mtok.p, "GPHDT", 5)
+ && memcmp(mtok.p, "GPROO", 5)
+ && memcmp(mtok.p, "GPRMA", 5)
+ && memcmp(mtok.p, "GPRMB", 5)
+ && memcmp(mtok.p, "GPRTE", 5)
+ && memcmp(mtok.p, "GPTRF", 5)
+ && memcmp(mtok.p, "GPSTN", 5)
+ && memcmp(mtok.p, "GPVBW", 5)
+ && memcmp(mtok.p, "GPVTG", 5)
+ && memcmp(mtok.p, "GPWPL", 5)
+ && memcmp(mtok.p, "GPXTE", 5)
+ && memcmp(mtok.p, "GPZDA", 5)))
+ {
+ tok.p -= 2;
+ }
+ else if ( !memcmp(mtok.p, "PMTK", 4))
+ {
+ tok.p -=2;
+ DBG("PMTK is %s", r->in);
+ if ( !memcmp(mtok.p, "PMTK010,002", 11) && g_EpoSend)
+ {
+ DBG("we got some START, ready to send EPO data");
+ callback_backup.create_thread_cb(gps_send_epo_thread, mtk_gps_send_EPO, NULL);
+ g_EpoSend = false;
+ }
+ /* disable QZSS start */
+ else if ( !memcmp(mtok.p, "PMTK010,001", 11))
+ {
+ DBG("we got some START, ready to send 352 cmd");
+ int temp_ret = 0;
+ temp_ret = write(_gps_state->tty_fd, "$PMTK352,1*2B\r\n", 15);
+ DBG("hao test : temp_ret is %d", temp_ret);
+ //g_EpoSend = false;
+ }
+ else if ( !memcmp(mtok.p, "PMTK001,352,3", 13))
+ {
+ DBG("received 352,3 response");
+ }
+ /* disable QZSS end */
+ return 0;
+ }
+ else {
+ tok.p -= 2;
+ return 0;
+ }
+ if (!LOC_FIXED(r)) {
+ VER("Location is not fixed, ignored callback\n");
+ }
+ else if (r->fix.flags != 0 && gps_nmea_end_tag) {
+#if NEMA_DEBUG
+ char temp[256];
+ char* p = temp;
+ char* end = p + sizeof(temp);
+ struct tm utc;
+
+ p += snprintf( p, end-p, "sending fix" );
+ if (r->fix.flags & GPS_LOCATION_HAS_LAT_LONG) {
+ p += snprintf(p, end-p, " lat=%g lon=%g", r->fix.latitude, r->fix.longitude);
+ }
+ if (r->fix.flags & GPS_LOCATION_HAS_ALTITUDE) {
+ p += snprintf(p, end-p, " altitude=%g", r->fix.altitude);
+ }
+ if (r->fix.flags & GPS_LOCATION_HAS_SPEED) {
+ p += snprintf(p, end-p, " speed=%g", r->fix.speed);
+ }
+ if (r->fix.flags & GPS_LOCATION_HAS_BEARING) {
+ p += snprintf(p, end-p, " bearing=%g", r->fix.bearing);
+ }
+ if (r->fix.flags & GPS_LOCATION_HAS_ACCURACY) {
+ p += snprintf(p,end-p, " accuracy=%g", r->fix.accuracy);
+ DBG("GPS accuracy=%g\n", r->fix.accuracy);
+ }
+ gmtime_r( (time_t*) &r->fix.timestamp, &utc );
+ p += snprintf(p, end-p, " time=%s", asctime( &utc ) );
+ VER(temp);
+#endif
+ callback_backup.location_cb(&r->fix);
+ {
+ nlp_context fix_location;
+ fix_location.latitude = r->fix.latitude;
+ fix_location.longitude= r->fix.longitude;
+ fix_location.accuracy= r->fix.accuracy;
+ fix_location.type = 1;
+ fix_location.started = started;
+ fix_location.ts.tv_sec = r->fix.timestamp/1000;
+ fix_location.ts.tv_nsec = (r->fix.timestamp%1000) * 1000*1000;
+ mtk_gps_update_location(&fix_location);
+ }
+ r->fix.flags = GPS_LOCATION_HAS_ACCURACY;
+ }
+
+ DBG("r->sv_status.num_svs = %d, gps_nmea_end_tag = %d", r->sv_status.num_svs,gps_nmea_end_tag);
+ if (r->sv_status.num_svs != 0 && gps_nmea_end_tag)
+ {
+ int idx;
+ r->sv_status.size = sizeof(GnssSvStatus);
+ callback_backup.gnss_sv_status_cb(&r->sv_status);
+ r->sv_count = r->sv_status.num_svs = 0;
+ memset( sv_used_in_fix, 0, 256*sizeof(int));
+ }
+ return 1;
+}
+
+
+static void
+nmea_reader_addc( NmeaReader* const r, int c )
+{
+ int ret = 0;
+ if (r->overflow) {
+ r->overflow = (c != '\n');
+ return;
+ }
+
+ if (r->pos >= (int) sizeof(r->in)-1 ) {
+ r->overflow = 1;
+ r->pos = 0;
+ DBG("nmea sentence overflow\n");
+ return;
+ }
+
+ r->in[r->pos] = (char)c;
+ r->pos += 1;
+ //DBG(" r->in[%d] is %c, r->pos is %d", r->pos, r->in[r->pos], r->pos);
+ if (c == '\n')
+ {
+ //r->pos < 9 :too short
+ if (gps_nmea_end_tag == 1 && r->pos >= 9) {
+ ret = nmea_reader_parse( r );
+ if (ret == 1)
+ {
+ DBG("ready to send : %s, strlen is %d, sizeof is %d", r->in, strlen(r->in), sizeof(r->in));
+ callback_backup.nmea_cb( r->fix.timestamp, r->in, r->pos );
+ pmtk_output_func( r->in, &(r->pos));
+ }
+ if (ret == 0)
+ {
+ pmtk_output_func(r->in, &(r->pos));
+ }
+ r->pos = 0;
+ }
+ else {
+ r->pos -=1;
+ }
+ }
+}
+
+static int
+epoll_register( int epoll_fd, int fd )
+{
+ struct epoll_event ev;
+ int ret, flags;
+
+ /* important: make the fd non-blocking */
+ flags = fcntl(fd, F_GETFL);
+ fcntl(fd, F_SETFL, flags | O_NONBLOCK);
+
+ ev.events = EPOLLIN;
+ ev.data.fd = fd;
+ do {
+ ret = epoll_ctl( epoll_fd, EPOLL_CTL_ADD, fd, &ev );
+ } while (ret < 0 && errno == EINTR);
+ if(ret < 0)
+ ERR("epoll ctl error, error num is %d\n, message is %s\n", errno, strerror(errno));
+ return ret;
+}
+
+
+static int
+epoll_deregister( int epoll_fd, int fd )
+{
+ int ret;
+ do {
+ ret = epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd, NULL );
+ } while (ret < 0 && errno == EINTR);
+ return ret;
+}
+
+void
+mtk_gps_start_driver()
+{
+ int fp = open("/dev/mt3337_gpsonly", O_RDWR);
+ if (fp == -1) {
+ DBG("open dev/mt3337_gpsonly fail, errorno is %d", errno);
+ }
+ else {
+ ioctl(fp, GPS_POWER_IOCTL, 1);
+ usleep(1000*200);
+ ioctl(fp, GPS_POWER_IOCTL, 0);
+ usleep(1000*200);
+ ioctl(fp, GPS_POWER_IOCTL, 1);
+ }
+ close(fp);
+}
+
+void
+mtk_gps_reset_driver()
+{
+ int fp = open("/dev/mt3337_gpsonly", O_RDWR);
+ if (fp == -1) {
+ DBG("open dev/mt3337_gpsonly fail, errorno is %d", errno);
+ }
+ else {
+ ioctl(fp, GPS_POWER_IOCTL, 0);
+ usleep(1000*1000);
+ ioctl(fp, GPS_POWER_IOCTL, 1);
+ }
+ close(fp);
+}
+
+void
+mtk_gps_stop_driver()
+{
+ int fp = open("/dev/mt3337_gpsonly", O_RDWR);
+ if (fp == -1) {
+ DBG("open dev/mt3337_gpsonly fail, errorno is %d", errno);
+ }
+ else {
+ ioctl(fp, GPS_POWER_IOCTL, 0);
+ }
+ close(fp);
+}
+
+void
+mnl_load_property()
+{
+ char result[512] = {0};
+ int iEpoDisable = 0;
+ int iHotstillEnable = 0;
+ GpsState* s = _gps_state;
+ int ret = 0;
+ if (property_get(MNL_CONFIG_STATUS, result, NULL))
+ {
+ iEpoDisable = result[7] - '0';
+ if (iEpoDisable == 0)
+ {
+ ret = write(s->tty_fd, "$PMTK127*36\r\n", 13);
+ DBG("we r going to clear EPO data, ret is %d", ret);
+ }
+ iHotstillEnable = result[4] - '0';
+ if (iHotstillEnable == 1)
+ {
+ ret = write(s->tty_fd, "$PMTK869,1,1*35\r\n", 17);
+ DBG("we r going to enable easy, ret is %d", ret);
+ }
+ else
+ {
+ ret = write(s->tty_fd, "$PMTK869,1,0*36\r\n", 17);
+ DBG("we r going to disable easy, ret is %d", ret);
+ }
+ }
+ else
+ {
+ DBG("YGPS config not set yet");
+ }
+}
+
+unsigned char
+calc_nmea_checksum( const char* sentence)
+{
+ unsigned char checksum = 0;
+ while (*sentence)
+ {
+ checksum ^= (unsigned char)*sentence++;
+ }
+
+ return checksum;
+}
+
+//translate UTC to GPS_Hour
+int
+utc_to_gps_hour( int iYr, int iMo, int iDay, int iHr)
+{
+ int iYearsElapsed;
+ int iDaysElapsed;
+ int iLeapDays;
+ int i;
+
+ const unsigned short doy[12] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
+ iYearsElapsed = iYr - 1980;
+ i = 0;
+ iLeapDays = 0;
+
+ while (i <= iYearsElapsed)
+ {
+ if ((i % 100) == 20)
+ {
+ if ((i % 400) == 20)
+ {
+ iLeapDays++;
+ }
+ }
+ else if ((i % 4) == 0)
+ {
+ iLeapDays++;
+ }
+ i++;
+ }
+ if ((iYearsElapsed % 100) == 20)
+ {
+ if (((iYearsElapsed % 400) == 20) && (iMo <= 2))
+ {
+ iLeapDays--;
+ }
+ }
+ else if (((iYearsElapsed % 4) == 0) && (iMo <= 2))
+ {
+ iLeapDays--;
+ }
+ iDaysElapsed = iYearsElapsed*365 + (int)doy[iMo - 1] + iDay + iLeapDays - 6;
+
+ return (iDaysElapsed * 24 + iHr);
+}
+
+void
+send_assistance_data (int iYr, int iMo, int iDay, int iHr, char * timeInfo, int iTimeLen)
+{
+ TRC();
+ int fp, ret = 0;
+ int i, segment, epo_gps_hour, current_gps_hour;
+ unsigned epobuf[MTKEPO_RECORD_SIZE/sizeof(unsigned)];
+ char strbuf[200], outbuf[200];
+ GpsState* s = _gps_state;
+ // open EPO file and read the header (assume EPO file has passed integrity check)
+ fp = open(MTK_GPS_DATA_PATH"EPOHAL.DAT", O_RDONLY);
+ if (fp < 0)
+ {
+ DBG("!!!!!!no EPO file ERROR: %d, %s", errno, strerror(errno));
+ return;
+ }
+ ret = read(fp, &epo_gps_hour, sizeof(int));
+ epo_gps_hour &= 0x00FFFFFF;
+
+ current_gps_hour = utc_to_gps_hour(iYr, iMo, iDay, iHr);
+ segment = (current_gps_hour - epo_gps_hour) / 6;
+ if ((segment < 0) || (segment >= MTKEPO_SEGMENT_NUM))
+ {
+ DBG("!!!!!segment ERROR : %d", segment);
+ return;
+ }
+ // read binary EPO data and sent it to MT3339
+ lseek(fp, segment*(MTKEPO_RECORD_SIZE)*(MTKEPO_SV_NUMBER), SEEK_SET);
+ DBG("ready to write time info before send EPO data");
+ ret = write(s->tty_fd, timeInfo, iTimeLen);
+ usleep(1000*200);
+ for (i = 0; i < MTKEPO_SV_NUMBER; i++)
+ {
+ read(fp, epobuf, MTKEPO_RECORD_SIZE);
+ // assume host system is little-endian
+ sprintf(strbuf,"PMTK721,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X",
+ i+1,
+ epobuf[0], epobuf[1], epobuf[2], epobuf[3], epobuf[4], epobuf[5],
+ epobuf[6], epobuf[7], epobuf[8], epobuf[9], epobuf[10], epobuf[11],
+ epobuf[12], epobuf[13], epobuf[14], epobuf[15], epobuf[16], epobuf[17]);
+ sprintf(outbuf, "$%s*%02X\r\n", strbuf, calc_nmea_checksum(strbuf));
+ // send them by UART
+ DBG("!!!!this EPO data len is %d,data is : %s", strlen(outbuf), outbuf); // for demo
+ for (int j = 0; j < 3; j++)
+ {
+ ret = write(s->tty_fd, outbuf, strlen(outbuf));
+ if (ret < 0)
+ DBG("Write EPO data fail, errno is %d", errno);
+ else
+ j = 3;
+ }
+ if (i%10 == 0)
+ usleep(1000*200);
+ }
+ close(fp);
+}
+
+/*for reducing the function call to get data from kernel*/
+static char buffGGA[2048];
+/*gps nmea read thread */
+static bool g_NmeaReadStart = false;
+static bool g_ThreadExistNmeaRead = false;
+static bool g_GpsDriverStart = false;
+static pthread_mutex_t g_mutx;
+
+void
+gps_read_nmea_from_uart_thread(void* arg)
+{
+ g_ThreadExistNmeaRead = true;
+ GpsState* state = (GpsState*) arg;
+ int fd = state->tty_fd;
+ while (g_ThreadExistNmeaRead)
+ {
+ if(g_GpsDriverStart && g_NmeaReadStart)
+ {
+ int nn, ret;
+ memset(buffGGA, 0, sizeof(buffGGA));
+ ret = read( fd, buffGGA, sizeof(buffGGA) );
+ gps_nmea_end_tag = 0;
+
+ DBG("before PARSE buffer[%d] is:%s.", ret, buffGGA);
+ memset(g_NmeaReader->in, 0, sizeof(g_NmeaReader->in));
+ for (nn = 0; nn < ret && g_GpsDriverStart; nn++)
+ {
+ if(nn == (ret-1))
+ gps_nmea_end_tag = 1;
+
+ nmea_reader_addc( g_NmeaReader, buffGGA[nn] );
+ }
+ g_NmeaReadStart = false;
+ }
+ usleep(100);
+ }
+ DBG("gps_read_nmea_from_uart_thread exit!");
+}
+/* this is the main thread, it waits for commands from gps_state_start/stop and,
+ * when started, messages from the GPS daemon. these are simple NMEA sentences
+ * that must be parsed to be converted into GPS fixes sent to the framework
+ */
+void
+gps_state_thread( void* arg )
+{
+ static float count = 0;
+ GpsState* state = (GpsState*) arg;
+ state->test_time += 1;
+ int tty_fd = state->tty_fd;
+ int control_fd = state->control[1];
+ int pow_fd = state->pow_fd;
+
+ int epoll_fd = state->epoll_hd;
+ int test_started = 0;
+
+ nmea_reader_init( g_NmeaReader );
+
+ // register control file descriptors for polling
+ if(epoll_register( epoll_fd, control_fd ) < 0)
+ ERR("control_fd register control_fd error, error num is %d\n, message is %s\n", errno, strerror(errno));
+ if(epoll_register( epoll_fd, tty_fd) < 0)
+ ERR("tty_fd register control_fd error, error num is %d\n, message is %s\n", errno, strerror(errno));
+ //if(epoll_register( epoll_fd, pow_fd) < 0)
+ if(epoll_add_fd( epoll_fd, pow_fd) < 0)
+ ERR("pow_fd register control_fd error, error num is %d\n, message is %s\n", errno, strerror(errno));
+
+ release_condition(&lock_for_sync[M_INIT]);
+
+ // now loop
+ for (;;)
+ {
+ struct epoll_event events[5];
+ int ne, nevents;
+ nevents = epoll_wait( epoll_fd, events, 5, -1 );
+ if (nevents < 0)
+ {
+ if (errno != EINTR)
+ ERR("epoll_wait() unexpected error: %s", strerror(errno));
+ continue;
+ }
+
+ for (ne = 0; ne < nevents; ne++)
+ {
+ if ((events[ne].events & (EPOLLERR|EPOLLHUP)) != 0)
+ {
+ ERR("EPOLLERR or EPOLLHUP after epoll_wait() !?");
+ goto Exit;
+ }
+ if ((events[ne].events & EPOLLIN) != 0)
+ {
+ int fd = events[ne].data.fd;
+
+ if (fd == pow_fd)
+ {
+ ERR("!!!!!!!!!!!EPO donwload done");
+ char cmd = 255;
+ int ret;
+
+ //socket
+ char epo_buff[100] = {0};
+ int offset = 0;
+ int read_len;
+
+ read_len = safe_recvfrom(fd, epo_buff, sizeof(epo_buff));
+ if (read_len <= 0) {
+ DBG("@@@@@@@@@gpsinf3337() safe_recvfrom() failed read_len=%d", read_len);
+ break;
+ }
+ cmd = get_int(epo_buff, &offset, sizeof(epo_buff));
+
+ if (cmd == CMD_EPO_DOWNLOAD_DONE) {
+ DBG("@@@@@@@@@@@@got the EPO download msg");
+ callback_backup.create_thread_cb(gps_send_epo_thread, mtk_gps_send_EPO, NULL);
+ }
+ }
+ else if (fd == control_fd)
+ {
+ char cmd = 255;
+ int ret;
+ do {
+ ret = read( fd, &cmd, 1 );
+ } while (ret < 0 && errno == EINTR);
+
+ if (cmd == CMD_QUIT) {
+ DBG("gps thread quitting on demand");
+ goto Exit;
+ }
+ else if (cmd == CMD_START) {
+ if (!started) {
+ started = 1;
+ nmea_reader_set_callback( g_NmeaReader, &state->callbacks);
+ switch (g_delete_aiding_data_flag) {
+ case 1:
+ DBG("Last time's delete_aiding : hot start");
+ ret = write(tty_fd, "$PMTK101*32\r\n", 13);
+ g_EpoSend = true;
+ break;
+ case 2:
+ DBG("Last time's delete_aiding : warm start");
+ ret = write(tty_fd, "$PMTK102*31\r\n", 13);
+ g_EpoSend = true;
+ break;
+ case 3:
+ DBG("Last time's delete_aiding : cold start");
+ ret = write(tty_fd, "$PMTK103*30\r\n", 13);
+ g_EpoSend = true;
+ break;
+ case 4:
+ DBG("Last time's delete_aiding : full start");
+ ret = write(tty_fd, "$PMTK104*37\r\n", 13);
+ g_EpoSend = true;
+ break;
+ default:
+ break;
+ }
+ g_delete_aiding_data_flag = 0;
+ }
+ }
+ else if (cmd == CMD_STOP) {
+ if (started) {
+ started = 0;
+ nmea_reader_set_callback( g_NmeaReader, NULL );
+ release_condition(&lock_for_sync[M_STOP]);
+ DBG("CMD_STOP has been receiving from HAL thread, release lock so can handle CLEAN_UP\n");
+ }
+ }
+ else if (cmd == CMD_RESTART) {
+ g_NmeaReader->fix_mode = 0;
+ DBG("gps 3337 restart!!!!");
+ }
+ }
+ else if (fd == tty_fd)
+ {
+ if(!flag_unlock)
+ {
+ release_condition(&lock_for_sync[M_START]);
+ flag_unlock = 1;
+ DBG("got first NMEA sentence, release lock to set state ENGINE ON, SESSION BEGIN");
+ }
+ if(report_time_interval > ++count){
+ DBG("[trace]count is %f\n", count);
+ //int ret = read( fd, buff, sizeof(buff) );
+ continue;
+ }
+ count = 0;
+ g_NmeaReadStart = true;
+ }
+ }
+ }
+ }
+Exit:
+ DBG("HAL thread is exiting, release lock to clean resources\n");
+ release_condition(&lock_for_sync[M_CLEANUP]);
+ return;
+}
+static void
+gps_state_done( GpsState* s )
+{
+ TRC();
+ char cmd = CMD_QUIT;
+
+ write( s->control[0], &cmd, 1 );
+ get_condition(&lock_for_sync[M_CLEANUP]);
+
+ g_ThreadExitPMTKIn = false;
+ g_hPowerGPS = INVALID_FD;
+ pthread_join(s->pmtk_thread->thread, NULL);
+ g_ThreadExistNmeaRead = false;
+ pthread_join(s->nmea_read_thread, NULL);
+
+ close( s->control[0] ); s->control[0] = -1;
+ close( s->control[1] ); s->control[1] = -1;
+ close( s->pow_fd ); s->pow_fd = -1;
+ close( s->tty_fd ); s->tty_fd = -1;
+ close(s->epoll_hd); s->epoll_hd = -1;
+ s->init = 0;
+ s->test_time -= 1;
+ DBG("GPS cleanup done");
+
+ return;
+}
+
+
+static void
+gps_state_start( GpsState* s )
+{
+ char cmd = CMD_START;
+ int ret;
+
+ do { ret=write( s->control[0], &cmd, 1 ); }
+ while (ret < 0 && errno == EINTR);
+
+ if (ret != 1)
+ ERR("%s: could not send CMD_START command: ret=%d: %s",
+ __FUNCTION__, ret, strerror(errno));
+}
+
+static void
+gps_state_stop( GpsState* s )
+{
+ char cmd = CMD_STOP;
+ int ret;
+
+ do { ret=write( s->control[0], &cmd, 1 ); }
+ while (ret < 0 && errno == EINTR);
+
+ if (ret != 1)
+ ERR("%s: could not send CMD_STOP command: ret=%d: %s",
+ __FUNCTION__, ret, strerror(errno));
+}
+
+static void
+gps_state_restart( GpsState* s )
+{
+ char cmd = CMD_RESTART;
+ int ret;
+
+ do { ret=write( s->control[0], &cmd, 1 ); }
+ while (ret < 0 && errno == EINTR);
+
+ if (ret != 1)
+ ERR("%s: could not send CMD_RESTART command: ret=%d: %s",
+ __FUNCTION__, ret, strerror(errno));
+}
+
+
+static void
+gps_state_init( GpsState* state )
+{
+ state->control[0] = -1;
+ state->control[1] = -1;
+ state->pow_fd = -1;
+ state->tty_fd = -1;
+
+ TRC();
+
+ //socket
+ state->pow_fd = socket_bind_udp(MNLD_HAL2GPS);
+ socket_set_blocking(state->pow_fd, 0);
+ if (state->pow_fd < 0) {
+ ERR("no gps hardware detected: %s:%d, %s", MNLD_HAL2GPS, state->pow_fd, strerror(errno));
+ return;
+ }
+
+ state->tty_fd = open(GPS_TTY_NAME, O_RDWR | O_NOCTTY | O_NONBLOCK);
+ if (state->tty_fd < 0) {
+ close(state->pow_fd);
+ state->pow_fd = -1;
+ ERR("no gps hardware detected: %s:%d, %s", GPS_TTY_NAME, state->tty_fd, strerror(errno));
+ return;
+ }
+ struct termios options;
+ int i4_baud = B115200;
+ tcgetattr(state->tty_fd, &options);
+ cfsetispeed(&options, i4_baud);
+ cfsetospeed(&options, i4_baud);
+
+ options.c_cflag |= (CLOCAL | CREAD);
+ options.c_cflag &= ~PARENB;
+ options.c_cflag &= ~CSTOPB;
+ options.c_cflag &= ~CSIZE;
+ options.c_cflag &= ~PARODD;
+ options.c_cflag |= CS8;
+ options.c_cflag &= ~CRTSCTS;
+ options.c_lflag &= ~(ISIG | ECHO);
+ options.c_oflag &= ~OPOST;
+ options.c_iflag &= ~(INLCR | INPCK | ISTRIP | IXON | BRKINT );
+ options.c_cc[VMIN] = 1;
+ options.c_cc[VTIME] = 0;
+ tcsetattr(state->tty_fd, TCSANOW, &options);
+
+ int epoll_fd = epoll_create(3);
+ state->epoll_hd = epoll_fd;
+
+ if ( socketpair( AF_LOCAL, SOCK_STREAM, 0, state->control ) < 0 ) {
+ ERR("could not create thread control socket pair: %s", strerror(errno));
+ goto Fail;
+ }
+ state->thread = callback_backup.create_thread_cb(gps_native_thread, gps_state_thread, state);
+ if (!state->thread){
+ ERR("could not create gps thread: %s", strerror(errno));
+ goto Fail;
+ }
+
+ DBG("gps state initialized, the thread is %d\n", (int)state->thread);
+ if (!g_ThreadExitPMTKIn)
+ {
+ state->pmtk_thread->thread= callback_backup.create_thread_cb(gps_pmtk_thread, powergps_pmtk_receive_thread, state);
+ if (!state->pmtk_thread->thread){
+ ERR("could not create gps pmtk thread: %s", strerror(errno));
+ goto Fail;
+ }
+ }
+
+ if (!g_ThreadExistNmeaRead)
+ {
+ state->nmea_read_thread = callback_backup.create_thread_cb(gps_nmea_read_thread, gps_read_nmea_from_uart_thread, state);
+ if (!state->nmea_read_thread){
+ ERR("could not create nmea read thread: %s", strerror(errno));
+ goto Fail;
+ }
+ }
+
+ DBG("gps PMTK initialized, the thread is %d\n", (int)state->pmtk_thread->thread);
+
+ return;
+
+Fail:
+ gps_state_done( state );
+}
+
+
+/*****************************************************************/
+/*****************************************************************/
+/***** *****/
+/***** I N T E R F A C E *****/
+/***** *****/
+/*****************************************************************/
+/*****************************************************************/
+static int
+mtk_gps_mt3337_init(GpsCallbacks* callbacks)
+{
+ TRC();
+ GpsState* s = _gps_state;
+ int get_time = 20;
+ int res = 0;
+ if(s->init)
+ return 0;
+ s->callbacks = *callbacks;
+ callback_backup = *callbacks;
+
+ gps_state_init(s);
+ get_condition(&lock_for_sync[M_INIT]);
+ usleep(1000*1);
+ s->init = 1;
+ DBG("Set GPS_CAPABILITY_SCHEDULING \n");
+ callback_backup.set_capabilities_cb(GPS_CAPABILITY_SCHEDULING);
+
+ if (gpshal_gpscbs_save(callbacks) != 0) {
+ return -1; // error
+ }
+
+ gpshal_set_gps_state_intent(GPSHAL_STATE_INIT);
+ gpshal2mnl_gps_init();
+ return 0;
+}
+
+static void
+mtk_gps_mt3337_cleanup(void)
+{
+ GpsState* s = _gps_state;
+
+ TRC();
+
+ if(s->start_flag)
+ get_condition(&lock_for_sync[M_STOP]); //make sure gps_stop has set state to GPS_STATUS_ENGINE_OFF by callback function
+ if(lock_for_sync[M_STOP].condtion == 1)
+ {
+ lock_for_sync[M_STOP].condtion = 0; //make sure gps_stop has set state to GPS_STATUS_ENGINE_OFF in next time
+ }
+ if (s->init)
+ gps_state_done(s);
+ gpshal_set_gps_state_intent(GPSHAL_STATE_CLEANUP);
+ gpshal2mnl_gps_cleanup();
+ DBG("mtk_gps_cleanup done");
+}
+
+int
+mtk_gps_mt3337_start()
+{
+ TRC();
+ GpsState* s = _gps_state;
+ int err;
+ int count=0;
+
+
+ if (!s->init) {
+ ERR("%s: called with uninitialized state !!", __FUNCTION__);
+ return -1;
+ }
+
+ while(s->start_flag == 1)
+ {
+ usleep(100000);
+ count++;
+ DBG("mtk_gps_start:start_flag = %d delay=%d \n",s->start_flag,count*100);
+ }
+ mtk_gps_start_driver();
+ g_GpsDriverStart = true;
+ DBG("mtk_gps_mt3337_start done!!!!");
+ mnl_load_property();
+
+ get_condition(&lock_for_sync[M_START]);
+ gps_state_start(s);
+
+ sta.status = GPS_STATUS_ENGINE_ON;
+ callback_backup.status_cb(&sta);
+ sta.status = GPS_STATUS_SESSION_BEGIN;
+ callback_backup.status_cb(&sta);
+
+ callback_backup.acquire_wakelock_cb();//avoid cpu to sleep
+ s->start_flag = 1;
+
+ gpshal_set_gps_state_intent(GPSHAL_STATE_START);
+ gpshal2mnl_gps_start();
+ return 0;
+}
+
+int
+mtk_gps_mt3337_stop()
+{
+ TRC();
+ GpsState* s = _gps_state;
+ int err;
+ int count=0;
+
+ if (!s->init) {
+ ERR("%s: called with uninitialized state !!", __FUNCTION__);
+ return -1;
+ }
+
+ while(s->start_flag == 0)
+ {
+ usleep(100000);
+ count++;
+ DBG("mtk_gps_stop:start_flag = %d delay=%d \n",s->start_flag,count*100);
+ }
+ s->start_flag = 0;
+
+ mtk_gps_stop_driver();
+ g_GpsDriverStart = false;
+ flag_unlock = 0;
+ gps_state_stop(s);
+ gpshal_set_gps_state_intent(GPSHAL_STATE_STOP);
+ gpshal2mnl_gps_stop();
+
+ callback_backup.release_wakelock_cb();
+ DBG("mtk_gps_mt3337_STOP done!!!!");
+ return 0;
+}
+
+static int
+mtk_gps_mt3337_inject_time(GpsUtcTime time, int64_t timeReference, int uncertainty)
+{
+ ntp_context inject_ntp;
+ long long time_s = 0;
+ int offset = 0;
+
+ TRC();
+ time_s = time/1000;
+ DBG("inject time= %lld,ctime = %s, timeReference = %lld,uncertainty =%d\n", time,ctime(&time_s), timeReference,uncertainty);
+ memcpy(&(inject_ntp.time),&time,sizeof(GpsUtcTime));
+ inject_ntp.timeReference = timeReference;
+ inject_ntp.uncertainty = uncertainty;
+
+ //do not support detail function
+ return 0;
+}
+
+static int
+mtk_gps_mt3337_inject_location(double latitude, double longitude, float accuracy)
+{
+ nlp_context nlp_location;
+ int offset = 0;
+
+ if(clock_gettime(CLOCK_MONOTONIC , &nlp_location.ts) == -1)
+ {
+ ERR("clock_gettime failed reason=[%s]\n",strerror(errno));
+ return -1;
+ }
+ DBG("ts.tv_sec= %lld,ts.tv_nsec = %lld\n", nlp_location.ts.tv_sec,nlp_location.ts.tv_nsec);
+ DBG("inject location lati= %f, longi = %f,accuracy =%f\n", latitude, longitude,accuracy);
+
+ //do not support detail function
+ return 0;
+}
+
+static void
+mtk_gps_mt3337_delete_aiding_data(GpsAidingData flags)
+{
+ /*workaround to trigger hot/warm/cold/full start*/
+ #define FLAG_HOT_START GPS_DELETE_RTI
+ #define FLAG_WARM_START GPS_DELETE_EPHEMERIS
+ #define FLAG_COLD_START (GPS_DELETE_EPHEMERIS | GPS_DELETE_POSITION | GPS_DELETE_TIME | GPS_DELETE_IONO | GPS_DELETE_UTC | GPS_DELETE_HEALTH)
+ #define FLAG_FULL_START (GPS_DELETE_ALL)
+ #define FLAG_AGPS_START (GPS_DELETE_EPHEMERIS | GPS_DELETE_ALMANAC | GPS_DELETE_POSITION | GPS_DELETE_TIME | GPS_DELETE_IONO | GPS_DELETE_UTC)
+ GpsState* s = _gps_state;
+ int ret;
+
+ DBG("%s:0x%X\n", __FUNCTION__, flags);
+
+ gps_state_restart(s);
+
+ if (flags == FLAG_HOT_START)
+ {
+ mtk_restart(MNL_CMD_RESTART_HOT);
+ if (g_GpsDriverStart)
+ {
+ DBG("GPS driver still start!!! send it HOT_START!!!");
+ ret = write(s->tty_fd, "$PMTK101*32\r\n", 13);
+ if (ret < 0)
+ DBG("HOT_START FAILED!!! error is %d : %s", errno, strerror(errno));
+ g_EpoSend = true;
+ }
+ else
+ {
+ g_delete_aiding_data_flag = 1;
+ }
+ }
+ else if (flags == FLAG_WARM_START)
+ {
+ mtk_restart(MNL_CMD_RESTART_WARM);
+ if (g_GpsDriverStart)
+ {
+ DBG("GPS driver still start!!! send it WARM_START!!!");
+ ret = write(s->tty_fd, "$PMTK102*31\r\n", 13);
+ if (ret < 0)
+ DBG("WARM_START FAILED!!! error is %d : %s", errno, strerror(errno));
+ g_EpoSend = true;
+ }
+ else
+ {
+ g_delete_aiding_data_flag = 2;
+ }
+ }
+ else if (flags == FLAG_COLD_START)
+ {
+ mtk_restart(MNL_CMD_RESTART_HOT);
+ if (g_GpsDriverStart)
+ {
+ DBG("GPS driver still start!!! send it COLD_START!!!");
+ ret = write(s->tty_fd, "$PMTK103*30\r\n", 13);
+ if (ret < 0)
+ DBG("COLD_START FAILED!!! error is %d : %s", errno, strerror(errno));
+ g_EpoSend = true;
+ }
+ else
+ {
+ g_delete_aiding_data_flag = 3;
+ }
+ }
+ else if (flags == FLAG_FULL_START)
+ {
+ mtk_restart(MNL_CMD_RESTART_HOT);
+ if (g_GpsDriverStart)
+ {
+ DBG("GPS driver still start!!! send it COLD_START!!!");
+ ret = write(s->tty_fd, "$PMTK104*37\r\n", 13);
+ if (ret < 0)
+ DBG("FULL_START FAILED!!! error is %d : %s", errno, strerror(errno));
+ g_EpoSend = true;
+ }
+ else
+ {
+ g_delete_aiding_data_flag = 4;
+ }
+ }
+ else if(flags == FLAG_AGPS_START)
+ {
+ DBG("Send MNL_CMD_RESTART_AGPS in HAL\n");
+ mtk_restart(MNL_CMD_RESTART_AGPS);
+ }
+}
+
+static int mtk_gps_mt3337_set_position_mode(GpsPositionMode mode, GpsPositionRecurrence recurrence,
+ uint32_t min_interval, uint32_t preferred_accuracy, uint32_t preferred_time)
+{
+ // FIXME - support fix_frequency
+ // only standalone supported for now.
+ DBG("set report location time interval is %d\n", min_interval);
+ if(min_interval <= 1000)
+ report_time_interval = 1;
+ else
+ report_time_interval = (float)min_interval/1000;
+ DBG("set report location time interval is %f s\n", report_time_interval);
+ TRC();
+ return 0;
+}
+
+static const void*
+mtk_gps_mt3337_get_extension(const char* name)
+{
+ TRC();
+ DBG("mtk_gps_get_extension name=[%s]\n", name);
+ if (strcmp(name, AGPS_RIL_INTERFACE) == 0) {
+ return &mtk_agps_ril_inf;
+ }
+/*
+#if EPO_SUPPORT
+ if (!strcmp(name, GPS_XTRA_INTERFACE))
+ return (void*)(&mtkGpsXtraInterface);
+#endif
+*/
+ return NULL;
+}
+
+static const GpsInterface mtkGpsInterface = {
+ sizeof(GpsInterface),
+ mtk_gps_mt3337_init,
+ mtk_gps_mt3337_start,
+ mtk_gps_mt3337_stop,
+ mtk_gps_mt3337_cleanup,
+ mtk_gps_mt3337_inject_time,
+ mtk_gps_mt3337_inject_location,
+ mtk_gps_mt3337_delete_aiding_data,
+ mtk_gps_mt3337_set_position_mode,
+ mtk_gps_mt3337_get_extension,
+};
+
+//=========================================================
+// Between
+// Gps Interface
+// Hardware Module Interface
+
+static const GpsInterface* gps_device__get_gps_interface(
+ __unused struct gps_device_t* device) {
+ /*
+ * hao mt3337 modify
+ * GPS_DEVICE__GET_GPS_INTERFACE__CHECK_PARAM;
+ * hal2mnl_hal_reboot();
+ */
+ return &mtkGpsInterface;
+}
+
+static const struct gps_device_t gps_device = {
+ .common = { // hw_device_t
+ .tag = HARDWARE_DEVICE_TAG,
+ .version = 0, // GPS JNI will not use it
+ .module = &HAL_MODULE_INFO_SYM,
+ .reserved = {0},
+ .close = NULL // GPS JNI will not call it
+ },
+ .get_gps_interface = gps_device__get_gps_interface
+};
+
+
+static int open_gps(const struct hw_module_t* module, char const* name,
+ struct hw_device_t** device)
+{
+ DBG("open_gps HAL 1\n");
+ *device = (struct hw_device_t*)&gps_device;
+ return 0;
+}
+
+
+static struct hw_module_methods_t gps_module_methods = {
+ .open = open_gps
+};
+
+
+struct hw_module_t HAL_MODULE_INFO_SYM = {
+ .tag = HARDWARE_MODULE_TAG,
+ .version_major = 1,
+ .version_minor = 0,
+ .id = GPS_HARDWARE_MODULE_ID,
+ .name = "MediaTek GPS Hardware Module",
+ .author = "MediaTek, Inc.",
+ .methods = &gps_module_methods,
+ .dso = NULL,
+ .reserved = {0}
+};
diff --git a/src/connectivity/gps/gps_hal/src/hal2mnl_interface.c b/src/connectivity/gps/gps_hal/src/hal2mnl_interface.c
new file mode 100644
index 0000000..4d6945b
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/src/hal2mnl_interface.c
@@ -0,0 +1,623 @@
+#include "hal2mnl_interface.h"
+#include "mtk_lbs_utility.h"
+#include "data_coder.h"
+#include "mtk_auto_log.h"
+
+int log_dbg_level = L_DEBUG;
+
+#ifdef LOG_TAG
+#undef LOG_TAG
+#define LOG_TAG "hal2mnl"
+#endif
+
+#ifndef MIN
+#define MIN(A,B) ((A)<(B)?(A):(B))
+#endif
+
+static float count = 0;
+static float report_time_interval = 0;
+
+int hal2mnl_hal_reboot() {
+ LOGI("hal2mnl_hal_reboot");
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+ put_int(buff, &offset, HAL2MNL_HAL_REBOOT);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_gps_init() {
+ LOGI("hal2mnl_gps_init");
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_GPS_INIT);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_gps_start() {
+ LOGI("hal2mnl_gps_start");
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_GPS_START);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+int hal2mnl_gps_stop() {
+ LOGI("hal2mnl_gps_stop");
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_GPS_STOP);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_gps_cleanup() {
+ LOGI("hal2mnl_gps_cleanup");
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_GPS_CLEANUP);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_gps_inject_time(int64_t time, int64_t time_reference, int uncertainty) {
+ /*LOGD("hal2mnl_gps_inject_time time=%zd time_reference=%zd uncertainty=%d",
+ time, time_reference, uncertainty);*/
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_GPS_INJECT_TIME);
+ put_long(buff, &offset, time);
+ put_long(buff, &offset, time_reference);
+ put_int(buff, &offset, uncertainty);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_gps_inject_location(double lat, double lng, float acc) {
+ // LOGD("hal2mnl_gps_inject_location lat,lng %f,%f acc=%f", lat, lng, acc);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_GPS_INJECT_LOCATION);
+ put_double(buff, &offset, lat);
+ put_double(buff, &offset, lng);
+ put_float(buff, &offset, acc);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_gps_delete_aiding_data(int flags) {
+ LOGD("flag=0x%x", flags);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_GPS_DELETE_AIDING_DATA);
+ put_int(buff, &offset, flags);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_gps_set_position_mode(gps_pos_mode mode, gps_pos_recurrence recurrence,
+ int min_interval, int preferred_acc, int preferred_time, bool lowPowerMode) {
+ LOGD("mode=%d recurrence=%d min_interval=%d preferred_acc=%d preferred_time=%d lowpowermode=%d",
+ mode, recurrence, min_interval, preferred_acc, preferred_time, lowPowerMode);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_GPS_SET_POSITION_MODE);
+ put_int(buff, &offset, mode);
+ put_int(buff, &offset, recurrence);
+ put_int(buff, &offset, min_interval);
+ put_int(buff, &offset, preferred_acc);
+ put_int(buff, &offset, preferred_time);
+ put_byte(buff, &offset, lowPowerMode);
+
+ if (min_interval <= 1000) {
+ report_time_interval = 1;
+ } else {
+ report_time_interval = (float)min_interval/1000;
+ }
+ LOGD("set report location time interval is %f s\n", report_time_interval);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_data_conn_open(const char* apn) {
+ LOGD("apn=[%s]", apn);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_DATA_CONN_OPEN);
+ put_string(buff, &offset, apn);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_data_conn_open_with_apn_ip_type(const char* apn, apn_ip_type ip_type) {
+ LOGD("apn=[%s] ip_type=%d",
+ apn, ip_type);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_DATA_CONN_OPEN_WITH_APN_IP_TYPE);
+ put_string(buff, &offset, apn);
+ put_int(buff, &offset, ip_type);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_data_conn_closed() {
+ LOGD("hal2mnl_data_conn_closed");
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_DATA_CONN_CLOSED);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_data_conn_failed() {
+ LOGD("hal2mnl_data_conn_failed");
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_DATA_CONN_FAILED);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_set_server(agps_type type, const char* hostname, int port) {
+ LOGD("type=%d hostname=[%s] port=%d",
+ type, hostname, port);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_SET_SERVER);
+ put_int(buff, &offset, type);
+ put_string(buff, &offset, hostname);
+ put_int(buff, &offset, port);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+ return 0;
+}
+
+int hal2mnl_set_ref_location(cell_type type, int mcc, int mnc, int lac, int cid) {
+ LOGD("ype=%d mcc=%d mnc=%d lac=%d cid=%d",
+ type, mcc, mnc, lac, cid);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_SET_REF_LOCATION);
+ put_int(buff, &offset, type);
+ put_int(buff, &offset, mcc);
+ put_int(buff, &offset, mnc);
+ put_int(buff, &offset, lac);
+ put_int(buff, &offset, cid);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_set_id(agps_id_type type, const char* setid) {
+ LOGD("type=%d setid=[%s]", type, setid);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_SET_ID);
+ put_int(buff, &offset, type);
+ put_string(buff, &offset, setid);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+
+int hal2mnl_ni_message(char* msg, int len) {
+ LOGD("len=%d", len);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_NI_MESSAGE);
+ put_binary(buff, &offset, msg, len);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+#if defined(__LINUX_OS__)
+int hal2mnl_send_pmtk(char* msg, int len) {
+ LOGD("len=%d", len);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_SEND_PMTK);
+ put_binary(buff, &offset, msg, len);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+#endif
+
+int hal2mnl_ni_respond(int notif_id, ni_user_response_type user_response) {
+ LOGD("notif_id=%d user_response=%d",
+ notif_id, user_response);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_NI_RESPOND);
+ put_int(buff, &offset, notif_id);
+ put_int(buff, &offset, user_response);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_update_network_state(int connected, network_type type, int roaming,
+ const char* extra_info) {
+ LOGD("connected=%d type=%d roaming=%d extra_info=[%s]",
+ connected, type, roaming, extra_info);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_UPDATE_NETWORK_STATE);
+ put_int(buff, &offset, connected);
+ put_int(buff, &offset, type);
+ put_int(buff, &offset, roaming);
+ put_string(buff, &offset, extra_info);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_update_network_availability(int available, const char* apn) {
+ LOGD("available=%d apn=[%s]",
+ available, apn);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_UPDATE_NETWORK_AVAILABILITY);
+ put_int(buff, &offset, available);
+ put_string(buff, &offset, apn);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_set_gps_measurement(bool enabled, bool enableFullTracking) {
+ LOGD("enabled=%d, flag=%d", enabled, enableFullTracking);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_GPS_MEASUREMENT);
+ put_int(buff, &offset, enabled);
+ put_int(buff, &offset, enableFullTracking);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_set_gps_navigation(bool enabled) {
+ LOGD("enabled=%d", enabled);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_GPS_NAVIGATION);
+ put_int(buff, &offset, enabled);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_set_vzw_debug(bool enabled) {
+ LOGD("enabled = %d\n", enabled);
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_VZW_DEBUG);
+ put_int(buff, &offset, enabled);
+
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+int hal2mnl_update_gnss_config(const char* config_data, int length) {
+ LOGD("data length:%d\n", length);
+ int offset = 0;
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ put_int(buff, &offset, HAL_MNL_INTERFACE_VERSION);
+
+ put_int(buff, &offset, HAL2MNL_GNSS_CONFIG);
+ put_int(buff, &offset, length);
+ put_string(buff, &offset, config_data);
+ return safe_sendto(MTK_HAL2MNL, buff, offset);
+}
+
+// -1 means failure
+int mnl2hal_hdlr(int fd, mnl2hal_interface* hdlr) {
+ char buff[HAL_MNL_BUFF_SIZE] = {0};
+ int offset = 0;
+ int ver;
+ mnl2hal_cmd cmd;
+ int read_len;
+ int ret = 0;
+
+ read_len = safe_recvfrom(fd, buff, sizeof(buff));
+ if (read_len <= 0) {
+ LOGE("mnl2hal_hdlr() safe_recvfrom() failed read_len=%d", read_len);
+ return -1;
+ }
+ ver = get_int(buff, &offset, sizeof(buff));
+ UNUSED(ver);
+ cmd = get_int(buff, &offset, sizeof(buff));
+
+ switch (cmd) {
+ case MNL2HAL_MNLD_REBOOT: {
+ if (hdlr->mnld_reboot) {
+ hdlr->mnld_reboot();
+ } else {
+ LOGE("mnl2hal_hdlr() mnld_reboot is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_LOCATION: {
+ if (report_time_interval > ++count) {
+ LOGD("count is %f, interval is %f\n", count, report_time_interval);
+ break;
+ }
+ count = 0;
+
+ if (hdlr->location) {
+ gps_location location;
+ get_binary(buff, &offset, (char*)&location, sizeof(buff), sizeof(gps_location));
+ hdlr->location(location);
+ } else {
+ LOGE("mnl2hal_hdlr() location is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_GPS_STATUS: {
+ if (hdlr->gps_status) {
+ gps_status status;
+ get_binary(buff, &offset, (char*)&status, sizeof(buff), sizeof(gps_status));
+ hdlr->gps_status(status);
+ } else {
+ LOGE("mnl2hal_hdlr() gps_status is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_GPS_SV: {
+ if (hdlr->gps_sv) {
+ gnss_sv_info sv;
+ get_binary(buff, &offset, (char*)&sv, sizeof(buff), sizeof(gnss_sv_info));
+ hdlr->gps_sv(sv);
+ } else {
+ LOGE("mnl2hal_hdlr() gps_sv is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_NMEA: {
+ if (hdlr->nmea) {
+ int64_t timestamp = get_long(buff, &offset, sizeof(buff));
+ char* nmea = get_string(buff, &offset, sizeof(buff));
+ int used_length = nmea - buff;
+ int max_length = sizeof(buff) - used_length;
+ int length = get_int(buff, &offset, sizeof(buff));
+ length = MIN(length,max_length);
+ hdlr->nmea(timestamp, nmea, length);
+ } else {
+ LOGE("mnl2hal_hdlr() nmea is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_GPS_CAPABILITIES: {
+ if (hdlr->gps_capabilities) {
+ gps_capabilites capabilities;
+ get_binary(buff, &offset, (char*)&capabilities, sizeof(buff), sizeof(gps_capabilites));
+ hdlr->gps_capabilities(capabilities);
+ } else {
+ LOGE("mnl2hal_hdlr() gps_capabilities is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_GPS_MEASUREMENTS: {
+ if (hdlr->gps_measurements) {
+ gps_data data;
+ get_binary(buff, &offset, (char*)&data, sizeof(buff), sizeof(gps_data));
+ hdlr->gps_measurements(data);
+ } else {
+ LOGE("mnl2hal_hdlr() gps_measurements is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_GPS_NAVIGATION: {
+ if (hdlr->gps_navigation) {
+ gps_nav_msg msg;
+ get_binary(buff, &offset, (char*)&msg, sizeof(buff), sizeof(gps_nav_msg));
+ hdlr->gps_navigation(msg);
+ } else {
+ LOGE("mnl2hal_hdlr() gps_navigation is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_GNSS_MEASUREMENTS: {
+ if (hdlr->gnss_measurements) {
+ gnss_data data;
+ get_binary(buff, &offset, (char*)&data, sizeof(buff), sizeof(gnss_data));
+ hdlr->gnss_measurements(data);
+ } else {
+ LOGE("mnl2hal_hdlr() gnss_measurements is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_GNSS_NAVIGATION: {
+ if (hdlr->gnss_navigation) {
+ gnss_nav_msg msg;
+ get_binary(buff, &offset, (char*)&msg, sizeof(buff), sizeof(gnss_nav_msg));
+ hdlr->gnss_navigation(msg);
+ } else {
+ LOGE("mnl2hal_hdlr() gnss_navigation is NULL");
+ ret = -1;
+ }
+ break;
+ }
+
+ case MNL2HAL_REQUEST_WAKELOCK: {
+ if (hdlr->request_wakelock) {
+ hdlr->request_wakelock();
+ } else {
+ LOGE("mnl2hal_hdlr() request_wakelock is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_RELEASE_WAKELOCK: {
+ if (hdlr->release_wakelock) {
+ hdlr->release_wakelock();
+ } else {
+ LOGE("mnl2hal_hdlr() release_wakelock is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_REQUEST_UTC_TIME: {
+ if (hdlr->request_utc_time) {
+ hdlr->request_utc_time();
+ } else {
+ LOGE("mnl2hal_hdlr() request_utc_time is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_REQUEST_DATA_CONN: {
+ if (hdlr->request_data_conn) {
+ struct sockaddr_storage addr;
+ get_binary(buff, &offset, (char*)&addr, sizeof(buff), sizeof(addr));
+ hdlr->request_data_conn(&addr);
+ } else {
+ LOGE("mnl2hal_hdlr() request_data_conn is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_RELEASE_DATA_CONN: {
+ if (hdlr->release_data_conn) {
+ hdlr->release_data_conn();
+ } else {
+ LOGE("mnl2hal_hdlr() release_data_conn is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_REQUEST_NI_NOTIFY: {
+ if (hdlr->request_ni_notify) {
+ int session_id = get_int(buff, &offset, sizeof(buff));
+ agps_notify_type type = get_int(buff, &offset, sizeof(buff));
+ char* requestor_id = get_string(buff, &offset, sizeof(buff));
+ char* client_name = get_string(buff, &offset, sizeof(buff));
+ ni_encoding_type requestor_id_encoding = get_int(buff, &offset, sizeof(buff));
+ ni_encoding_type client_name_encoding = get_int(buff, &offset, sizeof(buff));
+ hdlr->request_ni_notify(session_id, type, requestor_id, client_name,
+ requestor_id_encoding, client_name_encoding);
+ } else {
+ LOGE("mnl2hal_hdlr() request_ni_notify is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_REQUEST_SET_ID: {
+ if (hdlr->request_set_id) {
+ request_setid flags = get_int(buff, &offset, sizeof(buff));
+ hdlr->request_set_id(flags);
+ } else {
+ LOGE("mnl2hal_hdlr() request_set_id is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_REQUEST_REF_LOC: {
+ if (hdlr->request_ref_loc) {
+ request_refloc flags = get_int(buff, &offset, sizeof(buff));
+ hdlr->request_ref_loc(flags);
+ } else {
+ LOGE("mnl2hal_hdlr() request_ref_loc is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_VZW_DEBUG_OUTPUT: {
+ if (hdlr->output_vzw_debug) {
+ char* str = get_string(buff, &offset, sizeof(buff));
+ hdlr->output_vzw_debug(str);
+ } else {
+ LOGE("mnl2hal_hdlr() output_vzw_debug is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_UPDATE_GNSS_NAME: {
+ if (hdlr->update_gnss_name) {
+ int length = get_int(buff, &offset, sizeof(buff));
+ char* name = get_string(buff, &offset, sizeof(buff));
+ hdlr->update_gnss_name(name, length);
+ } else {
+ LOGE("mnl2hal_hdlr() update_gnss_name is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ case MNL2HAL_REQUEST_NLP: {
+ if (hdlr->request_nlp) {
+ bool independentFromGnss = get_byte(buff, &offset, sizeof(buff));
+ hdlr->request_nlp(independentFromGnss);
+ } else {
+ LOGE("mnl2hal_hdlr() update_gnss_name is NULL");
+ ret = -1;
+ }
+ break;
+ }
+ default: {
+ LOGE("mnl2hal_hdlr() unknown cmd=%d", cmd);
+ ret = -1;
+ break;
+ }
+ }
+
+ return ret;
+}
+
+// -1 means failure
+int create_mnl2hal_fd() {
+ int fd = socket_bind_udp(MTK_MNL2HAL);
+ socket_set_blocking(fd, 0);
+ return fd;
+}
+
diff --git a/src/connectivity/gps/gps_hal/src/hal_mnl_interface_common.c b/src/connectivity/gps/gps_hal/src/hal_mnl_interface_common.c
new file mode 100644
index 0000000..5a691a1
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/src/hal_mnl_interface_common.c
@@ -0,0 +1,173 @@
+#include <inttypes.h>
+
+#include "hal_mnl_interface_common.h"
+#include "mtk_lbs_utility.h"
+#include "mtk_auto_log.h"
+
+#ifdef LOG_TAG
+#undef LOG_TAG
+#define LOG_TAG "gpshal_dump"
+#endif
+
+#if 0
+void dump_gps_location(gps_location in) {
+ LOGD("===== dump_gps_location ====");
+ LOGD("flags=0x%x", in.flags);
+ LOGD("lat=%f", in.lat);
+ LOGD("lng=%f", in.lng);
+ LOGD("alt=%f", in.alt);
+ LOGD("speed=%f", in.speed);
+ LOGD("bearing=%f", in.bearing);
+ LOGD("accuracy=%f", in.accuracy);
+ LOGD("timestamp=%"PRId64, in.timestamp);
+}
+
+void dump_gnss_sv(gnss_sv in) {
+ LOGD("===== dump_gnss_sv ====");
+ LOGD("prn=%d", in.svid);
+ LOGD("constellation=%d", in.constellation);
+ LOGD("snr=%f", in.c_n0_dbhz);
+ LOGD("elevation=%f", in.elevation);
+ LOGD("azimuth=%f", in.azimuth);
+ LOGD("flags=%d", in.flags);
+}
+
+void dump_gnss_sv_info(gnss_sv_info in) {
+ int i = 0;
+ LOGD("===== dump_gnss_sv_info ====");
+ LOGD("num_svs=%d", in.num_svs);
+ for (i = 0; i < in.num_svs; i++) {
+ LOGD("i=%d", i);
+ dump_gnss_sv(in.sv_list[i]);
+ }
+}
+
+void dump_gps_measurement(gps_measurement in) {
+ LOGD("===== dump_gps_measurement ====");
+ LOGD("flags=0x%x", in.flags);
+ LOGD("prn=%d", in.prn);
+ LOGD("time_offset_ns=%f", in.time_offset_ns);
+ LOGD("state=0x%x", in.state);
+ LOGD("received_gps_tow_ns=%"PRId64, in.received_gps_tow_ns);
+ LOGD("received_gps_tow_uncertainty_ns=%"PRId64, in.received_gps_tow_uncertainty_ns);
+ LOGD("c_n0_dbhz=%f", in.c_n0_dbhz);
+ LOGD("pseudorange_rate_mps=%f", in.pseudorange_rate_mps);
+ LOGD("pseudorange_rate_uncertainty_mps=%f", in.pseudorange_rate_uncertainty_mps);
+ LOGD("accumulated_delta_range_state=0x%x", in.accumulated_delta_range_state);
+ LOGD("accumulated_delta_range_m=%f", in.accumulated_delta_range_m);
+ LOGD("accumulated_delta_range_uncertainty_m=%f", in.accumulated_delta_range_uncertainty_m);
+ LOGD("pseudorange_m=%f", in.pseudorange_m);
+ LOGD("pseudorange_uncertainty_m=%f", in.pseudorange_uncertainty_m);
+ LOGD("code_phase_chips=%f", in.code_phase_chips);
+ LOGD("code_phase_uncertainty_chips=%f", in.code_phase_uncertainty_chips);
+ LOGD("carrier_frequency_hz=%f", in.carrier_frequency_hz);
+ LOGD("carrier_cycles=%"PRId64, in.carrier_cycles);
+ LOGD("carrier_phase=%f", in.carrier_phase);
+ LOGD("carrier_phase_uncertainty=%f", in.carrier_phase_uncertainty);
+ LOGD("loss_of_lock=%d", in.loss_of_lock);
+ LOGD("bit_number=%d", in.bit_number);
+ LOGD("time_from_last_bit_ms=%d", in.time_from_last_bit_ms);
+ LOGD("doppler_shift_hz=%f", in.doppler_shift_hz);
+ LOGD("doppler_shift_uncertainty_hz=%f", in.doppler_shift_uncertainty_hz);
+ LOGD("multipath_indicator=%d", in.multipath_indicator);
+ LOGD("snr_db=%f", in.snr_db);
+ LOGD("elevation_deg=%f", in.elevation_deg);
+ LOGD("elevation_uncertainty_deg=%f", in.elevation_uncertainty_deg);
+ LOGD("azimuth_deg=%f", in.azimuth_deg);
+ LOGD("azimuth_uncertainty_deg=%f", in.azimuth_uncertainty_deg);
+ LOGD("used_in_fix=%d", in.used_in_fix);
+}
+
+void dump_gps_clock(gps_clock in) {
+ LOGD("===== dump_gps_clock ====");
+ LOGD("flags=0x%x", in.flags);
+ LOGD("leap_second=%d", in.leap_second);
+ LOGD("type=%d", in.type);
+ LOGD("time_ns=%"PRId64, in.time_ns);
+ LOGD("time_uncertainty_ns=%f", in.time_uncertainty_ns);
+ LOGD("full_bias_ns=%"PRId64, in.full_bias_ns);
+ LOGD("bias_ns=%f", in.bias_ns);
+ LOGD("bias_uncertainty_ns=%f", in.bias_uncertainty_ns);
+ LOGD("drift_nsps=%f", in.drift_nsps);
+ LOGD("drift_uncertainty_nsps=%f", in.drift_uncertainty_nsps);
+}
+
+void dump_gps_data(gps_data in) {
+ size_t i = 0;
+ LOGD("===== dump_gps_data ====");
+ LOGD("measurement_count=%zu", in.measurement_count);
+ for (i = 0; i < in.measurement_count; i++) {
+ LOGD("i=%zu", i);
+ dump_gps_measurement(in.measurements[i]);
+ }
+ dump_gps_clock(in.clock);
+}
+
+void dump_gps_nav_msg(gps_nav_msg in) {
+ LOGD("===== dump_gps_nav_msg ====");
+ LOGD("prn=%d", in.prn);
+ LOGD("type=%d", in.type);
+ LOGD("status=0x%x", in.status);
+ LOGD("message_id=%d", in.message_id);
+ LOGD("submessage_id=%d", in.submessage_id);
+ LOGD("data_length=%zu", in.data_length);
+}
+
+void dump_gnss_data(gnss_data in) {
+ size_t i = 0;
+ LOGD("===== dump_gnss_data ====");
+ LOGD("measurement_count=%zu", in.measurement_count);
+ for (i = 0; i < in.measurement_count; i++) {
+ LOGD("i=%zu", i);
+ dump_gnss_measurement(in.measurements[i]);
+ }
+ dump_gnss_clock(in.clock);
+}
+
+void dump_gnss_measurement(gnss_measurement in) {
+ LOGD("===== dump_gnss_measurement ====");
+ LOGD("flags=0x%x", in.flags);
+ LOGD("svid=%d", in.svid);
+ LOGD("constellation=0x%x", in.constellation);
+ LOGD("time_offset_ns=%f", in.time_offset_ns);
+ LOGD("state=0x%x", in.state);
+ LOGD("received_gps_tow_ns=%"PRId64, in.received_sv_time_in_ns);
+ LOGD("received_gps_tow_uncertainty_ns=%"PRId64, in.received_sv_time_uncertainty_in_ns);
+ LOGD("c_n0_dbhz=%f", in.c_n0_dbhz);
+ LOGD("pseudorange_rate_mps=%f", in.pseudorange_rate_mps);
+ LOGD("pseudorange_rate_uncertainty_mps=%f", in.pseudorange_rate_uncertainty_mps);
+ LOGD("accumulated_delta_range_state=0x%x", in.accumulated_delta_range_state);
+ LOGD("accumulated_delta_range_m=%f", in.accumulated_delta_range_m);
+ LOGD("accumulated_delta_range_uncertainty_m=%f", in.accumulated_delta_range_uncertainty_m);;
+ LOGD("carrier_frequency_hz=%f", in.carrier_frequency_hz);
+ LOGD("carrier_cycles=%"PRId64, in.carrier_cycles);
+ LOGD("carrier_phase=%f", in.carrier_phase);
+ LOGD("carrier_phase_uncertainty=%f", in.carrier_phase_uncertainty);
+ LOGD("multipath_indicator=%d", in.multipath_indicator);
+ LOGD("snr_db=%f", in.snr_db);
+}
+
+void dump_gnss_clock(gnss_clock in) {
+ LOGD("===== dump_gnss_clock ====");
+ LOGD("flags=0x%x", in.flags);
+ LOGD("leap_second=%d", in.leap_second);
+ LOGD("time_ns=%"PRId64, in.time_ns);
+ LOGD("time_uncertainty_ns=%f", in.time_uncertainty_ns);
+ LOGD("full_bias_ns=%"PRId64, in.full_bias_ns);
+ LOGD("bias_ns=%f", in.bias_ns);
+ LOGD("bias_uncertainty_ns=%f", in.bias_uncertainty_ns);
+ LOGD("drift_nsps=%f", in.drift_nsps);
+ LOGD("drift_uncertainty_nsps=%f", in.drift_uncertainty_nsps);
+ LOGD("hw_clock_discontinuity_count=%d", in.hw_clock_discontinuity_count);
+}
+
+void dump_gnss_nav_msg(gnss_nav_msg in) {
+ LOGD("===== dump_gnss_nav_msg ====");
+ LOGD("svid=%d", in.svid);
+ LOGD("type=%d", in.type);
+ LOGD("status=0x%x", in.status);
+ LOGD("message_id=%d", in.message_id);
+ LOGD("submessage_id=%d", in.submessage_id);
+ LOGD("data_length=%zu", in.data_length);
+}
+#endif
diff --git a/src/connectivity/gps/gps_hal/src/mtk_auto_log.c b/src/connectivity/gps/gps_hal/src/mtk_auto_log.c
new file mode 100644
index 0000000..33ab38f
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/src/mtk_auto_log.c
@@ -0,0 +1,109 @@
+/*
+* Copyright Statement:
+*
+* This software/firmware and related documentation ("MediaTek Software") are
+* protected under relevant copyright laws. The information contained herein is
+* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
+* the prior written permission of MediaTek inc. and/or its licensors, any
+* reproduction, modification, use or disclosure of MediaTek Software, and
+* information contained herein, in whole or in part, shall be strictly
+* prohibited.
+*
+* MediaTek Inc. (C) 2017. All rights reserved.
+*
+* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
+* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
+* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
+* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
+* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
+* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
+* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
+* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
+* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
+* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
+* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
+* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
+* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
+* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
+* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
+* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
+* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
+* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
+* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
+*/
+#include <sys/time.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <time.h>
+#include <memory.h>
+
+#include "mtk_auto_log.h"
+
+#if defined(__LINUX_OS__)
+// -1 means failure
+int get_time_str(char* buf, int len) {
+ struct timeval tv;
+ struct timezone tz;
+ struct tm *tm;
+
+ gettimeofday(&tv, &tz);
+ tm = localtime(&tv.tv_sec);
+
+ memset(buf, 0, len);
+ sprintf(buf, "%04d/%02d/%02d %02d:%02d:%02d.%03d",
+ tm->tm_year + 1900, 1 + tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min,
+ tm->tm_sec, (int)(tv.tv_usec / 1000));
+
+ return 0;
+}
+#endif
+
+int set_log_level(int *dst_level, int src_level)
+{
+#if defined(__ANDROID_OS__)
+
+ ALOGI("Current debug level=%d", *dst_level);
+
+ if (src_level < L_VERBOSE || src_level > L_SUPPRESS)
+ {
+ ALOGE("Invalid debug level, level=%d", src_level);
+ ALOGE(" [level] -");
+ ALOGE(" QUIET = 6");
+ ALOGE(" ASSERT = 5");
+ ALOGE(" ERROR = 4");
+ ALOGE(" WARNING = 3");
+ ALOGE(" INFO = 2");
+ ALOGE(" DEBUG = 1");
+ ALOGE(" LOGALL = 0");
+ return -1;
+ }
+
+ *dst_level = src_level;
+
+ ALOGI("New debug level=%d", *dst_level);
+
+#elif defined(__LINUX_OS__)
+
+ printf("Current debug level=%d\n", *dst_level);
+
+ if (src_level < L_VERBOSE || src_level > L_SUPPRESS)
+ {
+ printf("Invalid debug level, level=%d\n", src_level);
+ printf(" [level] -\n");
+ printf(" QUIET = 6\n");
+ printf(" ASSERT = 5\n");
+ printf(" ERROR = 4\n");
+ printf(" WARNING = 3\n");
+ printf(" INFO = 2\n");
+ printf(" DEBUG = 1\n");
+ printf(" LOGALL = 0\n");
+ return -1;
+ }
+
+ *dst_level = src_level;
+
+ printf("New debug level=%d\n", *dst_level);
+
+#endif
+ return 0;
+}
diff --git a/src/connectivity/gps/gps_hal/src/mtk_lbs_utility.c b/src/connectivity/gps/gps_hal/src/mtk_lbs_utility.c
new file mode 100644
index 0000000..cd51ad9
--- /dev/null
+++ b/src/connectivity/gps/gps_hal/src/mtk_lbs_utility.c
@@ -0,0 +1,296 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <sys/time.h>
+#include <time.h>
+#include <stddef.h> // offsetof
+#include <stdarg.h>
+#include <sys/stat.h>
+#include <unistd.h> // usleep
+#include <sys/socket.h>
+#include <string.h>
+#include <fcntl.h>
+#include <arpa/inet.h> // inet_addr
+#include <sys/un.h> // struct sockaddr_un
+#include <pthread.h>
+#include <sys/epoll.h>
+#include <signal.h>
+#include <semaphore.h>
+
+#include "mtk_lbs_utility.h"
+#include "mtk_auto_log.h"
+
+#ifdef LOG_TAG
+#undef LOG_TAG
+#define LOG_TAG "mtk_lbs_utility"
+#endif
+
+void msleep(int interval) {
+ usleep(interval * 1000);
+}
+
+// in millisecond
+time_t get_tick() {
+ struct timespec ts;
+ if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1) {
+ LOGE("clock_gettime failed reason=[%s]", strerror(errno));
+ return -1;
+ }
+ return (ts.tv_sec*1000) + (ts.tv_nsec/1000000);
+}
+
+// in millisecond
+time_t get_time_in_millisecond() {
+ struct timespec ts;
+ if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
+ LOGE("get_time_in_millisecond failed reason=[%s]", strerror(errno));
+ return -1;
+ }
+ return ((long long)ts.tv_sec*1000) + ((long long)ts.tv_nsec/1000000);
+}
+#ifdef __LINUX_OS__
+/*************************************************
+* Timer
+**************************************************/
+// -1 means failure
+timer_t init_timer_id(timer_callback cb, int id) {
+ struct sigevent sevp;
+ timer_t timerid;
+
+ memset(&sevp, 0, sizeof(sevp));
+ sevp.sigev_value.sival_int = id;
+ sevp.sigev_notify = SIGEV_THREAD;
+ sevp.sigev_notify_function = cb;
+
+ if (timer_create(CLOCK_MONOTONIC, &sevp, &timerid) == -1) {
+ LOGE("timer_create failed reason=[%s]", strerror(errno));
+ return (timer_t)-1;
+ }
+ return timerid;
+}
+
+// -1 means failure
+timer_t init_timer(timer_callback cb) {
+ return init_timer_id(cb, 0);
+}
+
+// -1 means failure
+int start_timer(timer_t timerid, int milliseconds) {
+ struct itimerspec expire;
+ expire.it_interval.tv_sec = 0;
+ expire.it_interval.tv_nsec = 0;
+ expire.it_value.tv_sec = milliseconds/1000;
+ expire.it_value.tv_nsec = (milliseconds%1000)*1000000;
+ return timer_settime(timerid, 0, &expire, NULL);
+}
+
+// -1 means failure
+int stop_timer(timer_t timerid) {
+ return start_timer(timerid, 0);
+}
+
+// -1 means failure
+int deinit_timer(timer_t timerid) {
+ if (timer_delete(timerid) == -1) {
+ // errno
+ return -1;
+ }
+ return 0;
+}
+
+#endif
+/*************************************************
+* Epoll
+**************************************************/
+// -1 means failure
+int epoll_add_fd(int epfd, int fd) {
+ struct epoll_event ev;
+ memset(&ev, 0, sizeof(ev));
+ ev.data.fd = fd;
+ ev.events = EPOLLIN;
+ // don't set the fd to edge trigger
+ // the some event like accept may be lost if two or more clients are connecting to server at the same time
+ // level trigger is preferred to avoid event lost
+ // do not set EPOLLOUT due to it will always trigger when write is available
+ if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev) == -1) {
+ LOGE("epoll_add_fd() epoll_ctl() failed reason=[%s]%d epfd=%d fd=%d",
+ strerror(errno), errno, epfd, fd);
+ return -1;
+ }
+ return 0;
+}
+
+// -1 failed
+int epoll_add_fd2(int epfd, int fd, uint32_t events) {
+ struct epoll_event ev;
+ memset(&ev, 0, sizeof(ev));
+ ev.data.fd = fd;
+ ev.events = events;
+ // don't set the fd to edge trigger
+ // the some event like accept may be lost if two or more clients are connecting to server at the same time
+ // level trigger is preferred to avoid event lost
+ // do not set EPOLLOUT due to it will always trigger when write is available
+ if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev) == -1) {
+ LOGE("epoll_add_fd2() epoll_ctl() failed reason=[%s]%d epfd=%d fd=%d",
+ strerror(errno), errno, epfd, fd);
+ return -1;
+ }
+ return 0;
+}
+
+int epoll_del_fd(int epfd, int fd) {
+ struct epoll_event ev;
+ int ret;
+
+ if (epfd == -1)
+ return -1;
+
+ ev.events = EPOLLIN;
+ ev.data.fd = fd;
+ do {
+ ret = epoll_ctl(epfd, EPOLL_CTL_DEL, fd, &ev);
+ } while (ret < 0 && errno == EINTR);
+ return ret;
+}
+
+// -1 failed
+int epoll_mod_fd(int epfd, int fd, uint32_t events) {
+ struct epoll_event ev;
+ memset(&ev, 0, sizeof(ev));
+ ev.data.fd = fd;
+ ev.events = events;
+ if (epoll_ctl(epfd, EPOLL_CTL_MOD, fd, &ev) == -1) {
+ LOGE("epoll_mod_fd() epoll_ctl() failed reason=[%s]%d epfd=%d fd=%d",
+ strerror(errno), errno, epfd, fd);
+ return -1;
+ }
+ return 0;
+}
+
+/*************************************************
+* Local UDP Socket
+**************************************************/
+// -1 means failure
+int socket_bind_udp(const char* path) {
+ int fd;
+ struct sockaddr_un addr;
+
+ fd = socket(PF_LOCAL, SOCK_DGRAM, 0);
+ if (fd < 0) {
+ LOGE("socket_bind_udp() socket() failed reason=[%s]%d",
+ strerror(errno), errno);
+ return -1;
+ }
+ LOGD("fd=%d,path=%s\n", fd, path);
+
+ memset(&addr, 0, sizeof(addr));
+ addr.sun_path[0] = 0;
+ MNLD_STRNCPY(addr.sun_path + 1, path,sizeof(addr.sun_path) - 1);
+ addr.sun_family = AF_UNIX;
+ unlink(path);
+
+ if (bind(fd, (const struct sockaddr *)&addr, sizeof(addr)) < 0) {
+ LOGE("socket_bind_udp() bind() failed path=[%s] reason=[%s]%d",
+ addr.sun_path+1, strerror(errno), errno);
+ close(fd);
+ return -1;
+ }else
+ LOGI("bind ok path=[%s]", addr.sun_path+1);
+ return fd;
+}
+
+// -1 means failure
+int socket_set_blocking(int fd, int blocking) {
+ if (fd < 0) {
+ LOGE("socket_set_blocking() invalid fd=%d", fd);
+ return -1;
+ }
+
+ int flags = fcntl(fd, F_GETFL, 0);
+ if (flags == -1) {
+ LOGE("socket_set_blocking() fcntl() failed invalid flags=%d reason=[%s]%d",
+ flags, strerror(errno), errno);
+ return -1;
+ }
+
+ flags = blocking ? (flags&~O_NONBLOCK) : (flags|O_NONBLOCK);
+ return (fcntl(fd, F_SETFL, flags) == 0) ? 0 : -1;
+}
+
+// -1 means failure
+int safe_sendto(const char* path, const char* buff, int len) {
+ int ret = 0;
+ struct sockaddr_un addr;
+ int retry = 10;
+ int fd = socket(PF_LOCAL, SOCK_DGRAM, 0);
+ if (fd < 0) {
+ LOGE("safe_sendto() socket() failed reason=[%s]%d",
+ strerror(errno), errno);
+ return -1;
+ }
+
+ int flags = fcntl(fd, F_GETFL, 0);
+ if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1){
+ LOGE("fcntl failed reason=[%s]%d",
+ strerror(errno), errno);
+
+ close(fd);
+ return -1;
+ }
+
+ memset(&addr, 0, sizeof(addr));
+ addr.sun_path[0] = 0;
+ MNLD_STRNCPY(addr.sun_path + 1, path,sizeof(addr.sun_path) - 1);
+ addr.sun_family = AF_UNIX;
+
+ while ((ret = sendto(fd, buff, len, 0,
+ (const struct sockaddr *)&addr, sizeof(addr))) == -1) {
+ if (errno == EINTR) {
+ LOGE("errno==EINTR\n");
+ continue;
+ }
+ if (errno == EAGAIN) {
+ if (retry-- > 0) {
+ usleep(100 * 1000);
+ LOGE("errno==EAGAIN\n");
+ continue;
+ }
+ }
+ LOGE("safe_sendto() sendto() failed path=[%s] ret=%d reason=[%s]%d",
+ path, ret, strerror(errno), errno);
+ break;
+ }
+
+ close(fd);
+ return ret;
+}
+
+// -1 means failure
+int safe_recvfrom(int fd, char* buff, int len) {
+ int ret = 0;
+ int retry = 10;
+ int flags = fcntl(fd, F_GETFL, 0);
+ if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1){
+ LOGE("fcntl failed reason=[%s]%d",
+ strerror(errno), errno);
+
+ close(fd);
+ return -1;
+ }
+
+ while ((ret = recvfrom(fd, buff, len, 0,
+ NULL, NULL)) == -1) {
+ LOGW("safe_recvfrom() ret=%d len=%d", ret, len);
+ if (errno == EINTR) continue;
+ if (errno == EAGAIN) {
+ if (retry-- > 0) {
+ usleep(100 * 1000);
+ continue;
+ }
+ }
+ LOGE("safe_recvfrom() recvfrom() failed reason=[%s]%d",
+ strerror(errno), errno);
+ break;
+ }
+ return ret;
+}