Geofence on Android

This section discusses about some Android OS specific GeoFence information.

Introduction

Geofence applications are the ones in which you have a background location task running on the phone by which a flag will be raised when you move into or move out of a predefined area. This is useful for maintaining context awareness, social networks, mobile marketing, tracking, etc. BCM47521/BCM47531 has Geofence feature to minimize the power consumption of whole system. BCM47521/BCM47531 computes position with the on-chip processor. This allows the Host CPU to go to sleep for long periods of time, while Geofence areas are still monitored by the chipset BCM47521/BCM47531 wakes up the Host whenever a Geofence area is entered/exited. The Host in turn notifies the Application.

Background

  • What is Geofence (GF)?
    • Alarm triggers launched by entering/exiting predefined geographic areas
    • Designed to work as a background process for “Always-On” applications
    • Always-on Applications
      Geofencing is an application that sends reports or triggers alarms when a predefined area is crossed. For example, users can be alerted to discounts with e-coupons when walking through a mall, or to “don’t forget the milk” — users can set their own reminder notifications based off of location; also, social networking. One example of location-based reminders is through Google Keep, which uses Android’s Geofence APIs on platforms that support hardware geofencing; this application will automatically take advantage of the hardware geofence solution.
      Geofencing applications run in the background for long periods of time, and their main task is to compute positions (fixes) without the need of assistance from other applications. An ultra-low-power GNSS position solution, or always-on positioning solution, is desirable for these scenarios. Typical applications require notifications when entering or exiting a geofence area, or require periodic reporting of user positions relative to the fence.
      GF_Background_001.jpg
  • Host based Positioning is not a friendly architecture for GF
    • Frequent verification of the GF condition from the host-based SW is not efficient, as the host CPU is not allowed to go to sleep
    • Host-Based Solution
      GNSS positioning requires dedicated hardware, complex software, and protocols. This complexity led GNSS providers to move parts of the software out of the IC to the AP.
      Using a mobile phone’s AP for position computation is one method of reducing the CPU and memory power footprint from the GNSS IC. At the same time, it also increases the power consumed by the platform needed to compute GNSS position, since part of the computation is not performed on the host-based IC. APs may consume approximately 100 mA just to be operational.
      With this type of shared architecture, the CPU and the memory on the GNSS IC are reduced, shrinking the size of the chip and reducing power consumed by the chip. In the below figure we see that the AP is communicating with the dedicated hardware, and the final PVT is computed by the AP. This solution fits well in many applications, such as navigation, where the AP has to run a mapping application at the same time.
      GF_Background_002.jpg
  • Hybrid Positioning.
    • For geofencing, we need a hybrid model, one which keeps GNSS IC complexity similar to the host-based architecture, but also offloads some of the host-based positioning so that the host can go to sleep. In Broadcom’s hybrid mode, the AP does not need to run when GNSS positions are computed. Broadcom’s hybrid IC does not invoke the host AP often, and thus achieves an even lower power footprint. The CPU on the GNSS IC used for computing position is a dedicated one. It needs to be carefully chosen because it has to be powerful enough to compute positions and be as power efficient as possible. All this is done while keeping the GNSS IC area size in mind, to control cost. Detailed analysis and steps were considered to ascertain the minimum requirements for the CPU and other resources to best accomplish the on-chip positioning task. Other considerations: the GNSS IC must be powered even when the AP is suspended, and the GNSS IC must be capable of waking up the AP. The below figure shows a possible implementation using a dedicated I/O signal controlled by the IC to wake up the host AP. With this architecture, the host AP will still be needed to provide some assistance data to the GNSS IC. The assistance provided allows the GNSS IC to not invoke the host AP often and thus achieve an even lower power footprint.
      GF_Background_003.jpg
  • BCM47521 and BCM47531 features on-chip GF
    • Based on BCM4752 and BCM4753, adding an innovative two mode architecture: host-based for Navigation and host-offload (on-chip SW) for Geofence
    • BCM47521/BCM47531 utilizes additional RAM to run the on-chip GF SW
    • While BCM47521/BCM47531 are in host-offload mode, the host CPU is allowed to go to sleep, hence bringing significant system power consumption savings

Process

  • Application defines Geofences (GFs), host-based SW computes a position, then programs the on-chip SW and hands over control to the chip
    • The application pushes the relevant GFs to the host based SW (GLL)
    • The GLL pushes the relevant GFs to the on-chip SW, as well as GNSS Assistance Data
  • BCM47521/BCM47531 periodically checks the GFs condition in Host-Offload Mode
    • IC performs GF checks with a dynamic frequency, depending on the proximity to a GF
    • IC only tries to acquire satellites for a few seconds each attempt, in order to preserve battery, and keeps time from one attempt to the next one
    • If a GF border is crossed, a BCM47521/BCM47531 pin wakes up the host, and the GLL passes the alarm to the responsible application
  • “GF Housekeeping”: process of refreshing assistance in the chip
    • Even if the device has not crossed any GF boundary, the host wakes up regularly for “housekeeping” (pushes fresh assistance to the chip and reprograms the on-chip GF)
    • If the host is woken up for a non-GF related reason, GLL takes advantage of it and runs “GF Housekeeping” thus reducing GF related wakeup time

Geofence Power Savings

Here is the BCM47521 Geofence current measurement.

BCM47521GeofencePowerSavings.png

It tested with below setup.

measurement_setup.png

Power Monitor was used to measure Geofence current.

PowerMonitor.png

This is what we measure.

PowerSaving_2.png

The average current during host-offload searching(re-acquisition) and tracking is 24mA at chip level.
24mA at chip level is equivalent to 12mA at battery level.

PowerSaving_3.png

Geofence Software Architecture

Geofence APIs with Broadcom GPS Library

Broadcom GPS library provides Geofence APIs to add and remove fence information. BCM47521 supports up to 64 Geofence requests simultaneously. Application can add set of a location and a radius to be monitored.

MakeGeofenceReq

  • Definition
        static GlRequest *MakeGeofenceReq(
                                    native_double dLatitude
                                   ,native_double dLongitude
                                   ,native_double dRadius
                                   ,GlReqOnStart    cbOnStart
                                   ,GlReqOnGeofenceEvent cbOnEvent
                                   ,GlOnMemAlloc    cbOnMemAlloc = GL_DFLT_MEM_ALLOC
                                   ,GlOnMemFree     cbOnMemFree = GL_DFLT_MEM_FREE)
    
  • Parameters + dLatitude - Latitude of the fence + dLongitude - Longitude of the fence + dRadius - Radius of the fence + cbOnStart - callback to be invoked when the request starts + cbOnEvent - callback to be invoked when events occur + cbOnMemAlloc - callback to allocate memory + cbOnMemFree - callback to free memory
  • Descriptions + Create request for a Geofence monitoring.

StartRequest

  • Definition
    bool StartRequest(GlRequest *pReq)
    
  • Parameters + pReq - The request that is created by MakeGeofenceReq
  • Descriptions + Method to start positioning request.

StopRequest

  • Definition
    bool StopRequest(GlRequest *pReq)
    
  • Parameters + pReq - The request that is created by MakeGeofenceReq
  • Descriptions + Cancel an ongoing request

Broadcom GPS Library also provides a callback function to notify position and fence information when the monitored Geofence area is entered or exited.

GlReqOnGeofenceEvent

  • Definition
    void (*GlReqOnGeofenceEvent)    (GlRequest *pReq, GL_REQ_GEOFENCE_CODE etCode, const GL_FIX_STATUS *pFixStatus)
    
  • Parameters + pReq - The request that is created by MakeGeofenceReq + etCode - GL_REQ_GEOFENCE_ON_ENTRY, GL_REQ_GEOFENCE_ON_EXIT + pFixStatus - GPS position information.
  • Descriptions + Callback function for getting geofence event

Geofence State Diagram

Broadcom Geofence runs on the BCM47521 with host consuming very little power, and it does not need the host application processor.
Here is the state diagram to understand Geofence Behavior.

Geofence_State.png
State NameDescriptions
Host PositionIf GPS system doesn't have enough aiding data for On Chip Position, it will run as Host Position state.
When it has all aiding data, it will go to On Chip Position mode to save power.
Whenever a new geofence is added, the state is changed to Host Position and do process to handle the geofence information, then it moves back to the previous state.
House KeepingRefresh aiding data for the ASIC and reprogram on-chip geofence parameters
Report Geofence Transition or Geofence statusIf geofence transition is happened, ASIC generates interrupt to wake up Host and proper Geofence event is sent to the application.
And if the GPS system can't monitor geofences because of lack of reliability or unavailability of the GPS signal, it will report the status to application.
After reporting it, it will go back to the previous state quickly.
On Chip PositionASIC runs without Host operation.
ASIC calculates current position and geofence transitions.
To go to On Chip Position, it needs valid position fix and 14 or more valid Ephemeris.
Fence Far Away ModeIf stored geofences are far from current position, ASIC will be totally turned off.
ASIC will wake up periodically to check the distance of geofences.
The turn off period can be changed by the distance of geofences and user speed.
Indoor ModeIf Indoor is detected, ASIC will be turned off to save power.
ASIC will wake up periodically to do indoor detection.

Android Framework

Android Software Interface

Here are general Android hardware interface layers.
Android provides "gps.h" and GpsLocationProvider.cpp as a JNI interface.

Android_Hardware_Abstraction_Layer.png

Android Interface for Apps

Since Android 4.3, it has been providing Geofence functions with Google Play Services.
You can implement Geofence feature with com.google.android.gms.location.LocationClient.

com.google.android.gms.location.LocationClient

The LocationClient is the main entry point for location related APIs, such as location and geofence.

Use the locationClient to:

  • Connect and disconnect to Google Location Services.
  • Request/remove location update callbacks.
  • Request/remove geofences.

If you want to get more detail information, please see the Google developer page <http://developer.android.com/reference/com/google/android/gms/location/LocationClient.html>
And also here is the example code <http://developer.android.com/training/location/geofencing.html#RequestGeofences>

Geofence Call Flow with Google Play Service

Google Play Services is provided with binary, so we don't know the actual implementation of Geofence.
But we could deduce there might be a GMS.GeofenceHardwareService and GMS.GeofenceHardwareManager, so application can create and monitor hardware Geofence.
Here is the call flow for addGeofence() function.

AddGeofence_outlook.png

We can zoom in the Frameworks part.

addGeofence.png

Geofence Call Flow with Location Manager

Android also provides APIs for Geofence. Application defines a Location and a radius to be monitored, and provides an intent (i.e. callback system) to be notified on entry/exit of a Geofence area.

Current LocationManager has functions for Geofence. But it uses Periodic GPS request instead of Hardware Geofence.

addProximityAlert

  • Definition
    public void addProximityAlert (double latitude, double longitude, float radius, long expiration, PendingIntent intent)
    
  • Parameters + latitude - the latitude of the central point of the alert region + longitude - the longitude of the central point of the alert region + radius - the radius of the central point of the alert region, in meters + expiration - time for this proximity alert, in milliseconds, or -1 to indicate no expiration + intent - a PendingIntent that will be used to generate an Intent to fire when entry to or exit from the alert region is detected
  • Descriptions + Set a proximity alert for the location given by the position (latitude, longitude) and the given radius. When the device detects that it has entered or exited the area surrounding the location, the given PendingIntent will be used to create an Intent to be fired. The fired Intent will have a boolean extra added with key KEY_PROXIMITY_ENTERING. If the value is true, the device is entering the proximity region; if false, it is exiting.

removeProximityAlert

  • Definition
    public void removeProximityAlert (PendingIntent intent)
    
  • Parameters + intent - the PendingIntent that no longer needs to be notified of proximity alerts
  • Descriptions + Removes the proximity alert with the given PendingIntent.

Here is the call flow of addProximityAlert.

addProximityAlert.png

Geofence Feature Implementation

Hardware Architecture

To support Host offload Geofence, the host should provides

  • UART (with HW flow control) or I2C
  • Interruptible GPIO for HOST_WAKE

With on-Chip Geofencing of BCM47521, movement across a predefined boundary wakes the Host CPU from a power-saving sleep state.
BCM47521 has HOST_WAKE GPIO pin to wake host on Geofence event. Here is a hardware diagram to support Geofence.

geofence_4.png

Host Wake Requirements

BCM47521 enable the Host Application Processor to go to sleep for long periods of time, while Geofences are still monitored.
Whenever a Geofence is crossed, or when the chipset needs data from the Host, it will start the wake up process in order to have the Host CPU operations.
So there should be a connection to an interrupt on the Host CPU. The Host CPU should wake up and resume the HW flow control in a short time in order to get the serial communication ongoing.
Whenever BCM47521 needs to wake up the Host, it will take the following actions:

  • Assert HOST_WAKE
  • Send WakeUp packet to Host on UART.
  • Wait for Host communication (with some retry mechanism).
  • De-assert HOST_WAKE

If BCM47521 doesn’t get any communication from the Host, it will have a few retries sending WakeUp packets. After some timeout, it will de-assert the WakeUp GPIO and resume normal processing.

geofence_5.png

HOST_WAKE

HOST_WAKE is an output from 47521 that is used to wake up the Host AP.
Whenever the chipset is powered; HOST_WAKE defaults to high impedance pad (not driven) with internal pull-down. It can be connected directly to an IRQ input on the Host CPU.
When HOST_WAKE set, Kernel detects the rising edge of HOST_WAKE, and the Kernel won’t go sleep mode while HOST_WAKE is set (high).

The HOST_WAKE can be reset with two below conditions.

  1. When ASIC gets a proper message from GLL through serial port.
  2. Even if there is no response, it will be reset (low) after 3 seconds.

Note: GLL doesn’t check the HOST_WAKE GPIO status. Only Kernel checks the GPIO.

geofence_6.png

UART Control

BCM47521 uses HW flow control to prevent data lost while the Host AP is asleep. Whenever the Host CPU goes to sleep, it needs to set the HW flow control lines to prevent data lost. BCM47521 Flow Control is active low and designated as nRTS and nCTS.

  • nRTS should be programmed as an output, driven high (stops BCM47521 from sending data)
  • nCTS should be programmed as an input. Whenever the Host AP wakes up from sleep, it needs to reprogram the UART (HW flow control, baudrate, …). The serial communication will resume at that point.

Host Wake Kernel Driver

To wake up host, kernel needs a host_wake device driver.
The driver handles the HOST_WAKE interrupt from ASIC.
Broadcom provides the example of host_wake driver and it tested on Pandaboard.

The example code has

  • bcm_gps_hostwake.c : It is device driver to use Host Wake GPIO.
  • bcm_gps_hostwake.h : It is placed in /include/linux/broadcom folder in kernel. And Board support file can be modified to use Geofence Host Wake as below:
#include <linux/broadcom/bcm_gps_hostwake.h>
//...
// GPS Host Wake for Geofence
#define GPS_HOSTWAKE_GPIO (139)
static struct bcm_gps_hostwake_platform_data gps_hostwake_data = {
    .gpio_hostwake = GPS_HOSTWAKE_GPIO,
};
static struct platform_device bcm_gps_hostwake = {
    .name   = "bcm-gps-hostwake",
    .id = -1,
    .dev    = {
        .platform_data  = &gps_hostwake_data,
    },
};
static void __init board_init(void)
{
//...
    platform_device_register(&bcm_gps_hostwake);
//...

Host CPU setup considerations

There are following considerations in terms of setting up Host CPU when we implement Geofence wake up feature.

  • Host Wakeup GPIO (IRQ) setup
  • UART nRTS setup
  • nSTDBY GPIO and external LNA power

Host Wakeup GPIO (IRQ)

For host wake-up GPIO we need to make sure that this pin can be used as an external interrupt source.

UART nRST

For UART nRTS, as mentioned above, we need to make sure that nRTS pin must be asserted high before going into sleep and put to low after waking-up from sleep.

nSTDBY GPIO and External LNA

For nSTDBY GPIO, we need to make sure that it is asserted high even when Host CPU is in sleep state if gpsd is in Geofence mode because without nSTDBY being high ESW cannot run.
For external LNA power, we need to make it maintained even during AP sleep, because in Geofence mode, BCM47521 needs RF power for satellite signal acquisition. BCM47521 can enable LNA only when it is needed thru using LNA_EN pin.
So the radio of BCM47521 should be on during Host CPU sleep and LNA power should be alive during sleep.


Tests

Run Geofence on WinXP

Geofence can be tested with WinXP executable binary and Triggerfish EVK (that has BCM47521).

Add Geofence to configuration file

At first, configuration file should be changed to add new Geofence job with area information that will be monitored.

<job Id="geofence_test">
    <task>
      <req_geofence FenceLatitude="33.75"   FenceLongitude="-84.389"  FenceRadius="100.0"/>
      <req_geofence FenceLatitude="33.75"   FenceLongitude="-84.3833" FenceRadius="100.0"/>
      <req_geofence FenceLatitude="33.7454" FenceLongitude="-84.389"  FenceRadius="100.0"/>
      <req_geofence FenceLatitude="33.7454" FenceLongitude="-84.3833" FenceRadius="100.0"/>
    </task>
</job>
  • job id: The name of job id which will be used to execute
  • FenceLatitude, FenceLongitude: Latitude, longitude of Geofence (decimal degrees).
  • FenceRadius: Radius of Geofence (meters).

Execute executable binary with Geofence job

Please follow the below steps to run Geofence job on WinXP.

1. Open cmd to run
2. cd SDK_TOP_DIRECTORY
3. cd bin\WinXP 
4. dir 
    a. Make sure that you have glgps_win_xp.exe and gpsconfig.xml 
5. glgps_win_xp.exe gpsconfig.xml geofence_test
    a. The job name is case sensitive 
6. Observe the T/R LEDs blinking on the evaluation kit. 
7. To quit, click on the cmd Window, press "q" on the keyboard. Ctrl-C won't work. 
8. Search for PGLOR,2,GFC in the log file under log directory 
    a. The log directory can be changed with LogDirectory in configuration file.

Check Log file

GPS log file contains internal GPS information and NMEA data as well. NMEA data shows Geofence information and event when Geofence is crossed.

$PGLOR,0,GFC - GeoFence Fix

$PGLOR,0,GFC,2,ddmmyy,hhmmss.ms,4.0,37.3,-121.4,400.0,event[,fixes,trials]*CC
        1  2  3   4          5    6    7      8     9   10     11*  12*

      The fields are:
         - 1    - Sentence version [0]
         - 2    - Sentence identifier "GFC"
         - 3    - request ID
         - 4    - UTC day, month, year
         - 5    - UTC hours, minutes, seconds, 100ths of seconds
         - 6    - Time (seconds) since the request was received
         - 7,8  - Latitude, longitude of geofence (decimal degrees)
         - 9    - Radius of geofence (meters)
         - 10   - Event:
                - IN or OUT from geofence
                - ADD or DELETE geofence
                - YLD
         - 11   - Only for YLD event:  number of fixes
         - 12   - Only for YLD event:  number of trials
         - CC  -  checksum

Here are examples of Geofence NMEA.

EventNMEA
Add Geofence$PGLOR,1,NEW,GEOFENCE,0*1D
$PGLOR,2,GFC,0,240413,022635.25,1.0,37.2006,127.0732,1000,ADD*72
Delete Geofence$PGLOR,2,GFC,0,240413,030358.84,2244.6,37.2006,127.0732,1000,DELETE*1B
$PGLOR,2,END,240413,030358.84,2244.6,GEOFENCE,0*1
In from Geofence$PGLOR,2,GFC,10,240413,022639.32,5.0,37.4980,127.0277,500,IN*3A
Out from Geofence$PGLOR,2,GFC,10,240413,023110.09,277.7,37.4980,127.0277,500,OUT*76
Yield$PGLOR,1,GFC,0,240413,023003.09,210.8,37.2006,127.0732,1000,YLD,3,3*67

Check Geofence log with Broadcom NMEA Log Analyzer

Broadcom NMEA Log Analyzer can convert GPS log to kmz format, Geofence information can be shown graphically in Google Earth.

At first, convert GPS log file to NMEA file with bar2nmea.bat

bar2nmea.bat
        Broadcom GPS Log file can be dragged to this batch file for conversion.
        glgps_win_xp.exe for instance can produce some Broadcom GPS Log file. 
        The output will be nmea file.

Then, convert the NMEA file to kmz to see in Google Earth.

nmea2kmz-g.bat
        Converts NMEA file to Google Earth KMZ file, with green positions without drawing
        estimated accuracy circles. (drag and drop of GLL or nmea file to the batch file is possible)

In Google Earth, green circle shows a Geofence that is defined in configuration file. And it shows IN/OUT events with time.

  • Green Circle : Geofence defined in configuration file.
  • Blue Dot : True Path
  • Green Dot : Geofence Events.
geofence_8.png
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Defines