Location

The location library provides functionality for retrieving the location of a device using different positioning methods such as:

  • GNSS satellite positioning including Assisted GPS (A-GPS) and Predicted GPS (P-GPS) data.

  • Cellular positioning.

  • Wi-Fi positioning.

Overview

This library provides an API for applications to request the location of a device. The application can determine the preferred order of the location methods to be used along with other configuration information. If a method fails to provide the location, the library performs a fallback to the next preferred method.

Both cellular and Wi-Fi positioning detect the base stations and use web services for retrieving the location. GNSS positioning uses satellites to compute the location of the device. This library can use the assistance data (A-GPS and P-GPS) to find the satellites faster.

Implementation

The location library has a compact API and a location core that handles the functionality that is independent of the location method, such as fallback to the next preferred method and timeouts. Each location method has its own implementation for the location retrieval:

  • GNSS positioning

  • Cellular positioning

    • LTE link controller for getting visible cellular base stations.

    • Sending cell information to the selected location service and getting the calculated location back to the device.

  • Wi-Fi positioning

    • Zephyr’s Network Management API Network Management for getting the visible Wi-Fi access points.

    • Sending access point information to the selected location service and getting the calculated location back to the device.

The default priority order of location methods is GNSS positioning, Wi-Fi positioning and Cellular positioning. If any of these methods are disabled, the method is simply omitted from the list.

Here are details related to the services handling cell information for cellular positioning, or access point information for Wi-Fi positioning:

Requirements

nRF Cloud certificates

When using nRF Cloud for any location data, you must have the certificate provisioned. See Updating the nRF Cloud certificate for more information. nRF9160 DK comes pre-provisioned with certificates for nRF Cloud.

Location service accounts

To use the location services that provide A-GPS or P-GPS, cellular or Wi-Fi positioning data, see the respective documentation for setting up your account and getting the required credentials for authentication:

You can configure the required credentials for the location services using Kconfig options.

Wi-Fi chip

None of the supported DKs have an integrated Wi-Fi chip. You can use an external Wi-Fi chip, such as nRF7002 EK, and connect it to the nRF9160 DK.

Library files

This library is found under lib/location in the nRF Connect SDK folder structure.

Configuration

Configure the following Kconfig options to enable this library:

Configure the following Kconfig options to enable Wi-Fi interface:

The chosen Wi-Fi device needs to be set in Devicetree:

chosen {
  ncs,location-wifi = &mywifi;
};

Configure the following options to enable location methods of your choice:

The following options control the use of GNSS assistance data:

The following option is useful when setting CONFIG_NRF_CLOUD_AGPS_FILTERED:

The following options control the transport method used with nRF Cloud:

Both cellular and Wi-Fi location services are handled externally by the application or selected using the runtime configuration, in which case you must first configure the available services. Use at least one of the following sets of options:

The following options are related to the HERE service and can usually have the default values:

The following options control the default location request configurations and are applied when location_config_defaults_set() function is called:

Usage

To use the Location library, perform the following steps:

  1. Initialize the library with the location_init() function.

  2. Create the configuration (location_config structure).

  3. Set the default values by passing the configuration to the location_config_defaults_set() function together with the list of method types.

  4. Set any required non-default values to the structures.

  5. Call the location_request() function with the configuration.

You can use the location_request() function in different ways, as in the following examples.

Use default values for location configuration:

int err;

err = location_request(NULL);

Use GNSS and cellular and set custom timeout values for them:

int err;
struct location_config config;
enum location_method methods[] = {LOCATION_METHOD_GNSS, LOCATION_METHOD_CELLULAR};

location_config_defaults_set(&config, ARRAY_SIZE(methods), methods);

/* Now you have default values set and here you can modify the parameters you want */
config.timeout = 180 * MSEC_PER_SEC;
config.methods[0].gnss.timeout = 90 * MSEC_PER_SEC;
config.methods[1].cellular.timeout = 15 * MSEC_PER_SEC;

err = location_request(&config);

Use method priority list defined by Kconfig options and set custom timeout values for entire :c:func:location_request operation and cellular positioning:

int err;
struct location_config config;

location_config_defaults_set(&config, 0, NULL);

/* Now you have default values set and you can modify the parameters you want but you
 * need to iterate through the method list as the order is defined by Kconfig options.
 */
for (int i = 0; i < config.methods_count; i++) {
    if (config.methods[i].method == LOCATION_METHOD_GNSS) {
        config.methods[i].cellular.timeout = 15 * MSEC_PER_SEC;
    }
}

err = location_request(&config);

Samples using the library

The following nRF Connect SDK applications and samples use this library:

Limitations

  • The Location library can only have one application registered at a time. If there is already an application handler registered, another initialization will override the existing handler.

  • Cellular neighbor information used for cellular positioning is more accurate on modem firmware (MFW) 1.3.0 compared to earlier MFW releases that do not have an API for scanning the neighboring cells. For MFW releases older than 1.3.0, only serving cell information is provided and it can be hours or days old, or even older, depending on the modem sleep states.

Dependencies

This library uses the following nRF Connect SDK libraries:

It uses the following sdk-nrfxlib library:

It uses the following Zephyr libraries:

API documentation

Header file: include/modem/location.h
Source files: lib/location
group location

Typedefs

typedef void (*location_event_handler_t)(const struct location_event_data *event_data)

Event handler prototype.

Param event_data

[in] Event data.

Enums

enum location_method

Location method.

Values:

enumerator LOCATION_METHOD_CELLULAR

LTE cellular positioning.

enumerator LOCATION_METHOD_GNSS

Global Navigation Satellite System (GNSS).

enumerator LOCATION_METHOD_WIFI

Wi-Fi positioning.

enum location_req_mode

Location acquisition mode.

Values:

enumerator LOCATION_REQ_MODE_FALLBACK

Fallback to next preferred method (default).

enumerator LOCATION_REQ_MODE_ALL

All requested methods are used sequentially.

enum location_event_id

Event IDs.

Values:

enumerator LOCATION_EVT_LOCATION

Location update.

enumerator LOCATION_EVT_TIMEOUT

Getting location timed out.

enumerator LOCATION_EVT_ERROR

An error occurred when trying to get the location.

enumerator LOCATION_EVT_RESULT_UNKNOWN

Application has indicated that getting location has been completed, the result is not known, and the Location library does not need to care about it. This event can occur only if CONFIG_LOCATION_SERVICE_EXTERNAL is set.

enumerator LOCATION_EVT_GNSS_ASSISTANCE_REQUEST

GNSS is requesting A-GPS data. Application should obtain the data and send it to location_agps_data_process().

enumerator LOCATION_EVT_GNSS_PREDICTION_REQUEST

GNSS is requesting P-GPS data. Application should obtain the data and send it to location_pgps_data_process().

enumerator LOCATION_EVT_CELLULAR_EXT_REQUEST

Cellular location request with neighbor cell information is available. Application should send the cell information to cloud services and then call location_cellular_ext_result_set().

enumerator LOCATION_EVT_WIFI_EXT_REQUEST

Wi-Fi location request with Wi-Fi access point information is available. The application should send the access point information to cloud services and then call location_wifi_ext_result_set().

enum location_ext_result

Result of the external request.

Values:

enumerator LOCATION_EXT_RESULT_SUCCESS
enumerator LOCATION_EXT_RESULT_UNKNOWN
enumerator LOCATION_EXT_RESULT_ERROR
enum location_accuracy

Location accuracy.

Values:

enumerator LOCATION_ACCURACY_LOW

Allow lower accuracy to conserve power.

enumerator LOCATION_ACCURACY_NORMAL

Normal accuracy.

enumerator LOCATION_ACCURACY_HIGH

Try to improve accuracy. Increases power consumption.

enum location_service

Location service.

Values:

enumerator LOCATION_SERVICE_ANY

Use any location service that has been configured to be available. This is useful when only one service is configured but can also be used even if several services are available.

enumerator LOCATION_SERVICE_NRF_CLOUD

nRF Cloud location service.

enumerator LOCATION_SERVICE_HERE

HERE location service.

Functions

int location_init(location_event_handler_t event_handler)

Initializes the library.

Initializes the library and sets the event handler function. The first call to this function must be called before going to LTE normal mode. This can be called multiple times, which sets the event handler again.

Parameters
  • event_handler[in] Event handler function.

Return values
  • -EINVAL – Given event_handler is NULL.

  • -EFAULT – Failed to obtain Wi-Fi interface.

Returns

0 on success, or negative error code on failure.

int location_request(const struct location_config *config)

Requests the current position or starts periodic position updates.

Requests the current position using the given configuration. Depending on the configuration, a single position or periodic position updates are given. If the position request is successful, the results are delivered to the event handler function in LOCATION_EVT_LOCATION event. Otherwise LOCATION_EVT_TIMEOUT or LOCATION_EVT_ERROR event is triggered.

In periodic mode, position update is always attempted after the configured interval regardless of the outcome of any previous attempt. Periodic position updates can be stopped by calling location_cancel().

Parameters
  • config[in] Used configuration or NULL to get a single position update with the default configuration. Default configuration has the following location methods in priority order (if they are enabled in library configuration): GNSS, Wi-Fi and Cellular.

Return values
  • -EPERM – Library not initialized.

  • -EBUSY – Previous location request still ongoing.

  • -EINVAL – Invalid configuration given.

Returns

0 on success, or negative error code on failure.

int location_request_cancel(void)

Cancels periodic position updates.

Return values

-EPERM – Library not initialized.

Returns

0 on success, or negative error code on failure.

void location_config_defaults_set(struct location_config *config, uint8_t methods_count, enum location_method *method_types)

Sets the default values to a given configuration.

Parameters
  • config[inout] Configuration to be supplied with default values.

  • methods_count[in] Number of location methods. This must not exceed CONFIG_LOCATION_METHODS_LIST_SIZE.

  • method_types[in] List of location method types in priority order. Location methods with these types are initialized with default values into given configuration. List size must be as given in ‘methods_count’.

const char *location_method_str(enum location_method method)

Return location method as a string.

Parameters
  • method[in] Location method.

Returns

Location method in string format. Returns “Unknown” if given method is not known.

int location_agps_data_process(const char *buf, size_t buf_len)

Feed in A-GPS data to be processed by library.

If Location library is not receiving A-GPS assistance data directly from nRF Cloud, it triggers the LOCATION_EVT_GNSS_ASSISTANCE_REQUEST event when assistance is needed. Once application has obtained the assistance data it can be handed over to Location library using this function.

Note that the data must be formatted similarly to the nRF Cloud A-GPS data, see for example nrf_cloud_agps_schema_v1.h.

Parameters
  • buf[in] Data received.

  • buf_len[in] Buffer size of data to be processed.

Return values
  • -EINVAL – Given buffer is NULL or buffer length zero.

  • -ENOTSUP – CONFIG_LOCATION_GNSS_AGPS_EXTERNAL is not set.

Returns

0 on success, or negative error code on failure.

int location_pgps_data_process(const char *buf, size_t buf_len)

Feed in P-GPS data to be processed by library.

If Location library is not receiving P-GPS assistance data directly from nRF Cloud, it triggers the LOCATION_EVT_GNSS_PREDICTION_REQUEST event when assistance is needed. Once application has obtained the assistance data it can be handed over to Location library using this function.

Note that the data must be formatted similarly to the nRF Cloud P-GPS data, see for example nrf_cloud_pgps_schema_v1.h.

Parameters
  • buf[in] Data received.

  • buf_len[in] Buffer size of data to be processed.

Return values
  • -EINVAL – Given buffer is NULL or buffer length zero.

  • -ENOTSUP – CONFIG_LOCATION_GNSS_PGPS_EXTERNAL is not set.

Returns

0 on success, or negative error code on failure.

void location_cellular_ext_result_set(enum location_ext_result result, struct location_data *location)

Pass cellular location result to the library.

If the Location library is not receiving cellular position directly from services, it triggers the LOCATION_EVT_CELLULAR_EXT_REQUEST event, that indicates the neighbor cell information is ready to be sent to cloud services for location resolution. Then, the application responds with the result.

In addition to ‘success’ and ‘error’ results, the application can indicate that the result is unknown with LOCATION_EXT_RESULT_UNKNOWN. This is useful when the application wants the Location library to proceed irrespective of the outcome. The Location library will try to perform a fallback to the next method, if available, just like in a failure case. If there are no more methods, LOCATION_EVT_RESULT_UNKNOWN event will be sent to the application.

Parameters
  • result[in] Result of the external cellular request.

  • location[in] Cellular location data. Will be used only if result is LOCATION_EXT_RESULT_SUCCESS.

void location_wifi_ext_result_set(enum location_ext_result result, struct location_data *location)

Pass Wi-Fi location result to the library.

If the Location library is not receiving Wi-Fi position directly from the services, it triggers the LOCATION_EVT_WIFI_EXT_REQUEST event, that indicates the access point information is ready to be sent to cloud services for location resolution. Then, the application responds with the result.

In addition to ‘success’ and ‘error’ results, the application can indicate that the result is unknown with LOCATION_EXT_RESULT_UNKNOWN. This is useful when the application wants the Location library to proceed irrespective of the outcome. The Location library will try to perform a fallback to the next method, if available, just like in a failure case. If there are no more methods, LOCATION_EVT_RESULT_UNKNOWN event will be sent to the application.

Parameters
  • result[in] Result of the external Wi-Fi request.

  • location[in] Wi-Fi location data. Will be used only if result is LOCATION_EXT_RESULT_SUCCESS.

struct location_datetime
#include <location.h>

Date and time (UTC).

Public Members

bool valid

True if date and time are valid, false if not.

uint16_t year

4-digit representation (Gregorian calendar).

uint8_t month

1…12

uint8_t day

1…31

uint8_t hour

0…23

uint8_t minute

0…59

uint8_t second

0…59

uint16_t ms

0…999

struct location_data
#include <location.h>

Location data.

Public Members

double latitude

Geodetic latitude (deg) in WGS-84.

double longitude

Geodetic longitude (deg) in WGS-84.

float accuracy

Location accuracy in meters (1-sigma).

struct location_datetime datetime

Date and time (UTC).

struct location_event_data
#include <location.h>

Location event data.

Public Members

enum location_event_id id

Event ID.

enum location_method method

Used location method.

struct location_data location

Current location, used with event LOCATION_EVT_LOCATION.

union location_event_data.[anonymous] [anonymous]

Event specific data.

struct location_gnss_config
#include <location.h>

GNSS configuration.

Public Members

int32_t timeout

Timeout (in milliseconds), meaning how long GNSS is allowed to run when trying to acquire a fix. SYS_FOREVER_MS means that the timer is disabled, meaning that GNSS will continue to search until it gets a fix or the application calls cancel.

Note that this is not real time as experienced by the user. Since GNSS cannot run while LTE is operating, the running time is counted from the instant when GNSS is allowed to start. Library waits until RRC connection is inactive before starting GNSS. If LTE power saving mode (PSM) is enabled and A-GPS is disabled, library waits until modem enters PSM before starting GNSS, thus maximizing uninterrupted operating window and minimizing power consumption.

Default value is 120000 (2 minutes). It is applied when location_config_defaults_set function is called and can be changed at build time with CONFIG_LOCATION_REQUEST_DEFAULT_GNSS_TIMEOUT configuration.

enum location_accuracy accuracy

Desired accuracy level.

If accuracy is set to LOCATION_ACCURACY_LOW, GNSS relaxes the criteria for a qualifying fix and may produce fixes using only three satellites.

If accuracy is set to LOCATION_ACCURACY_HIGH, instead of using the first fix, GNSS is allowed to run for a longer time. This typically improves the location accuracy.

Default value is LOCATION_ACCURACY_NORMAL. It is applied when location_config_defaults_set function is called and can be changed at build time with CONFIG_LOCATION_REQUEST_DEFAULT_GNSS_ACCURACY choice configuration.

uint8_t num_consecutive_fixes

The number of fixes GNSS is allowed to produce before the library outputs the current location when accuracy is set to LOCATION_ACCURACY_HIGH.

If accuracy is set to LOCATION_ACCURACY_NORMAL or LOCATION_ACCURACY_LOW this parameter has no effect.

Default value is 3. It is applied when location_config_defaults_set function is called and can be changed at build time with CONFIG_LOCATION_REQUEST_DEFAULT_GNSS_NUM_CONSECUTIVE_FIXES configuration.

bool visibility_detection

Obstructed visibility detection. If set to true, the library tries to detect situations where getting a GNSS fix is unlikely or would consume a lot of energy. When such a situation is detected, GNSS is stopped without waiting for a fix or a timeout.

See Kconfig for related configuration options.

Default value is false. It is applied when location_config_defaults_set function is called and can be changed at build time with CONFIG_LOCATION_REQUEST_DEFAULT_GNSS_VISIBILITY_DETECTION configuration.

Note

Only supported with modem firmware v1.3.2 or later.

bool priority_mode

Enable GNSS priority mode if GNSS does not get enough runtime due to LTE idle mode operations.

If set to true, the library triggers GNSS priority mode if five consecutive PVT messages indicate that GNSS is blocked by LTE idle mode operations. This is especially helpful if A-GPS or P-GPS is not enabled or downloading assistance data fails and GNSS module has to decode navigation data from the satellite broadcast. Priority mode is disabled automatically after the first fix or after 40 seconds.

If the device attempts to send data during the priority mode, it will be buffered and sent after the priority time window ends. In case of mobile terminated data reception during the priority mode the network will typically buffer the data and sent them to the device once the priority time window ends. However, it is possible that the network drops the data, or some protocol timer expires causing data transfer to fail.

Default value is false. It is applied when location_config_defaults_set function is called and can be changed at build time with CONFIG_LOCATION_REQUEST_DEFAULT_GNSS_PRIORITY_MODE configuration.

struct location_cellular_config
#include <location.h>

LTE cellular positioning configuration.

Public Members

int32_t timeout

Timeout (in milliseconds) of how long the cellular positioning procedure can take. SYS_FOREVER_MS means that the timer is disabled.

Default value is 30000 (30 seconds). It is applied when location_config_defaults_set function is called and can be changed at build time with CONFIG_LOCATION_REQUEST_DEFAULT_CELLULAR_TIMEOUT configuration.

When CONFIG_LOCATION_SERVICE_EXTERNAL is enabled, this timeout stops when event LOCATION_EVT_CELLULAR_EXT_REQUEST is sent. However, timeout specified in location_config structure is still valid.

enum location_service service

Used cellular positioning service.

Default value is LOCATION_SERVICE_ANY. It is applied when location_config_defaults_set function is called.

This parameter is ignored when CONFIG_LOCATION_SERVICE_EXTERNAL is enabled.

struct location_wifi_config
#include <location.h>

Wi-Fi positioning configuration.

Public Members

int32_t timeout

Timeout (in milliseconds) of how long the Wi-Fi positioning procedure can take. SYS_FOREVER_MS means that the timer is disabled.

Default value is 30000 (30 seconds). It is applied when location_config_defaults_set function is called and can be changed at build time with CONFIG_LOCATION_REQUEST_DEFAULT_WIFI_TIMEOUT configuration.

When CONFIG_LOCATION_SERVICE_EXTERNAL is enabled, this timeout stops when event LOCATION_EVT_WIFI_EXT_REQUEST is sent. However, timeout specified in location_config structure is still valid.

enum location_service service

Used Wi-Fi positioning service.

Default value is LOCATION_SERVICE_ANY. It is applied when location_config_defaults_set function is called.

This parameter is ignored when CONFIG_LOCATION_SERVICE_EXTERNAL is enabled.

struct location_method_config
#include <location.h>

Location method configuration.

Public Members

enum location_method method

Location method.

struct location_cellular_config cellular

Configuration for LOCATION_METHOD_CELLULAR.

struct location_gnss_config gnss

Configuration for LOCATION_METHOD_GNSS.

struct location_wifi_config wifi

Configuration for LOCATION_METHOD_WIFI.

struct location_config
#include <location.h>

Location request configuration.

Public Members

uint8_t methods_count

Number of location methods in ‘methods’.

struct location_method_config methods[CONFIG_LOCATION_METHODS_LIST_SIZE]

Selected location methods and associated configurations in priority order.

Index 0 has the highest priority. Number of used methods is indicated in ‘methods_count’ and it can be smaller than the size of this table.

uint16_t interval

Position update interval in seconds.

Set to 0 for a single position update. For periodic position updates the valid range is 1…65535 seconds.

Default value is 0. It is applied when location_config_defaults_set function is called and can be changed at build time with CONFIG_LOCATION_REQUEST_DEFAULT_INTERVAL configuration.

int32_t timeout

Timeout (in milliseconds) for the entire location request.

SYS_FOREVER_MS means that the timer is disabled.

Default value is 300000 (5 minutes). It is applied when location_config_defaults_set function is called and can be changed at build time with CONFIG_LOCATION_REQUEST_DEFAULT_TIMEOUT configuration.

enum location_req_mode mode

Location acquisition mode.

Default value is LOCATION_REQ_MODE_FALLBACK. It is applied when location_config_defaults_set function is called.