Sections ▾

Contextual Engine

The contextual engine is the center of ContextHub, adding dynamic capabilities to events generated by your apps through context rules. The contextual engine aims to solve the problem of allowing developers to change how their app behaves based on events generated by a device to create a more seamless experience for end users. Through events, feeds, and context rules, you’ll be able to build more quickly modern, contextually-aware applications your users will enjoy.

Context rules are written in javascript. There are a few pre-existing objects that you can interact with when one of your context rules executes –

Beacon

Beacons are Bluetooth 4.0 Low Energy devices that allow devices to detect proximity to objects within 50 meters. This gives you the ability to give context-sensitive information to your users in areas where GPS, WiFi, and cellular towers cannot pinpoint a user’s exact location, such as deep inside buildings or underground. Here’s how to use the beacon object to interact with beacons in a context rule:

beacon properties

Property Description
uuid Generates a random uuid every time this propery is accessed. You should store the value of this property in a variable if you need to use the same uuid in multiple places.

beacon methods

Method Description
create Creates a new beacon in ContextHub
find Finds a beacon by id
allTagged Finds beacons matching all of the given tags
anyTagged Finds beacons matching any of the given tags
update Updates an existing beacon with new information
destroy Deletes a beacon from the system


Create

Creating a beacon contextual element in ContextHub is simple. Every beacon has a UUID (32 digit hexadecimal character, a major value (ranging from 1-65535), and a minor value (also ranging from 1-65535). UUIDs you use should be unique so beacons from other user’s do not interfere with your app. A combination of these three values should be unique for every beacon you have.

Syntax

beacon.create(tags, name, uuid, major, minor)

Parameter Values
Parameter Description
tags Required. A comma separated string of tags to associate with the beacon. If you don’t want to tag the beacon, you can pass in null or “”.
name Required. The name of the beacon
uuid Required. The uuid of the beacon.
major Optional. The major number for this beacon.
minor Optional. The minor number for this beacon.
Return Value

The id of the newly created beacon.

Example


Find

Retrieve a specific beacon from ContextHub by passing a beacon ID.

Syntax

beacon.find(id)

Parameter Values
Parameter Description
id Required. The id of the beacon you want to retrieve.
Return Value

A beacon object.

Example


All Tagged

Retrieves a group of beacons from ContextHub. Adding more tags separated by commas to the same function call filters only beacons that have all tags on the same beacon.

Syntax

beacon.allTagged(tags)

Parameter Values
Parameter Description
tags Required. A string containing the tag(s) to search for. Multiple tags can be searched for by separating them with commas. Results will contain beacons that match all the specified tags.
Return Value

An array of beacon objects.

Example


Any Tagged

Retrieves a group of beacons from ContextHub. This function returns beacons that match any of the given tags.

Syntax

beacon.anyTagged(tags)

Parameter Values
Parameter Description
tags Required. A string containing the tag(s) to search for. Multiple tags can be searched for by separating them with commas. Results will contain beacons that match any of the specified tags.
Return Value

An array of beacon objects.

Example


Update

Updates an existing beacon.

Syntax

beacon.update(id, data, tags)

Parameter Values
Parameter Description
id Required. The id of the beacon you wish to update.
data Required. Stringified JSON of the beacon attributes that you want updated.
tags Optional. A string containing the tag(s) to assign to the beacon. Multiple tags can be assigned by separating them with commas.
Return Value

Nothing.

Example


Destroy

Destroying a beacon only requires passing the id of the beacon object. The beacon is deleted from ContextHub.

Syntax

beacon.destroy(id)

Parameter Values
Parameter Description
id Required. The id of the beacon you want to delete.
Return Value

Nothing.

Example


Console

The console object allows you to log activity inside your context rule.

Console Methods

Method Description
log Makes a http GET request to the specified url.


Log

Logs the message to the console. You can see the logs from the Logs screen in the developer portal.

Syntax

console.log(message)

Parameter Values
Parameter Description
message Required. Message to log to the console.
Return Value

Nothing.

Example


Device

The device object you allows to find devices in your application.

Device Properties

Property Description
triggeringDevice The device that triggered the event in this context rule. This can be null if the event originated from a trigger and not a device.

Device Methods

Method Description
findByAlias Finds devices by their alias.
findById Finds devices by their device id.
allTagged Finds devices matching all of the given tags.
anyTagged Finds devices matching any of the given tags.
near Finds devices near a location


Find By Alias

Finds devices by their alias.

Syntax

device.findByAlias(alias,...,aliasN)

Parameter Values
Parameter Description
alias Required. One or more aliases to find.
Return Value

Array of device objects.

Example


Find By Id

Finds devices by their device id.

Syntax

device.findById(id,...,idN)

Parameter Values
Parameter Description
id Required. One or more ids to find.
Return Value

Array of device objects.

Example


All Tagged

Finds devices by tags. Adding more tags separated by commas to the same function call filters only devices that have all tags on the same device.

Syntax

device.allTagged(tags)

Parameter Values
Parameter Description
tags Required. A string containing the tag(s) to search for. Multiple tags can be searched for by separating them with commas. Results will contain devices that match all the specified tags.
Return Value

Array of device objects.

Example


Any Tagged

Finds devices by tags. This function returns devices that match any of the given tags.

Syntax

device.anyTagged(tags)

Parameter Values
Parameter Description
tags Required. A string containing the tag(s) to search for. Multiple tags can be searched for by separating them with commas. Results will contain devices that match any of the specified tags.
Return Value

Array of device objects.

Example


Near

Finds devices near a location.

Syntax

device.near(latitude, longitude, radius)

Parameter Values
Parameter Description
latitude Required. The latitude of the position you want to find devices near.
longitude Required. The longitude of the position you want to find devices near.
radius Required. The radius (in meters) from the position you want to find devices near.
Return Value

Array of device objects.

Example


##EVENT
Sensors in modern devices generate a lot of data which ContextHub packages today into an event. The event object contains the event that triggered the execution of the context rule. The event object is readonly and contains the following properties:

Property Description
name The name of the event. This matches the event type of the context rule.
data The data object contains all the properties relevant to this event type. See below for specific structures.
context The context object contains all information known about the device at the time the event was created.
payload Developer-defined custom data sent along with every event generated by the ContextHub SDK.
id A unique identifier for this event.
created_at An ISO8601 timestamp of when the event was received by the server.

###Sample Event

Here is the structure of a sample event:

###Beacon In/Out

The beacon_in/beacon_out event is generated whenever a device enters or exits a beacon region. A beacon region is defined as a UUID + major/minor values, if provided. If not provided, then several beacons having the same UUID will only trigger a beacon_in event once. Inside the data key, there is a beacon key indicating the beacon region which was just entered/exited and the UUID for the beacon region. Major and minor values will be filled only if the monitored region in ContextHub has them (they are not required). To get events about specific beacons, specifically state and accuracy values, look at beacon_changed.

Beacon Changed

The beacon_changed event is generated whenever a device changes proximity of a specific beacon. There are three pre-defined states, immediate_state, near_state, and far_state which are approximately 0-6 inches, 6-12 inches, and 12 inches - 50 feet depending on the range and power setting of the particular beacon used. Within the beacon key of the data key, you will find the specific major and minor values of the beacon, as well as the rssi value giving relative strength. Estimote explains very well here RSSI values and how they relate to distance between a device an a beacon. accuracy is also another key present which gives the approximate distance from the beacon to the device. Given the number of factors that influence wireless signals in an area, the accuracy value should be used as a general guideline, and not relied on in critical scenarios.

###Geofence In/Out

The geofence_in/geofence_out is generated whenever a device enters or exists a circular geofence region. A geofence region is defined as a geospatial center with latitude and longitude, and radius in meters. Inside the data key, there is a fence key indicating the geofence region which was just entered/exited along with the latitude, longitude, and radius of the geofence. The state key determines whether the event was a geofence_in or geofence_out event.

###Location Changed

The location_changed event is generated whenever a device has a significant location change as defined by the platform. For iOS, this is approximately once every 1000 meters, depending on WiFi/cellular tower density and GPS availability. The data structure contains keys related to the latitude, longitude, speed, altitude, and course of the device at the time the event was generated.

Tick

The tick event is a special event that is automatically executed once every minute in the ContextHub server. Using the JavaScript Date() object and checking the time, this allows you the ability to execute commands in ContextHub even with the absence of any events on the server. So instead of your server code simply being reactive to devices, it can be a proactive part of your applications.

###Custom Events

Custom events are events triggered by the developer that have no predefined data structure. These events are manually triggered by the SDK through a specific method, or by posting an event through a feed for web browsers, servers, JavaScript scripts, and IoT-like devices like the Raspberry Pi or Arduino. All custom events must have a defined name key, so they can be processed by the appropriate context rule if it exists and should have the data key representing your custom data structure. Custom events generated by non-SDK devices, will not have either the context or payload unless they are defined by you, the application developer.

Below is a sample of a data structure of a custom event, taken from the [Awareness](/samples/ios/awareness) context rule sample app.


Geofence

Geofences are pre-defined areas of interest that allow your application to be notified when a device has entered or exited that region. Here’s how to use the geofence object to interact with geofences:

geofence methods

Method Description
create Creates a new geofence in ContextHub
find Finds a geofence by id
allTagged Finds geofences matching all of the given tags
anyTagged Finds geofences matching any of the given tags
search Finds geofences within the geographical area
update Updates an existing geofence with new information
destroy Deletes a geofence from the system


Create

Creating a geofence contextual element in ContextHub is simple. Every geofence is defined by a latitude and longitude indicating their center and a radius in meters to create the perimeter.

Syntax

geofence.create(tags, name, latitude, longitude, radius)

Parameter Values
Parameter Description
tags Required. A comma separated string of tags to associate with the geofence. If you don’t want to tag the geofence, you can pass in null or “”.
name Required. The name of the geofence
latitude Required. The latitude of the center of the geofence.
longitude Required. The longitude of the center of the geofence.
radius Required. The radius (in meters) of the geofence.
Return Value

The id of the newly created geofence.

Example


Find

Retrieve a specific geofence from ContextHub by passing a geofence ID.

Syntax

geofence.find(id)

Parameter Values
Parameter Description
id Required. The id of the geofence you want to retrieve.
Return Value

A geofence object.

Example


All Tagged

Retrieves a group of geofences from ContextHub. Adding more tags separated by commas to the same function call filters only geofences that have all tags on the same geofence.

Syntax

geofence.allTagged(tags)

Parameter Values
Parameter Description
tags Required. A string containing the tag(s) to search for. Multiple tags can be searched for by separating them with commas. Results will contain geofences that match all the specified tags.
Return Value

An array of geofence objects.

Example


Any Tagged

Retrieves a group of geofences from ContextHub. This function returns geofences that match any of the given tags.

Syntax

geofence.anyTagged(tags)

Parameter Values
Parameter Description
tags Required. A string containing the tag(s) to search for. Multiple tags can be searched for by separating them with commas. Results will contain geofences that match any of the specified tags.
Return Value

An array of geofence objects.

Example


Retrieves geofences that are within the specified area.

Syntax

search(latitude, longitude, radius)

Parameter Values
Parameter Description
latitude Required. The latitude of the center of the search area.
longitude Required. The longitude of the center of the search area.
radius Required. The radius (in meters) of the search area.
Return Value

An array of geofence objects.

Example


Update

Updates an existing geofence.

Syntax

geofence.update(id, data, tags)

Parameter Values
Parameter Description
id Required. The id of the geofence you wish to update.
data Required. Stringified JSON of the geofence attributes that you want updated.
tags Optional. A string containing the tag(s) to assign to the geofence. Multiple tags can be assigned by separating them with commas.
Return Value

Nothing.

Example


Destroy

Destroying a geofence only requires passing the id of the geofence object. The geofence is deleted from ContextHub.

Syntax

geofence.destroy(id)

Parameter Values
Parameter Description
id Required. The id of the geofence you want to delete.
Return Value

Nothing.

Example


HTTP

The http object allows you to send http requests to external services in a context rule. This allows you
to send data to external servers when interesting events occur inside ContextHub. You will see the status
of your request in your logs, but you will not be able to do anything with the response.

http methods

Method Description
get Makes a http GET request to the specified url.
post Makes a http POST request to the specified url.


Get

Allows you to perform an http GET request to a specific URL. You can specify optional query parameters and headers with the params, and headers parameters. These need to be in the form of JSON strings.

Syntax

http.get(url, params, headers)

Parameter Values
Parameter Description
url Required. The url you are making the request to.
params Optional. Stringified JSON of any query parameters that you want to include.
headers Optional. Stringified JSON of any request headers that you want to include.
Return Value

Nothing.

Example


Post

Allows you to perform an http POST request to a specific URL. You can specify optional headers with the headers parameter. This needs to be in the form of a JSON string.

Syntax

http.post(url, body, headers)

Parameter Values
Parameter Description
url Required. The url you are making the request to.
body Optional. The body of the post request.
headers Optional. Stringified JSON of any request headers that you want to include.
Return Value

Nothing.

Example


Push

The push object allows you to send push notifications across all service platforms (APNS & GCM). By sending notifications to devices with a certain tag, you can send a single notification to IOS and Android devices. Certain APNS keys (alert, badge, sound, category) will be duplicated in the GCM message payload to simplify sending similar messages to different platforms.

When sending notifications to multiple platforms, you need to be mindful of payload size limits:

push methods

Method Description
deliver Sends a push notification to iOS and/or Android devices.


Deliver

Delivers a push notification to one or more devices. There a few ways to determine which devices will receive the notification: push_tokens, device_ids, alias, tags. You need to use at least one of those keys to successfully send a notification.

Syntax

push.deliver(jsonString)

Parameter Values
Parameter Description
jsonString Required. Stringified JSON of the push object to send. See the table below to see all the available options.
Key Platform Type Description
push_tokens APNS/GCM Array An array of APNS device tokens and/or GCM registration ids to send a notification to.
alias APNS/GCM Array An array of device aliases to send a notification to.
device_ids APNS/GCM Array An array device ids to send a notification to. This is the preferred way to send notifications to a single device.
tags APNS/GCM Array An array of device tags to send a notification to. This is the preferred way to send notifications to multiple devices.
tag_operator APNS/GCM String By default, tag matching will match on ANY of the given tags. If you want to send notifications to devices that match ALL of the given tags, set the tag_operator parameter to ALL. The default value is ANY.
exclude_device_ids APNS/GCM Array Array of device ids that you want to exclude from delivering a message to. This is handy when sending notifications to tagged devices and want to exclude one or more devices from that group.
exclude_push_tokens APNS/GCM Array Array of push tokens that you want to exclude from delivering a message to. This is handy when sending notifications to tagged devices and want to exclude one or more devices from that group.
mdm APNS String APNS Mobile Device Management magic key. You most likely don’t want to use this. This is an APNS specific key.
priority APNS Integer Sets the APNS priority. Can be either be set to 10 (immediate) or 5 (conserve power). This is an APNS specific key. Defaults to 10.
expiry APNS/GCM Integer Identifies when a notification is no longer valid and can be discarded. APNS notifications default to one day. GCM notifications default to 4 weeks.
category APNS String Sets the APNS category for push. This key will be added to the GCM data payload if it exists and the data payload does not already contain a category key.
url_args APNS String Sets the url-args in the aps section of the APNS payload. This is an APNS specific key used for notifications to web browsers.
badge APNS Integer The number to display as the badge of the app icon. If this property is absent, the badge is not changed. To remove the badge, set the value of this property to 0. This key will be added to the GCM data payload if it exists and the data payload does not already contain a badge key.
sound APNS String The name of a sound file in the app bundle. The sound in this file is played as an alert. If the sound file doesn’t exist or default is specified as the value, the default alert sound is played. The audio must be in one of the audio data formats that are compatible with system sounds. This key will be added to the GCM data payload if it exists and the data payload does not already contain a sound key.
alert APNS String or Object If this property is included, the system displays a standard alert. You may specify a string as the value of alert or a dictionary as its value. If you specify a string, it becomes the message text of an alert with two buttons: Close and View. If the user taps View, the app is launched. Alternatively, you can specify a dictionary as the value of alert. This key will be added to the GCM data payload if it exists and the data payload does not already contain a alert key.
content_available APNS Integer Provide this key with a value of 1 to indicate that new content is available. Including this key and value means that when your app is launched in the background or resumed, application:didReceiveRemoteNotification:fetchCompletionHandler: is called. Newsstand apps are guaranteed to be able to receive at least one push with this key per 24-hour window. This is an APNS specific key.
collapse_key GCM String A collapse key is an arbitrary string that is used to collapse a group of like messages when the device is offline, so that only the most recent message gets sent to the client. For example, New mail, Updates available, and so on. GCM allows a maximum of 4 different collapse keys to be used by the GCM server at any given time. If you exceed this number GCM will only keep 4 collapse keys, with no guarantees about which ones they will be. This is an GCM specific key.
data APNS/GCM Object For APNS devices, this adds custom keys to the payload data. For GCM devices, this is the message payload. Any valid JSON is acceptable. GCM messages will have the ‘alert’, ‘badge’, ‘sound’, ‘category’ keys added to the payload if they have been set and the keys do not already exist in the payload.
Return Value

Nothing.

Example


Vault

The vault object provides access to the vault document store.

vault methods

Method Description
create Adds a new document to the vault.
find Retreives a document from the vault via id.
allTagged Finds vault objects matching all of the given tags
anyTagged Finds vault objects matching any of the given tags
search Finds vault objects containing the given term.
keyPath Finds vault objects with the given key path.
update Updates an existing vault object with new information
destroy Deletes a vault object from the system


Create

Stores the given json data in the vault with the given tags.

Syntax

vault.create(data, tags)

Parameter Values
Parameter Description
data Required. Stringified JSON of the data you want to store in the vault.
tags Required. A comma separated string of tags to associate with the vault object. If you don’t want to tag the vault object, you can pass in null or “”.
Return Value

The id of the newly created vault object.

Example


Find

Retreives a document from the vault via id.

Syntax

vault.find(id)

Parameter Values
Parameter Description
id Required. The id of the vault object to find.
Return Value

A vault object.

Property Description
data Your data is stored under the data propery.
vault_info Object containing metadata about the vault object.
vault_info Properties Description
id The vault object id.
tags Array of tags assigned to the vault object.
created_at Timestamp of when the object was created.
updated_at Timestamp of when the object was last updated.
tag_string Tags as a comma separated string
Example


All Tagged

Finds vault objects that contain all the specified tags.

Syntax

vault.allTagged(tags)

Parameter Values
Parameter Description
tags Required. A string containing the tag(s) to search for. Multiple tags can be searched for by separating them with commas. Results will contain vault objects that match all the specified tags.
Return Value

An array of vault objects.

Example


Any Tagged

Finds vault objects that contain any of the specified tags.

Syntax

vault.anyTagged(tags)

Parameter Values
Parameter Description
tags Required. A string containing the tag(s) to search for. Multiple tags can be searched for by separating them with commas. Results will contain vault objects that match any the specified tags.
Return Value

An array of vault objects.

Example

Search

Finds all vault objects that contain the given term. You can use the following search operators in your queries to fine tune your results. You can use parentheses to set operator precedence.

Operator Example
Not !term
And term1 & term2
Or term1 | term2
Syntax

vault.search(term)

Parameter Values
Parameter Description
term Required. A string containing the term to search for. Any documents containing the term will be returned.
Return Value

An array of vault objects.

Example


KeyPath

Finds all vault objects that have the specified key path. If a value is provided, then documents that have the value
at the key path will be returned.

Syntax

vault.keyPath(key, value)

Parameter Values
Parameter Description
key Required. A string containing the key to search for. Use dot notation ‘address.city’ for specifying a nested key.
value Optional. If provided documents that match the value at the key will be returned. Otherwise, all documents that contain the key will be returned.
Return Value

An array of vault objects.

Example


Update

Replaces the vault object at the given id with the given data.

Syntax

vault.update(id, data, tags = nil)

Parameter Values
Parameter Description
id Required. The id of the vault object to update.
data Required. Stringified JSON of the data you want to store in the vault.
tags Optional. A comma separated string of tags to associate with the vault object. If you don’t want to update the tags, you can omit this parameter.
Return Value

Nothing.

Example

Destroy

Deleting a vault items only requires passing the id to the vault object. The vault item is deleted from ContextHub.

Syntax

vault.destroy(id)

Parameter Values
Parameter Description
id Required. The id of the vault object to delete.
Return Value

Nothing.

Example