NAV
cURL PHP

Introduction

Welcome to the Pegasus API Documentation!

This documentation gives you access to the entire Pegasus stack, including live communication, device interaction and historical data. The documentation is designed to make it easy to interact with DCT’s suite of IoT devices that are currently supported on Pegasus, allowing you to deploy highly customizable solutions.

If you find yourself stuck or don’t have a clear understanding of what’s going on, please don’t hesitate to post issues on our public repo and join the conversation in our Gitter.

The documentation was generated using Slate.

Background

Digital Communication Technologies (DCT) manufactures intelligent devices which collect data from different sensors and accessories as well as GPS satellites simulatenously.

These intelligent devices send all their data in realtime to a server called: Pegasus Gateway or just Pegasus. Pegasus works as a central server where all the data is collected, analyzed and then exposed via the API for easy viewing.

The API allows you to query any of the 300+ parameters the devices and their sensors expose. It is also a way for you to interact directly with the device, allowing you to make changes to the configuration, create rules, customizable actions depending on device states, and much more with easy to understand API commands.

Pegasus Overview

Multiple Pegasus servers can exist, in fact there are multiple Pegasus servers deployed around the world, each server having a custom URL or subdomain which is controlled by a Pegasus owner via a licensed fee.

pegasusOverview image

At the core of each Pegasus site, the API is the same. The requests are built the same way, the only difference being the base URL.

Base URL

https://sitedomain.com/api

https://pegasus1.pegasusgateway.com/api

The base URL is the domain where the Pegasus server is hosted, in our case it’s used to identify where the requests will be built from.

API Reference

https://sitedomain.com/api/docs

https://pegasus1.pegasusgateway.com/api/docs

The Pegasus API reference allows you to test all the methods directly with your site, it can be found under the path /api/docs

Demo

API Reference Login

user: developer@digitalcomtech.com

pass: deV3lopErs

Throughout the guide we’ll work on a Demo server called: Pegasus1

The vehicles we’ll work with are:

vehicle_id name imei device features
2600 PruIng1-TDX566 356612022409637 Syrus 2 Engine data
1956 (1) TEST HALL 357042062920955 Syrus 3G BT Photo data
691 Stand 4 - Syrus Mobile 357042063193172 Syrus 3G BT Device outputs (sensors / buzzers)
3168 Syrus OBDII SO3G-3 357041069434986 Syrus OBDII Engine data
3005 Titan 4G 869912030003715 Titan GPS data & temperature

Versioning

/api

{
  "date": "Sep 28 15:01:56 2018",
  "live-url": "https://live.pegasusgateway.com",
  "tag": "2.36.4",
  "name": "2.36.4"
}

To consult the version of your API use the /api endpoint.

field description
date Time of last update
live-url Socket communication endpoint
tag Version tag
name major.minor.patch

Breaking changes may occur on major and minor numbers. Patches, are not expected to affect compatibility.

For future version releases and changelog go to Github - Releases.

Also subscribe to our mailing list for updates.

Resource Patterns

Resources URI patterns try to follow the general convention:

/vehicles represents all the vehicles

/vehicles/:id represents a particular vehicle ID

/vehicles/:id/remote/state see the state of a particular vehicle ID

/vehicles/:id/routes see the routes of a particular vehicle ID

etc.

Pagination

api/vehicles?set=2&page=2

{
  "set": 2,
  "total": 5,
  "data": [...],
  "page": 2,
  "pages": 3
}

Requests to a collection of resources (such as: Users, Vehicles, Devices) are automatically paginated and will return a set of 200 resources by default. You can request up to 1000 entries per page (up to 500 Devices) by using the set parameter.

You will see the following additional parameters in the request.

parameter description
set Number of items in current page
page current page
pages total number of pages
total total number of items

HTTP

Verbs

verb meaning
GET Used for retrieving resources.
POST Used for creating resources, sending-info, actions
PUT Used for replacing/updating resources.
DELETE Used for deleting resources.

Status

code description meaning
200 OK General success status code.
201 CREATED Entity has been created (POST request successful). Response body content may or may not be present.
204 NO CONTENT Status when wrapped responses are not used and nothing is in the body (e.g. DELETE).
304 NOT MODIFIED Used in response to conditional GET calls to reduce bandwidth usage.
400 BAD REQUEST General error when fulfilling the request would cause an invalid state. Domain validation errors, missing data, etc.
401 UNAUTHORIZED User is not authenticated with Gateway, does not have the required scopes, or does not share groups with requested entity
403 FORBIDDEN User is not allowed to perform operation, regardless of scopes or admin level.
404 NOT FOUND Used when the requested resource is not found, whether it doesn’t exist or if there was a 401 or 403 that, for security reasons, the service wants to mask.
409 CONFLICT Whenever a resource conflict would be caused by fulfilling the request. Duplicate entries, deleting root objects when cascade-delete not supported are a couple of examples.
429 TOO MANY REQUESTS Too many requests in a given amount of time, both global limits as well as per-resource and per-user limits apply. See rates.
500 INTERNAL SERVER ERROR Catch-all error when the server-side throws an exception.

Rates

The API handles limits to the different resources on a per user and global rate:

Rawdata & Counters:

Trips:

Other resources such as vehicles, groups, assets, etc. apply an anti DOS (Denial of Service) limit, which would only be reached if various machines spam the API.

Whenever you hit the limit the API returns a 429 Status Code. At which point it is important that your app suspends more subsequent requests to the API until the limit is reset.

{
  "reason": "vehicles",
  "message": "Rate exceeded",
  "limit": 10,
  "id": "ec2ec6e51a42f40d12e7009787d833b8",
  "value": 11.0455
}
> HTTP/1.1 429 TOO MANY REQUESTS
> Connection: keep-alive
> Content-Length: 135
> Content-Type: application/json
> Date: Sun, 30 Sep 2018 16:45:13 GMT
> Server: nginx
> X-Peg-Id: 1
> X-Peg-Server: F
> X-Peg-User-Id: 54
> X-RateLimit-Limit: 10
> X-RateLimit-Remaining: 0
> X-RateLimit-Reset: 1538325923


{reason: "vehicles", message: "Rate exceeded", limit: 10, id: "ec2ec6e51a42f40d12e7009787d833b8",…}

The API returns some response headers which include X-RateLimit-* keys so you know when it’s safe to make requests again.

The response on the right hand side tells us there’s a limit of 10 requests, and the client has 0 remaining, the limit resets back to 10 at the following epoch timestamp: 1445098790 - Sun Sep 30 2018 14:45:23 GMT

field description
reason resource that reached limit
message description
limit amount of request allowed
id internal use
value rate of requests
header description
X-RateLimit-Limit resource limit
X-RateLimit-Remaining amount of requests that remain
X-RateLimit-Reset when it’s safe to make more requests

Authentication

Normal login

curl -X POST https://pegasus1.pegasusgateway.com/api/login \
    --header 'Content-Type: application/json' \
    -d '{"username":"developer@digitalcomtech.com",
        "password":"deV3lopErs"}'

{"message":"User successfully authenticated","app":null,"auth":"7ebbd199ecb10a156bdc189d3e0cd8ad9f9b676979deaaadca3612c0"}

Infinite token login

curl -X POST https://pegasus1.pegasusgateway.com/api/login \
    --header 'Content-Type: application/json' \
    -d '{"username":"developer@digitalcomtech.com",
        "password":"deV3lopErs", "scheme": "infinite"}'

{"message":"User successfully authenticated","app":null,"auth":"7ebbd199ecb10a156bdc189d3e0cd8ad9f9b676979deaaadca3612c0"}

POST api/login

Body

{
  "username": "developer@digitalcomtech.com",
  "password": "deV3lopErs"
}

Response

{
  "message": "User successfully authenticated",
  "app": null,
  "auth": "7ebbd199ecb10a156bdc189d3e0cd8ad9f9b676979deaaadca3612c0"
}

To authenticate use the /login resource.

param description
username your username (email address)
password your password
scheme set to infinite to generate an infinite token
app custom name to manage tokens
expires expiration of token in seconds (default: 3600)

A successful login returns a token that has to be used on every subsequent request. Tokens expire after 60 minutes of no requests made with the token, unless you set the scheme to infinite.

The token that’s generated has to be sent on a header called Authenticate in order to retrieve data from the API.
Authenticate: 7ebbd199ecb10a156bdc189d3e0cd8ad9f9b676979deaaadca3612c0

When sending JSON make sure you use the following Content-Type header
Content-Type: application/json

Sessions

View tokens you have created

api/user/sessions

{
  "tokens": [
    {
      "origin": "--",
      "scopes": "groups=285&write=remote.output,tasks",
      "app": "myApp",
      "expires": 7183,
      "token": "9c56c37b52ff3b96ed0a501ac63e574fcb42c32a28c251c2a2033724",
      "app_scheme": "",
      "scheme": "finite"
    }
  ],
  "session": {
    "origin": "--",
    "scopes": "",
    "app": "None",
    "expires": 3600,
    "token": "7ebbd199ecb10a156bdc189d3e0cd8ad9f9b676979deaaadca3612c0",
    "app_scheme": "",
    "scheme": "normal"
  }
}

You can manage tokens and the current session with the /user/sessions resource. You can also create your own tokens with a POST to the same resource

param description
scheme infinite or finite token
limit limit of token in seconds
app custom app name
scopes specify the group(s) id that the token has access to, and any scope
app_scheme pegasus application use only

Create a scoped API token

curl -X POST https://pegasus1.pegasusgateway.com/api/user/sessions \
    --header 'Content-Type: application/json' \
    --header 'Authenticate: 7ebbd199ecb10a156bdc189d3e0cd8ad9f9b676979deaaadca3612c0' \
    -d '{"scheme":"infinite","app":"myApp","scopes":"groups=285&write=remote.output,tasks"}'

Remove a token

curl https://pegasus1.pegasusgateway.com/api/logout?auth=640c59b1df21aed608fe9cb775d56faaea9e33dd74730e31a94456e2 \
    --header 'Content-Type: application/json'

{"message": "Session terminated"}

Scopes

api/user

{
  "username": "developer@digitalcomtech.com",
  "scopes": {
    "sims": "r",
    "tasks": "w",
    "remote.phones": "w",
    "pindrops": "w",
    "remote.tracking_resolution": "w",
    "remote.gps_status": "w",
    "remote.diagnostic": "w",
    "users": "r",
    "vehicles.counters": "r",
    "geofences:visibility.all": "r",
    "groups.vehicles": "r",
    "remote.trigger_position_event": "w",
    "remote.safe_immo": "w",
    "remote.call": "w",
    "geofences": "w",
    "remote.output": "w",
    "remote.speed": "w",
    "remote.sms_alias": "w",
    "rawdata": "w",
    "remote.state": "w",
    "remote.ecu_console": "w",
    "remote.rpm": "w",
    "remote.outputsetlog": "w",
    "groups": "r",
    "remote.configuration": "w",
    "plugins.photocam": "w",
    "remote.fwupdate": "w",
    "remote": "w",
    "assets": "r",
    "geofences:visibility.groups": "r",
    "triggers": "w",
    "vehicles": "r",
    "devices": "r",
    "groups.assets": "r",
    "groups.users": "r",
    "remote.console": "w",
    "remote.mdt": "w",
    "plugins.garmin": "w",
    "plugins.lumeway": "w"
  },
  "first_name": "Juan",
  "last_name": "Noh",
  "is_superuser": false,
  "is_active": true,
  "__updated": 1538367457.1485951,
  "id": 632,
  "phone": "9999698536",
  "is_staff": false,
  "last_login": 1538367457.01,
  "groups": [
    404
  ],
  "prefs": {
    "fuelunits": "gallon",
    "distance": "mile",
    "temperature": "F",
    "language": "en",
    "distanceunits": "mile",
    "volume": "gallon",
    "coords": "WGS84",
    "hour_format": 12,
    "system_notifications": {}
  },
  "email": "developer@digitalcomtech.com",
  "date_joined": 1396137176.0
}

A user’s access to the API resources is controlled by their what groups they belong to and the scopes they have assigned.

When a user belongs to a particular group they can see all the entities (vehicles, sims, assets, devices, etc) that group has associated.

Scopes are identified by the name of the resource and then the letter’s: r or w corresponding to their access level for that resource

r : read-only permissions : GET

w : read and write permissions : POST + PUT + DELETE

For example, a user with scopes: { "triggers": "r", "vehicles": "w" } has read permission for triggers and write permissions for vehicles allowing the user to only read triggers as well as create, edit, and delete vehicles

List of available scopes - resources/users/scopes

resource permission description API
assets read see the assets (drivers, things, etc) assets
assets write create and edit assets (drivers, things, etc) assets
configurations read read the managed configurations configurations
device.mute read view mute status devices
device.mute write mute device events devices
devices read view devices devices
entities.link write associate two separte entities entities
forwarders read view forwarder status forwarders
geofences read view geofences geofences
geofences write create and edit your own geofences geofences
geofences:visibility.all write create public geofences geofences
geofences:visibility.groups write create geofences for your group geofences
groups read read the groups and its’ info groups
groups write create and edit groups groups
groups.assets write manage assets within your group assets
groups.users write manage users within your group users
groups.vehicles write manage vehicles within your group vehicles
pindrops write create a pindrop (safe zone) around an entity pindrops
plugins.garmin read see garmin jobs & messages plugins.garmin
plugins.garmin write create garmin jobs and send garmin messages plugins.garmin
plugins.lumeway read read the lumeway data plugins.lumeway
plugins.lumeway write take a photo with the lumeway accessory plugins.lumeway
plugins.photocam read see the photos photos
plugins.photocam write take photos photos
plugins.satcom read see satcom parameters satcom
plugins.satcom write set satcom parameters satcom
rawdata read get the vehicle’s rawdata rawdata
remote read see the remote GET methods remote
remote write ability to execute all remote commands remote
remote.call write call an authorized number remote
remote.configuration write set a managed configuration remote
remote.console write send console (freestyle) commands remote
remote.fwupdate write execute a firmware update remote
remote.mdt write send mdt (serial port) messages remote
remote.output write set an output remote
remote.phones write authorize a number remote
remote.rpm write set rpm threshold remote
remote.safe_immo write execute a safe engine immobilization remote
remote.sms_alias write set an sms_alias for actions remote
remote.speed write set a speed limit threshold remote
remote.tracking_resolution write set tracking resolution remote
routes read see entity routes routes
routes write create routes routes
sims read see the SIMs info sims
tasks read view a task tasks
tasks write create/edit a task tasks
triggers read see the triggers assigned to your user triggers
triggers write create and edit triggers triggers
users read read the user’s info users
users write create and edit the users users
vehicles read read the vehicle list and it’s information vehicles
vehicles write create and edit a vehicle vehicles
vehicles.counters read read the vehicle’s counters vehicle-counters
vehicles.counters write edit the global vehicle counters vehicle-counters

Units

Unless otherwise specified, the API handles all units for keys in the following manner by default.

Metric Unit
Distance meter
Volume liter
Time second
Temperature Celsius

Speed and acceleration units vary per resource, but will normally take the form of

The API’s of Rawdata, Counters and Trips support unit paramaters, which can modify the output to the desired units.

Allowed values

The Gateway allows you to specify multiple values for each unit of measurement.

Metric Allowed values
Distance meter, km, mile
Volume liter, gallon
Time second, minute, hour
Temperature C, F

You may also pass user for either the distance or volume parameters, where applicable. The API will return the values in accordance with the users preference.

Speed

Where applicable, the speed is determined by the distance and time units (default: meter/second)

The Counters and Trips API’s allows you to override this unit, by specifying one of kph , mph or user, where user falls back to either kph or mph based on the users distance preference (mile or km)

Acceleration

The acceleration field is always the speed units, per second

Timezone

List of available time zones
api/tz

curl https://pegasus1.pegasusgateway.com/api/tz? \
    --header 'Authenticate: 99ff984fbe2c90603da515cdb193fda3146c9c4c9a347bcf062b0760'

{"server_utc_epoch":1538478876.558243,"allowed":["Africa/Abidjan","Africa/Accra","Africa/Addis_Ababa","Africa/Algiers","Africa/Asmara","Africa/Bamako","Africa/Bangui","Africa/Banjul",...]}

The API by default returns all timestamps in UTC (GMT+0)

You can change the timestamp by passing a URL param tz or an HTTP header value with: "X-Time-Zone" : "time_zone_value"

&tz=America/New_York

"X-Time-Zone" : "America/New_York"

URL param

api/rawdata?vehicles=2600&fields=$basic&duration=P1D&tz=America/New_York

{
  "units": {
    "volume": "liter",
    "distance": "meter",
    "speed": "mph",
    "time": "second"
  },
  "events": [
    {
      "head": 291,
      "code": 0,
      "hdop": 0.82,
      "event_time": "2018-10-02T09:20:47",
      "type": 10,
      "vid": 2600,
      "lon": -72.50346,
      "sv": 9,
      "mph": 0,
      "label": "prdtst",
      "valid_position": true,
      "lat": 7.94937,
      "system_time": "2018-10-02T09:20:50.505475",
      "speed": 0,
      "id": 260012351115505,
      "device_id": 356612022409637
    }
  ]
}

HTTP Header

curl 'https://pegasus1.pegasusgateway.com/api/rawdata?vehicles=2600&fields=$basic&duration=PT1H' \
    --header 'X-Time-Zone: America/New_York' \
    --header 'Authenticate: 99ff984fbe2c90603da515cdb193fda3146c9c4c9a347bcf062b0760'

{"units": {"volume": "liter", "distance": "meter", "speed": "mph", "time": "second"}, "events": [{"head": 291, "code": 0, "hdop": 0.81999999999999995, "event_time": "2018-10-02T09:20:47", "type": 10, "vid": 2600, "lon": -72.503460000000004, "sv": 9, "mph": 0, "label": "prdtst", "valid_position": true, "lat": 7.94937, "system_time": "2018-10-02T09:20:50.505475", "speed": 0, "id": 260012351115505.0, "device_id": 356612022409637}]}

Entities

returns vehicle’s name & device info

api/vehicles?select=name,device:*


return particular vehicle’s name & device’s network info

api/vehicles?select=name,device:network&ids=2600

Entities are collections of vehicles & assets. As far as the API is concerned, these resources are interchangeable with respect to the data they collect and can report, in other words both vehicle’s and assets can have rawdata, trips, etc. Also, vehicle’s and assets can be associated to one another. The API manages a concept of primary_id & secondary_id when associating these entities.

Primary ID refers to the main entity, whether it’s a vehicle or an asset, and the secondary ID refers to the ID of the asset of vehicle that it has associated.

Other resources which include collections of things are: devices, geofences, users, groups, sims.

All of the collections mentioned above support pagination & select parameter.

The select parameter is used to filter the data that you are looking for from the resources. You can also join resources using the select &select=devices:*,users:*

Users

All users

api/users


Particular user

api/users/:id


Usernames & preferences only

api/users?select=username,prefs

Users are identified by email.
Usernames give access to both the Pegasus Platform GUI and to the API.
A User’s API access is controlled by scopes
Their entities visibility is determinated by its groups’ membership

More info

Own User

You can look at your own user with the following resource:
GET https://pegasus1.pegasusgateway.com/api/user

api/user

{
  "username": "developer@digitalcomtech.com",
  "scopes": {
    "sims": "w",
    "vehicles.counters": "w",
    "remote": "w",
    "users": "r",
    "vehicles": "r",
    "devices": "w",
    "geofences": "w",
    "rawdata": "w",
    "groups": "r",
    "plugins.garmin": "w",
    "plugins.photocam": "w",
    "plugins.lumeway": "w",
    "assets": "r"
  },
  "first_name": "DCT",
  "last_name": null,
  "is_superuser": false,
  "is_active": true,
  "__updated": 1505078528.8436389,
  "id": 632,
  "phone": null,
  "is_staff": false,
  "last_login": 1505078528.8169999,
  "groups": [
    500,
    807
  ],
  "prefs": {
    "fuelunits": "gallon",
    "distance": "mile",
    "temperature": "F",
    "language": "es",
    "distanceunits": "mile",
    "volume": "gallon",
    "coords": "WGS84",
    "hour_format": 12
  },
  "email": "developer@digitalcomtech.com",
  "date_joined": 1396137176.0
}

this is helpful in determining what permissions/scopes you have access to as well as the groups of vehicles you are assigned.

Groups

All groups

api/groups


Particular group

api/groups/:id

Groups are identified by a unique ID and a user-defined name.
Groups relate Users and Vehicles.
The most common usage is “a group per client”, but it’s flexible to serve other purposes:

More info

Vehicles

All vehicles

api/vehicles


Particular vehicle

api/vehicles/:id


All vehicle’s info & last device communication

api/vehicles?select=info,device:last*

Vehicles are the core resource for 90% of the requests. When you request tracking and counters data, for example, it is organized per vehicle. Remote interaction with a Syrus is done to its associated vehicle. 90% Of Automation triggers are triggered by vehicle events

More info

Devices

All devices

api/devices


Particular device

api/devices/:imei


All device’s inputs & outputs state

api/devices?select=ios_state

Device’s latest data reported

api/devices/:imei?select=latest

Devices refer to any of the device’s in the DCT ecosystem, a vehicle can only have one device assigned at any one time. This vehicle-device association may change over time (unit replacement) but it will always be a one to one relationship. You may see an association history of the vehicle’s / IMEIs when you make an api/vehicles/:id request

The device’s api is very powerful and full of information related to the current status of the device, it always represents the last information that the device reported.

More info

SIMs

api/sims

api/sims/:id

The SIMs resources is one that’s automatically updated by the listener of the gateway, the moment the device reports a SIM it will be updated, and any change, for example a new SIM card is introduced to the device it will be automatically updated accordingly.

Assets

Rawdata request that groups by asset id aid, shows the max speed daily per driver

api/rawdata?groups=500&duration=P3D&fields=$basic,aid&resample=event_time&how=mph:max,vid:first&freq=1D&group_by=aid

{
  "events": [
    {
      "aid": 672,
      "mph": 47,
      "vid": 598,
      "event_time": "2016-10-04T12:00:00"
    },
    {
      "aid": 791,
      "mph": 54,
      "vid": 759,
      "event_time": "2016-10-04T12:00:00"
    },
    {
      "aid": 791,
      "mph": 47,
      "vid": 759,
      "event_time": "2016-10-05T00:00:00"
    }
  ]
}

Assign a vehicle to an asset manually

curl -X POST https://pegasus1.pegasusgateway.com/api/entities/link \
  --header 'Content-Type: application/json' \
  --header 'Authenticate: 99ff984fbe2c90603da515cdb193fda3146c9c4c9a347bcf062b0760' \
  -d '{"primary_id": 2600, "secondary_id": 691}'

Assets are entities that can provide a relationship between a device and an accessory, this makes them very valuable when you want to assign a driver to a vehicle.

The accessories that are compatible with assets are iButton, Fingerprint readers, Bluetooth tags, and Taurus. An example use case is that the asset is assigned a unique iButton id. Whenever that unique iButton ID is read by any device, that device will instantly be associated to that asset.

The typical application for an asset is for assigning a driver to a vehicle.

There are two ways to associate an asset & a vehicle together, the first is manually with the api/entities/link

The second method is with the device automatically reporting an iButton ID, Fingerprint ID, Bluetooth Tag MAC address or Taurus token and associating it to an existing asset. To do this:

First, you create an asset.

Second, you associate the unique iButton ID, Bluetooth Tag MAC, Fingerprint ID, or enable the Taurus Token

Third, you present the particular iButton ID, or MAC address near the device

And that’s it, afterwards the vehicle’s device will be assigned that asset until another iButton or something else takes it place.

This opens up the possibilities of making requests with asset informations. The following fields would be available:

aid or asset ID

Thus when you want to create a rawdata request, and you’d like to resample and group_by a field, you can now group_by the asset ID, thereby allowing you to have rawdata requests per asset or driver.

Associations

Accessories

Syrus has a lot of accessories that can interface and work simultaneously with one another, below you will find the accessories integration with the API. If you are looking for installation guides and more general information about the accessories please visit our support site.

iButton

See a list of all iButtons and their associations api/ibuttons

{
    "id": "0A000017B5E64F01",
    "entity": 1037
}

The iButton is an accessory that can be used to identify physical entities or assets such as drivers. iButtons have a unique 16 character ID that can be associated to an asset.

Associating an iButton

To associate an iButton to an entity or asset simply make a POST with the ID of the iButton (16 alpha-numerical characters) and the asset ID, to the fields id and entity respectively.

You can see the iButton ID associated to any asset by going into that particular asset’s ID: GET api/assets/:id

Associating an iButton ID to an asset POST api/ibuttons

Payload of request, this will associate ibutton ID: 1234567890123456 to asset id: 1032

{
    "id":"1234567890123456",
    "entity": 1032
}

See a particular asset’s information (including iButtons associated)
api/assets/1032

{
  "info": {
    "first_name": "Test",
    "last_name": "User",
    "type": "driver",
    "email": "user@email.com"
  },
  "name": "Test User",
  "ibuttons": [
    "1234567890123456"
  ],
  "groups": [
    1,
    479,
    566
  ],
  "device": 356612021234567,
  "type": "driver",
  "id": 1032,
  "counters": null
}

Setting Up the iButton

In order to setup the iButton effectively on the API and associate the assets correctly you need to update the device configuration to use the ;IS extended tag. To confirm that this is done for the managed configuration that your device is using check the device’s configuration commands. Look for commands that start with >RXAEF and it has to contain ;IS, this will tell us that the iButton is kept associated to the device until a new one is introduced.

Retrieving an Asset’s events

Once the user places that iButton on the device, it will update a field called: aid (asset ID) in the rawdata API and the trips API This field is kept associated to the device it was introduced until a new iButton is placed. Allowing you to associate the events by an asset ID.

This rawdata request will group the resampled events by aid (asset id)
api/rawdata?vehicles=617,654&fields=$basic,$counters,aid&duration=P1D&filter=(valid_position and mph > 5 and comdelay < 3600 and hdop < 3)&how=$counters:diff,mph:mean&freq=1D&group_by=aid&resample=event_time

The result is the daily values of the counters, and the average speed grouped by the asset ID

For more info please visit our iButton Documentation on our Support Site

Bluetooth Tags

Associating to asset

PUT api/:bt_tags_mac

PUT api/bt_tags/00:07:80:EA:B9:8C

{
  "asset_id": 123
}

In order to associate a Bluetooth tag to an asset you must make a PUT request to the Tag’s MAC address /api/:bttag_mac with the asset_id you want associated

Getting Bluetooth Tag Data

GET Bluetooth tag data

GET api/rawdata?vehicles=2050&fields=$bttag&duration=P1D&filter=btt_battery>0

{
  "units": {
    "volume": "liter",
    "distance": "meter",
    "speed": "mph",
    "time": "second"
  },
  "events": [
    {
      "btt_impact": null,
      "system_time": "2017-06-23T16:12:19.462809",
      "btt_battery": 100.0,
      "vid": 2050,
      "event_time": "2017-06-23T16:12:19.462809",
      "btt_reed": false,
      "btt_motion": false,
      "btt_button": false,
      "btt_light": 0.0,
      "id": 5023175567.0,
      "btt_freefall": null,
      "btt_temp": 212.0,
      "btt_mac": "00:07:80:EA:B8:C0",
      "btt_humidity": 61.0
    }
  ]
}

You can use the set called: $bttag on the rawdata API to request all the fields for the bluetooth tag.

Field Type Description Range
btt_battery Number Battery % 0, 100
btt_button Boolean True if button is detected
btt_driver Number Asset ID associated event
btt_freefall Boolean True if freefall detected
btt_humidity Number Humidity % 0, 100
btt_impact Boolean True if impact detected
btt_light Number Light % 0, 100
btt_mac String Tag’s unique MAC address
btt_motion Boolean True if motion is detected
btt_presence Boolean True if tag presence is detected
btt_reed Boolean True if reed switch is detected
btt_temp Number °C * 10 (divide by 10 to get the temperature in °C) -100, 450 (-10°C to 45°C)
btt_wreason String Reason for waking up

Bluetooth tag wake up reasons

btt_wreason Description
R Reed switch.
C Time.
B Button.
M Motion.
L Light.
W Low batt.
X Beacon mode.
i First Time.
u Unknown.

Input / Output Expander

Rawdata request with $io_exp set
api/rawdata?vehicles=56&fields=$io_exp&duration=P1D&filter=io_exp_state%3E0

{
  "io_exp_in1": false,
  "io_exp_in2": true,
  "io_exp_in3": true,
  "io_exp_in4": true,
  "vid": 56,
  "event_time": "2016-10-17T17:21:09",
  "io_exp_out1": true,
  "io_exp_out2": false,
  "io_exp_out2_short": null,
  "io_exp_out4": false,
  "system_time": "2016-10-17T17:21:51.625232",
  "io_exp_state": true,
  "io_exp_out3_short": null,
  "io_exp_out1_short": null,
  "io_exp_out4_short": null,
  "id": 4384626550,
  "io_exp_out3": false
}

The input/output expander allows your device to control an additional 4 more inputs and 4 more outputs.

You will have an additional 13 fields available in the rawdata api, you may use the $io_exp set to easily access the fields

Interacting with Outputs

Activating extended output 3
POST api/vehicles/:vid/remote/output

{
  "otype": "e",
  "out": 3,
  "state": true
}

Response

{
  "msg": "instruction set to device. ",
  "device_is_online": false,
  "oids": [
    449500
  ]
}

View the status of the extended inputs/outputs

api/devices/:imei?select=ios_state

{
  "imei": 357042062920955,
  "ios_state": {
    "io_pwr": true,
    "io_exp_in1": false,
    "io_exp_in2": false,
    "io_exp_in3": false,
    "io_exp_in4": false,
    "_epoch": 1538175893.721557,
    "io_ign": true,
    "io_out2_short": false,
    "io_exp_out1": false,
    "io_exp_out2": false,
    "io_exp_out3": false,
    "io_exp_out4": false,
    "io_exp_state": true,
    "io_out1_short": false,
    "io_exp_out2_short": false,
    "io_in2": false,
    "io_out1": false,
    "io_out2": true,
    "io_exp_out1_short": false,
    "io_exp_out4_short": false,
    "io_in1": true,
    "io_exp_out3_short": false,
    "io_in3": false
  }
}

View a log of the output changes

api/devices/357042062920955/remote/outputsetlog

[
  {
    "state": true,
    "otype": "e",
    "out": 3,
    "user": "developer@digitalcomtech.com",
    "time": 1452542329.846
  }
]

In order to activate/deactivate the outputs of the IO Expander, you can use the output remote method, with the otype as e
POST /api/vehicles/:vid/remote/output

Payload for activating the output 3 of the expander

{
  "otype": "e",
  "out": 3,
  "state": true
}

You can view the changes done to the device’s outputs with the

GET api/vehicles/617/remote/outputsetlog

More info

Photocam

Photocam is a camera that can be connected to the Syrus and it can take photos by request or with a programmable trigger.

The photocam can be accessed under the plugins namespace, the interaction happens per device or vehicle, so we need to specify either a vehicle ID api/vehicles/:vid or an api/devices/:imei

All photocam methods

/api/vehicles/:vid/plugins/photocam

/api/devices/:imei/plugins/photocam

Capturing a photo

Capture a photo from the camera connected to vehicle id: 1956

api/vehicles/1956/plugins/photocam/capture

{
    "msg": "instruction sent to device. ",
    "device_is_online": true
}

To take a photo simply send: GET /api/vehicles/:vid/plugins/photocam/capture

or

GET /api/devices/:imei/plugins/photocam/capture

When the photo is taken it will take some time to upload it, at this point you can poll the api’s last method while the photo uploads, or subscribe to the vehicle’s events via live communication to get the status updates

 


 


 


 


Getting the last photo

Requesting the last photo taken from a vehicle with 1 camera connected
https://pegasus1.pegasusgateway.com/api/vehicles/397/plugins/photocam/last

{
    "status": "Photo taken, device is uploading it.",
    "source": 0,
    "status_no": 3
}

after some seconds you will see the following response
https://pegasus1.pegasusgateway.com/api/vehicles/397/plugins/photocam/last

{
  "photos": [
    {
      "status": "jpeg photo found",
      "debug": "2016-10-17 15:40:09-05:00",
      "source": 0,
      "epoch": 1476736809,
      "imei": 356612024116677,
      "b64data": "/9j/2wCEABQODxIPDR__BASE_64__DvqS9BAKgPU1YhKKYBRQAUUAFJQB//Z",
      "status_no": 4,
      "size": 8586
    }
  ],
  "event": {
    "dphoto_ptr": 46742,
    "system_time": "2016-10-17T15:40:21",
    "event_time": "2016-10-17T15:40:09",
    "lon": -80.29358,
    "lat": 25.78397,
    "id": 5014711973,
    "device_id": 356612024116677
  }
}

Requesting the last photo taken from a vehicle with 3 cameras connected
https://pegasus1.pegasusgateway.com/api/vehicles/469/plugins/photocam/last

{
  "photos": [
    {
      "status": "jpeg photo found",
      "debug": "2016-09-07 14:04:12-05:00",
      "source": 1,
      "epoch": 1473275052,
      "imei": 356612024116677,
      "b64data": "/9j/2wCEABQODxIPDRQS__BASE_64_DATA__EBIXFRQYHjIhHhwcHj0sLiQySUBM"
    },
    {...},
    {...}
  ],
  "event": {
    "dphoto_ptr": 44379,
    "system_time": "2016-09-07T14:04:15",
    "event_time": "2016-09-07T14:04:12",
    "lon": -80.29348,
    "lat": 25.78357,
    "id": 5013175609,
    "device_id": 356612024116677
  }
}

In order to obtain the last photo you can perform a GET /api/vehicles/:vid/plugins/photocam/last

The photo itself mime type: jpeg and is base64 encoded, to convert this into an image you can the HTML img tag and modify the source of the image with the following format:

<img src='data:image/jpeg;base64,__INSERT__BASE__64__' />

you can also use a website such as: http://freeonlinetools24.com/base64-image

decoded image

 


 


 


 


 


 


 


 


Browsing photos

Browse photos
https://pegasus1.pegasusgateway.com/api/vehicles/469/plugins/photocam/browse?_from=2016-05-11&_to=2016-05-12

[
  {
    "dphoto_ptr": 40656,
    "system_time": "2016-05-11T21:16:43",
    "code": 48,
    "event_time": "2016-05-11T21:16:40",
    "vid": 469,
    "lon": -80.29351,
    "label": null,
    "lat": 25.78392,
    "id": 5008241019
  }
]

You can use the browse method to see a list of events that have a photo associated to them.

GET /api/vehicles/:vid/plugins/photocam/browse

This method requires two parameters _from and _to which is the dates from and to search for photos.

GET /api/vehicles/:vid/plugins/photocam/browse?_from=YYYY-MM-DD[Thh:mm:ss]&_to=YYYY-MM-DD[Thh:mm:ss]

The time [Thh:mm:ss] is optional

The result gives us an object with different id that correspond to an event with photos

[
  {
    "dphoto_ptr": 40602,
    "system_time": "2016-05-10T20:41:00",
    "code": 48,
    "event_time": "2016-05-10T20:40:57",
    "vid": 469,
    "lon": -80.29355,
    "label": null,
    "lat": 25.78403,
    "id": 5008197387
  }
]

With this ID we can use the from_event method to obtain the photo from this event.

Getting an event’s photo(s)

Requesting the photos associated to the event id: 5008241019

api/vehicles/469/plugins/photocam/from_event?event=5008241019&time=2016-05-11

{
  "photos": [
    {
      "status": "jpeg photo found",
      "photo_id": 10000321,
      "debug": "2016-05-11 16:16:40-05:00",
      "source": 1,
      "epoch": 1463001400,
      "imei": 356612024116677,
      "b64data": "/9j/2wCEABQODxIPDRQSE__BASE_64_Data__HhwcHj0sLiQySUBMS0dARkV"
    },
    {...},
    {...}
  ],
  "event": {
    "dphoto_ptr": 40656,
    "system_time": "2016-05-11T16:16:43",
    "event_time": "2016-05-11T16:16:40",
    "lon": -80.29351,
    "photo_status": null,
    "photo_status_time": null,
    "lat": 25.78392,
    "pi": null,
    "id": 5008241019,
    "device_id": 356612024116677
  }
}

Requesting a photo from a camera that has an error
/api/vehicles/617/plugins/photocam/from_event?event=5013893009&time=2016-09-26

{
  "photos": [
    {
      "status": "Photo could not be taken. Device can not communicate with the camera.",
      "source": 0,
      "status_no": 5
    }
  ],
  "event": {
    "dphoto_ptr": 45535,
    "system_time": "2016-09-26T10:56:09",
    "event_time": "2016-09-26T10:56:01",
    "lon": -80.29352,
    "photo_status": null,
    "photo_status_time": null,
    "lat": 25.78409,
    "pi": null,
    "id": 5013893009,
    "device_id": 356612023728084
  }
}

In order to get a particular photo we can use the method GET /api/vehicles/:vid/plugins/photocam/from_event

this method requires two parameters event and time where event is the id from the event that has a photo associated to it, and time is the timestamp that the event was received on the server (system_time)

GET /api/vehicles/:vid/plugins/photocam/from_event?event=####&time=YYYY-MM-DDThh:mm:ss

If there’s a problem taking the photo, you will get a status_no which is a status number that corresponds to one of the following errors.

Photo Camera Status Numbers

status description
0 Received photo request
1 Waiting for the camera’s capture acknowledge
2 Device is receiving photo from the camera
3 Photo is being uploaded
4 Photo ready, loading…
5 Serial camera is not responding
6 Capture command could not be sent to the camera
7 Camera did not recognize the capture command, try again
8 The information of the captured photo could not be read
9 Comms. error between camera and device
10 Device could not create photo file
11 Device could not send photo to server
12 Device could not connect to server, will retry
13 Another photo is being captured, photo in queue
14 Device memory full, could not capture
15 Error capturing photo, photo removed from queue
16 Device could not capture, ID max index reached
99 Camera inactive or initializing

For more info please visit our Support Site

Lumeway

The lumeway accessory works essentially the same as the Photocam accessory, the API requests are very similar, with a few exceptions to some commands you can send to configure the Lumeway.

The lumeway can be accessed under the plugins namespace, this interaction happens per vehicle, so we need to specify a vehicle ID first :vid

sending this request will give us all the possibilities with the lumeway accessory.

/api/vehicles/:vid/plugins/lumeway

Capturing a photo

Capturing a photo for a Lumeway accessory

api/vehicles/1/plugins/photocam/capture

{
  "msg": "Capture commands set",
  "device_is_online": true,
  "oids": [
    436085
  ]
}

When the photo is taken it will take some time to upload it, at this point you can poll the api’s last method while the photo uploads.

Getting the last photo

In order to obtain the last photo you can perform a GET /api/vehicles/:vid/plugins/photocam/last

The photo itself is mime type jpeg and base64 encoded, to convert this into an image you can the HTML img tag and modify the source of the image with the following format:

<img src='data:image/jpeg;base64,__INSERT__BASE__64__' />

Getting the last photo
https://pegasus1.pegasusgateway.com/api/vehicles/1/plugins/photocam/last

Notice how the source is 99, this is always the case when the photos are generated from the Lumeway accessory

{
  "photos": [
    {
      "status": "Photo taken, device is uploading it.",
      "source": 99,
      "status_no": 3
    }
  ],
  "event": {
    "dphoto_ptr": 8308,
    "system_time": "2016-10-12T18:11:10",
    "event_time": "2016-10-12T18:11:08",
    "lon": -69.09872,
    "lat": -24.25018,
    "id": 4357500360,
    "device_id": 356612024713036
  }
}

after some seconds you will see the following response

https://pegasus1.pegasusgateway.com/api/vehicles/397/plugins/photocam/last


{
  "photos": [
    {
      "status": "jpeg photo found",
      "debug": "2016-10-12 17:47:11-05:00",
      "source": 99,
      "epoch": 1476312431,
      "imei": 356612024713036,
      "b64data": "/9j/4AAQSkZJRgABAQAA....5H5gVt3I=",
      "status_no": 4,
      "size": 3269
    }
  ],
  "event": {
    "dphoto_ptr": 8306,
    "system_time": "2016-10-12T17:47:13",
    "event_time": "2016-10-12T17:47:11",
    "lon": -69.12449,
    "lat": -24.25723,
    "id": 4357497035,
    "device_id": 356612024713036
  }
}

Browsing photos

Browse photos from any date to any date
https://pegasus1.pegasusgateway.com/api/vehicles/1/plugins/photocam/browse?_from=2016-10-01&_to=2016-10-01T10:39:40

You can use the browse method to see a list of events that have a photo associated to them.

GET /api/vehicles/:vid/plugins/photocam/browse

This method requires two parameters _from and _to which is the dates from and to search for photos.

GET /api/vehicles/:vid/plugins/photocam/browse?_from=YYYY-MM-DD[Thh:mm:ss]&_to=YYYY-MM-DD[Thh:mm:ss]

The time [Thh:mm:ss] is optional

The result gives us an object with different id that correspond to an event with photos

[
  {
    "dphoto_ptr": 8033,
    "system_time": "2016-10-01T10:39:40",
    "code": 84,
    "event_time": "2016-10-01T10:39:39",
    "vid": 790,
    "lon": -69.12207,
    "label": "lumenodrv",
    "lat": -24.25782,
    "id": 4356063141
  }
]

With the ID of the photos we just browsed, we can use the from_event method to carry obtain that photo

https://pegasus1.pegasusgateway.com/api/vehicles/790/plugins/photocam/browse?_from=2016-10-01&_to=2016-10-01T10:39:40

[
  {
    "dphoto_ptr": 8033,
    "system_time": "2016-10-01T10:39:40",
    "code": 84,
    "event_time": "2016-10-01T10:39:39",
    "vid": 790,
    "lon": -69.12207,
    "label": "lumenodrv",
    "lat": -24.25782,
    "id": 4356063141
  }
]

using the id 4356063141 - we can get that particular photo with the from_event method

Getting an event’s photo(s)

In order to get a particular photo we can use the method GET /api/vehicles/:vid/plugins/photocam/from_event

this method requires two parameters event and time where event is the id from the event that has a photo associated to it, and time is the time that the event was generated

GET /api/vehicles/:vid/plugins/photocam/from_event?event=####&time=YYYY-MM-DDThh:mm:ss

If there’s a problem taking the photo, you will get a status_no which is a status number that corresponds to one of the following errors.

Lumeway Status Status Numbers

Status Code Description
00 Lumeway ready.
03 Sending photo to the FTP server.
04 Photo was successfully sent to the FTP server.
05 Lumeway is not responding.
06 Capture command could not be sent to the camera.
08 The information of the captured photo could not be read.
09 Wrong checksum.
10 Could not create photo file on the Syrus
11 Could not send photo to the FTP server, because the Syrus’s FTP service is busy.
12 Could not connect to the FTP server.
13 Another photo is being captured. Photo in queue.
14 Error capturing photo. Queue full or camera disconnected.
15 Error capturing photo. Photo removed from queue.
16 Error max photo id reached. “999999999”.
17 Error limit of requests reached
99 Inactive mode or initializing.

Requesting the photos associated to the event id: 4356063141
api/vehicles/790/plugins/photocam/from_event?event=4356063141&time=2016-10-01

{
  "photos": [
    {
      "status": "jpeg photo found",
      "photo_id": 990003450,
      "debug": "2016-10-01 05:39:39-05:00",
      "source": 99,
      "epoch": 1475318379,
      "imei": 356612024713036,
      "b64data": "/9j/4AAQSkZJRg...+18kcnsehrWguYorYEkfSv/Z",
      "status_no": 4,
      "size": 3261
    }
  ],
  "event": {
    "dphoto_ptr": 8033,
    "system_time": "2016-10-01T05:39:40",
    "event_time": "2016-10-01T05:39:39",
    "lon": -69.12207,
    "photo_status": null,
    "photo_status_time": null,
    "lat": -24.25782,
    "pi": null,
    "id": 4356063141,
    "device_id": 356612024713036
  }
}

For more info please visit our Support Site

Serial Expander

Take a photo with a device that has 3 cameras connected to it

api/vehicles/469/plugins/photocam/capture

{
  "msg": "instruction set to device. ",
  "device_is_online": true,
  "oids": [
    334966
  ]
}

Get the last photos for vehicle id: 469

api/vehicles/469/plugins/photocam/last

{
  "photos": [
    {
      "status": "Device is taking/uploading the photo.",
      "source": 1,
      "status_no": 0
    },
    {
      "status": "Device is taking/uploading the photo.",
      "source": 2,
      "status_no": 0
    },
    {
      "status": "Device is taking/uploading the photo.",
      "source": 3,
      "status_no": 0
    }
  ]
}

After some seconds

api/vehicles/469/plugins/photocam/last

{
  "photos": [
    {
      "status": "jpeg photo found",
      "photo_id": 10000122,
      "debug": "2016-11-13 15:04:23-05:00",
      "source": 1,
      "epoch": 1447445063,
      "imei": 356612024116677,
      "b64data": "/9j/2wCQOxI__BASE64_DATA__bOTGSTSa6q9z/2Q==",
      "status_no": 4,
      "size": 9232
    },
    {
      "status": "jpeg photo found",
      "photo_id": 20000122,
      "debug": "2016-11-13 15:04:23-05:00",
      "source": 2,
      "epoch": 1447445063,
      "imei": 356612024116677,
      "b64data": "/9j/2wCEODxy+vHO__BASE64__DATA__KFFMQ0gP//Z",
      "status_no": 4,
      "size": 5532
    },
    {
      "status": "jpeg photo found",
      "photo_id": 30000122,
      "debug": "2016-11-13 15:04:23-05:00",
      "source": 3,
      "epoch": 1447445063,
      "imei": 356612024116677,
      "b64data": "/9j/2wCEApoZWM__BASE64_DATA__eKkCsfselAH//Z",
      "status_no": 4,
      "size": 6894
    }
  ],
  "event": {
    "dphoto_ptr": 30798,
    "system_time": "2016-11-13T15:04:27",
    "event_time": "2016-11-13T15:04:23",
    "lon": -80.29337,
    "photo_status": null,
    "photo_status_time": null,
    "lat": 25.78379,
    "pi": null,
    "id": 5003163587,
    "device_id": 356612024116677
  }
}

The serial expander can be used to connect multiple serial communication (RS-232) accessories simultaneously. This allows you to take up to 3 photos simultaneously with the camera.

Depending on the Syrus configuration you use you can have the option to associate an event to take a photo with 1, 2 or 3 of the cameras connected.

For more info please visit our Support Site

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

ECU Monitor

The ECU monitor can be used to connect the Syrus directly to the vehicle’s onboard computer to obtain CAN data. The possible protocols that the ECU Monitor can detect are:

For more information about protocols and vehicles which are compatible visit our support site

The connection to the onboard computer automatically gives you access to precise vehicle metrics. The master fields list gives you an idea of all the possible values obtained with the ECU monitor.

Counters API request with ecu parameters api/counters?vehicles=1716&duration=P1D&round=2&time=hour&speed=mph&distance=mile&volume=gallon

{
  "units": {
    "volume": "gallon",
    "distance": "mile",
    "speed": "mph",
    "time": "hour"
  },
  "counters": [
    {
      "ecu_dist": 232.7,
      "vid": 1716,
      "ecu_ifuel": 0.5,
      "dev_tot_avg_speed": 34.12,
      "tra_avg_speed": 36.36,
      "from": "2016-10-17T13:30:51",
      "dev_idle": 0.41,
      "ecu_eidle": 1.35,
      "ecu_fuelp_idling": 1.39,
      "to": "2016-10-18T13:30:13",
      "ecu_eusage": 7.75,
      "ecu_tot_avg_speed": 30.03,
      "ecu_tfuel": 36.22,
      "ecu_tra_avg_speed": 36.36,
      "dev_orpm": 0,
      "dev_tra_fuel_efcy": 7.43,
      "ecu_tot_fuel_efcy": 6.42,
      "tot_avg_speed": 30.03,
      "ecu_tra_fuel_efcy": 6.52,
      "dev_dist": 265.44,
      "distance": 232.7,
      "dev_ign": 7.78,
      "dev_tra_avg_speed": 36.01,
      "dev_tot_fuel_efcy": 7.33,
      "idle": 1.35,
      "ignition": 7.75,
      "dev_ospeed": 0.56
    }
  ]
}

When using the counters API, you will notice that the following fields will be available, they give us precise engine data

Counter Description Calculation
dev_tot_fuel_efcy Syrus calculated Fuel efficiency dev_dist/ecu_tfuel
dev_tra_fuel_efcy Syrus calculated Traveling fuel efficiency dev_dist/(ecu_tfuel-ecu_ifuel)
ecu_dist Distance reported by ECU monitor
ecu_eidle Idle time reported by ECU monitor
ecu_eusage Engine usage time reported by ECU Monitor
ecu_fuelp_idling Fuel percentage used while idling ecu_ifuel*100/ecu_tfuel
ecu_ifuel Fuel consumed while idling, reported by ECU monitor
ecu_tfuel Total fuel consumed, reported by ECU monitor
ecu_tot_avg_speed Total average speed, ECU ecu_dist/ecu_eusage
ecu_tot_fuel_efcy ECU calculated Fuel efficiency ecu_dist/ecu_tfuel
ecu_tra_avg_speed Traveling average speed, ECU ecu_dist/(ecu_eusage-ecu_eidle)
ecu_tra_fuel_efcy ECU calculated Traveling fuel efficiency ecu_dist/(ecu_tfuel-ecu_ifuel)

When using the rawdata API you’ll notice that you have access to all the fields in the master fields list that start with ecu_

Rawdata request with the ECU RPMs and the flag

/api/rawdata?vehicles=1716&duration=P1D&fields=ecu_rpm,ecu_rpm_flag

{
  "ecu_rpm_flag": "F",
  "system_time": "2016-10-17T16:58:39.711674",
  "vid": 1716,
  "event_time": "2016-10-17T16:58:37",
  "ecu_rpm": 0,
  "id": 5014706111
}

Filtered by rpm_flag = “T” (show’s valid values)

api/rawdata?vehicles=1716&duration=P1D&fields=ecu_rpm,ecu_rpm_flag&filter=(ecu_rpm_flag==%22T%22)

{
  "ecu_rpm_flag": "T",
  "system_time": "2016-10-17T13:39:34.614058",
  "vid": 1716,
  "event_time": "2016-10-17T13:39:31",
  "ecu_rpm": 692,
  "id": 5014700250
}

The following sets will also be available from the rawdata API

remember you can see which fields are in these sets with an empty rawdata request GET /api/rawdata

All the ECU Monitor parameters have the following flags associated
ecu_**_flag (where ** corresponds to any of the ECU parameters below)

Flag Status Description
B ECU Monitor accessory upgrading Firmware
D ECU Monitor accessory not detected
F ECU Monitor accessory detected and vehicle’s engine turned off
O ECU Monitor accessory has not received new data from this parameter in the last 2 minutes
T ECU Monitor accessory detected and vehicle’s engine turned on. ECU VALID DATA
U Parameter not available. (ECU Detected, Parameter Data is not Available)

As seen above, only when the flag is “T” will the ECU parameters be valid and should be used for calculations, thus when making the rawdata request you could add this as a filter

&filter=(ecu_rpm_flag==%22T%22)

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Tips

Get the ECU Monitor information for a vehicle

GET api/vehicles/:vid/remote/ecu_state

{
  "protocol_name": "J1708",
  "protocol": null,
  "upgrading": false,
  "ecu_fw": 40,
  "_epoch": 1508232214.0765109,
  "detected": true,
  "ecu_parameters_1": 0,
  "ecu_parameters_0": 468383157349548003,
  "params_numbers": [],
  "ecu_fw_full": "4.3.0",
  "params": [
    [
      "Vehicle's speed",
      "Vehicle's speed in km/h."
    ],
    [
      "Engine's oil pressure",
      "Engine's oil level pressure in psi."
    ],
    [
      "Total traveled distance",
      "Total traveled distance reported by the vehicle in meters."
    ],
    [
      "Total fuel consumption",
      "Total fuel consumption reported by the vehicle in liters. This value must divided by 10 to obtain the actual value."
    ],
    [
      "Vehicle's throttle position",
      "Vehicle's throttle position value as a percentage. 100% means that the throttle is fully depressed."
    ],
    [
      "Engine RPM",
      "Engine RPM value."
    ],
    [
      "Instant Fuel Consumption",
      "Vehicle's instant fuel consumption in liters/hour. This value must be divided by 100 to obtain the actual value."
    ],
    [
      "Diagnostic message",
      "ECU Monitor diagnostic messages"
    ],
    [
      "Cruise control and/or PTO state availability",
      "0 indicates that neither parameter is available. 1 indicates that either or both parameters are available."
    ],
    [
      "Parking break status.",
      "Parking break status."
    ],
    [
      "Vehicle's battery",
      "Vehicle's battery level value in millivolts."
    ],
    [
      "Fuel Percentage (read by vehicle's computer)",
      "Fuel level read by vehicle's computer. Tank's Percentage"
    ],
    [
      "Engine's coolant temperature",
      "Engine's coolant temperature in ºC"
    ],
    [
      "Engine usage",
      "Total engine usage time reported by the vehicle in hours. This value must divided by 100 to obtain the actual value."
    ],
    [
      "Total time while engine in idle",
      "Total time while engine is in idle reported by the vehicle in hours. This value must divided by 100 to obtain the actual value."
    ],
    [
      "Tires temperature",
      "Indicates if the protocol used by the vehicle supports the Tires' temperature parameter"
    ],
    [
      "ECUMon communication quality indicator",
      "ECUMon communication quality indicator"
    ],
    [
      "Ambient air temperature",
      "Ambient air temperature"
    ],
    [
      "Engine's oil temperature",
      "Engine's oil temperature"
    ]
  ],
  "ecu_updateepoch": 1508232214.076124,
  "engineison": false
}

You can get a list of the parameters that the ECU supports with the following api GET /api/vehicles/:vid/remote/ecu_state

check the response on the right hand side (JSON)

Mobileye™

Daily event count for Mobileye™ Speeding, Left Turn Signal, Right Turn Signal and Headway Warning

api/rawdata?vehicles=1477&from=2016-10-15&to=2016-10-18T23:59:59&fields=$basic,count:1&labels=mblyspd,mblylftsig,mblyrghsig,mblyhdwrn,mblypddng&resample=event_time&freq=1D&how=count:sum&group_by=label

{
  "units": {
    "volume": "liter",
    "distance": "meter",
    "speed": "mph",
    "time": "second"
  },
  "events": [
    {
      "count": 5,
      "event_time": "2016-10-16T00:00:00",
      "label": "mblyhdwrn"
    },
    {
      "count": 11,
      "event_time": "2016-10-16T00:00:00",
      "label": "mblylftsig"
    },
    {
      "count": 4,
      "event_time": "2016-10-16T00:00:00",
      "label": "mblypddng"
    },
    {
      "count": 11,
      "event_time": "2016-10-16T00:00:00",
      "label": "mblyrghsig"
    },
    {
      "count": 146,
      "event_time": "2016-10-16T00:00:00",
      "label": "mblyspd"
    }
  ]
}

The Mobileye™ accessory integrates with the Syrus devices via the ECU Monitor accessory, with this accessory connected you will have access to the following labels in the rawdata API

Label Short Description Details
mblyerr Mobileye™ Error Error detected in Mobileye™ Accessory
mblylldw Left Lane Departure Warning Vehicle departed the left lane
mblyrldw Right Lane Departure Warning Vehicle departed the right lane
mblyfcw Forward Collision Warning Vehicle imminent collision
mblymaint Mobileye™ Maintenance Flag Mobileye™ maintenance required
mblyflsf Mobileye™ Failsafe Indicate one of the following: blurred image, saturated image, low sun, partial blockage or partial transparent
mblypdfcw Mobileye™ Pedestrian Forward Collision Warning Collision warning with pedestrian detected
mblypddng Pedestrian in Danger Zone Vehicle close to pedestrians
mblytmpr Mobileye™ Tamper Mobileye™ tampering detected
mblyspd Mobileye™ Speeding Speed of vehicle above speed limit sign detected on road
mblyhdwrn Mobileye™ Headway Warning Vehicle driving too close to vehicle in front
mblybrkon Brakes on Brakes applied
mblylftsig Left turn signal Left turn signal activated
mblyrghsig Right turn signal Right turn signal activated
mblywprs Wipers on Wipers activated
mblylwbm Low Beams Vehicle lights turned on
mblyhibm High Beams Vehicle high beams turned on
mblytime Time Signal Change in time of day

You can see a more detailed explanation of this in the following document

Garmin™

The Garmin™ accessory has the following methods exposed

you can send a message to a Garmin™ device and have that message appear in the inbox of the Garmin™ screen, you can also send a job or a location you want the Garmin™ to navigate you to.

These methods are also found in GET /api/vehicles/:vid/plugins/garmin

Get the methods available for the Garmin™

api/vehicles/254/plugins/garmin

{
  "job": {
    "POST": [
      "message",
      "flat",
      "flon"
    ]
  },
  "message": {
    "POST": [
      "message",
      "mtype"
    ],
    "GET": [
      "_from"
    ], 
    "DELETE": []
  },
  "state": {
    "POST": [
      "new_mode"
    ],
    "GET": []
  }
}

Get the current state of the Garmin™

api/vehicles/254/plugins/garmin/state

{
  "state": 1,
  "pending": 0
}

Enable the Garmin™ mode

POST /api/vehicles/254/plugins/garmin/state

payload 
{
  "new_mode": true
}

To start interacting with the Garmin™, make sure the state is online in order to check the state of the Garmin™ you can send

GET /api/vehicles/:vid/plugins/garmin/state

Sending Messages

Messages are sent with the garmin/message method under the plugins API

POST /api/vehicles/:vid/plugins/garmin/message

This method accepts two parameters: mtype and message

Parameter Description
mtype inbox means the message goes to the inbox of the garmin, screen means the message shows up on the garmin screen immediately
message text to be displayed on the garmin, up to 40 characters

Send a message to the inbox on the Garmin™ device

POST api/vehicles/254/plugins/garmin/message

payload 
{
  "message":"testing",
  "mtype":"inbox"
}

a successful response means that the instruction / message was sent to the Garmin™ device

{
  "msg": "instruction set to device. ",
  "ts_message_id": 48,
  "device_is_online": true,
  "oids": [
    124272
  ]
}

Getting Messages

Messages are retrieved with the GET method on api/vehicles/:vid/plugins/garmin/message by passing the _from parameter. This will give you all the messages received and sent to the Garmin device from that particular date.

Request Parameters

Parameter Description Required
upto Retrieve up to this many messages (Number) No
skip Skip this many messages (Number) No
_from Retrieve messages from this date (YYYY-MM-DD) Yes

GET messages from a Garmin

GET api/vehicles/254/plugins/garmin/message?_from=2017-08-03

{
  "skip": 0,
  "set": 1,
  "total": 1,
  "data": [
    {
      "update_time": null,
      "deleted": false,
      "msg": "Hello World",
      "isread": false,
      "user": "user@email.com",
      "time": 1502064044116,
      "imei": 450000169939621,
      "type": "TS",
      "id": 1284
    }
  ]
}

Assigning a Job

A job is a geographical destination that can be sent along with a message to the Garmin™. Once this job is created it will appear on the screen of the Garmin™ device where the driver can click on it and give step by step directions to the destination.

An example of this would be if you wanted to send a driver the location of where to pick up a package.

In order to assign a job we need to use the garmin/job method under the plugins API

POST api/vehicles/:vid/plugins/garmin/job

This method accepts three parameters message, flat, flon

Parameter Description
flat Latitude
flon Longitude
message Text to be displayed on the way to the job (Up to 40 characters - ASCII)

POST api/vehicles/254/plugins/garmin/job

payload 
{
  "message": "package #3242 pick up @ 1:30pm",
  "flat" : 25.78393,
  "flon" : -80.29353
}

successful response means that the instruction was sent to the Garmin™

{
  "msg": "instruction set to device. ",
  "job_message_id": 25,
  "device_is_online": true,
  "oids": [
    124279
  ]
}

Temperature Sensor (Analog interface)

The analog interface or temperature sensor has 3 sensors that can detect temperature at different points

Getting Temperature

The temperature comes in 3 fields ea_a ea_b ea_c

These values can be queried with rawdata

the results of these values correspond to a temperature value:

here’s a graph that has the Temperature vs mV relation Graph

You’ll see there’s a 12th degree polynomial function that’s used to calculate the temperature value.

f(x) = -2.0368055E-35*x^11 + 6.2029607E-31*x^10 – 8.2710455E-27*x^9 + 6.3466737E-23*x^8 – 3.0989103E-19*x^7 + 1.0055822E-15*x^6 – 2.2005923E-12*x^5 + 3.2320968E-09*x^4 – 3.1180082E-06*x^3 + 0.0019020671*x^2 – 0.70336715*x + 141.46249

Javascript

function degC(mV) {
    return parseFloat((-2.0368055E-35 * Math.pow(mV,11) + 6.2029607E-31 * Math.pow(mV,10) + -8.2710455E-27 * Math.pow(mV,9) + 6.3466737E-23 * Math.pow(mV,8) + -3.0989103E-19 * Math.pow(mV,7) + 1.0055822E-15 * Math.pow(mV,6) + -2.2005923E-12 * Math.pow(mV,5) + 3.2320968E-09 * Math.pow(mV,4) + -3.1180082E-06 * Math.pow(mV,3) + 0.0019020671 * Math.pow(mV,2) + -0.70336715*mV + 141.46249).toFixed(2))
}

Python

import math

def degC(mV):
    return -2.0368055E-35 * math.pow(mV,11) + 6.2029607E-31 * math.pow(mV,10) + -8.2710455E-27 * math.pow(mV,9) + 6.3466737E-23 * math.pow(mV,8) + -3.0989103E-19 * math.pow(mV,7) + 1.0055822E-15 * math.pow(mV,6) + -2.2005923E-12 * math.pow(mV,5) + 3.2320968E-09 * math.pow(mV,4) + -3.1180082E-06 * math.pow(mV,3) + 0.0019020671 * math.pow(mV,2) + -0.70336715*mV + 141.46249

Temp °C mV Temp °C mV Temp °C mV Temp °C mV Temp °C mV
60 189 40 291 20 548 0 1271 -20 3583
59 192 39 299 19 569 -1 1333 -21 3791
58 195 38 307 18 590 -2 1398 -22 4014
57 199 37 315 17 613 -3 1467 -23 4252
56 203 36 324 16 638 -4 1540
55 207 35 334 15 663 -5 1618
54 211 34 344 14 690 -6 1700
53 215 33 354 13 718 -7 1788
52 219 32 365 12 749 -8 1881
51 224 31 377 11 780 -9 1980
50 229 30 389 10 814 -10 2085
49 234 29 401 9 849 -11 2196
48 239 28 414 8 886 -12 2314
47 245 27 428 7 925 -13 2440
46 250 26 443 6 967 -14 2574
45 256 25 458 5 1010 -15 2716
44 263 24 474 4 1057 -16 2868
43 269 23 491 3 1106 -17 3030
42 276 22 509 2 1158 -18 3202
41 283 21 528 1 1213 -19 3386

For more information about the temperature sensor please visit our support site

Continental TPMS™

Request tire data

api/rawdata?vehicles=1113&fields=ecu_tires_psi,ecu_tires_tmp,ecu_tpms_warnings,ecu_tpms_provision&duration=P1D&head=1

{
  "ecu_tpms_warnings": "0320030,0330030,0340030,0350030,0000030,0160030,0170030,0180030,0190030",
  "system_time": "2018-10-01T16:51:07.881648",
  "vid": 1113,
  "event_time": "2018-10-01T16:51:05",
  "ecu_tpms_provision": "010310,0191825501010,0181835292341,0171834981980,0161834979294,0351831256396,0341831255008,0331835297967,0321835293060,0011834981950,0001835292410",
  "ecu_tires_psi": "019107,018107,017109,016106,035109,034107,033109,032109,001110,000111",
  "id": 111312277332881,
  "ecu_tires_tmp": "01923,01820,01720,01623,03527,03424,03324,03227,00129,00028"
}

The API is capable of reading data from CPC accessory provided by Continental™.

The data that it can read is

field description
ecu_tires_psi Tire pressure
ecu_tires_tmp Tire temperature
ecu_tpms_warnings Tire warnings
ecu_tpms_provision Tire provisioning

All the fields report in a csv format with the corresponding Tire and it’s value.

Tire location

The tire location comes with every field mentioned above, in order to get the Tire location to an axle and tire position you have to take the first

The tire location can be calculated by taking the low order 4 bits, which represent a position number, counting left to right when facing in the direction of normal vehicle travel (forward). The high order 4 bits represent a position number, counting front to back on the vehicle

You can use the following code to calculate the tire_axle & tire_position (assuming that tire_location is converted from string to integer)

tire_axle = (tire_location >> 4) & 0x0F

tire_position: (tire_location) & 0xF

Example: tire location 019, corresponds to tire_axle: 1 & tire_position: 3

Explanation of data

ecu_tires_psi: 019107,018107,017109,016106,035109,034107,033109,032109,001110,000111

tire: 019 has a pressure of 107 psi, etc.

"ecu_tires_psi": "
AAA
BBB
,AAABBB,AAABBB,AAABBB..."
ecu_tires_psi Description
AAA
000 - 255. Tire Location.
BBB
Pressure (psi)

"ecu_tires_tmp": "
AAA
BBB
,AAABBB,AAABBB,AAABBB..."

ecu_tires_tmp: 01923,01820,01720,01623,03527,03424,03324,03227,00129,00028

tire: 019 has a temperature of 23 °C, etc.

ecu_tires_tmp Description
AAA
000 - 255. Tire Location.
BBB
Temperature (°C)

"ecu_tires_warnings": "
AAA
B
C
D
E
,AAABCDE,AAABCDE,AAABCDE..."

ecu_tpms_warnings: 0320030,0330030,0340030,0350030,0000030,0160030,0170030,0180030,0190030

tire 032 has no 0 Alarm warning, 0 TTM not defective, 3 TTM not supported and 0 no battery warnings

ecu_tpms_warnings Description
AAA
000 - 255. Tire Location.
B
Alarm warning
C
TTM defective (1 if TTM is defective)
D
Loose TTM detection
E
Battery warning.
Alarm warning
Description
0
Ok.
1
Under-inflation warning.
2
Under inflation alarm.
3
Tire leak alarm.
4
TTM (Truck tire module) mute.
5
Temperature warning.
8
TTM over temperature warning.
Loose TTM detection
Description
0
No problem
1
TTM loose
2
TTM turned
3
Not supported

"ecu_tpms_provision": "
A
B
CC
DD
,
ZZZ
XXXXXXXXXX
,ZZZXXXXXXXXXX,ZZZXXXXXXXXXX..."

ecu_tpms_provision: 010310,0191825501010,0181835292341,0171834981...

system 0 is a truck, whose state is 0 OK, the number of axles is 03, and the number of TTMs is 10

the tire ID 019 has a TTM Sensor ID of 1825501010 dec, or 6CCEEF52 in HEX.

ecu_tpms_provision Description
A
System ID (0: Truck, 1: Trailer)
B
System state.
CC
Number of axles.
DD
Number of TTMs (Truck tire modules)
ZZZ
000 - 255. Tire Location.
XXXXXXXXXX
Sensor ID (decimal)
System state
Description
0
Ok.
1
System malfunction (could indicate DTC errors or bad configuration of the CCU)
2
System deactivated.

Pushing data to server

TPMS Temperature sent along with event data to external resource

POST http://yourserver.com/webserver/receiver

{
  ...
  "lat": -33.51001,
  "lon": -70.70053,
  "event_time": "2018-09-25T21:19:24+00:00",
  "tpms_tmp": [
    {
      "position": 0,
      "axle": 0,
      "value": 24
    },
    {
      "position": 1,
      "axle": 0,
      "value": 22
    },
    {
      "position": 0,
      "axle": 1,
      "value": 24
    },
    {
      "position": 1,
      "axle": 1,
      "value": 22
    },
    {
      "position": 2,
      "axle": 1,
      "value": 21
    },
    {
      "position": 3,
      "axle": 1,
      "value": 22
    },
    {
      "position": 1,
      "axle": 2,
      "value": 16
    },
    {
      "position": 2,
      "axle": 2,
      "value": 16
    }
  ]
}

The TPMS data can be sent to an external server via a forwarder in separate fields.

Counters

The rawdata API allows for extreme flexibility when browsing events.

Perhaps the most frequent use case for the rawdata API, is a resampling of a vehicle(s) counters over a period of time.

For example, to view how much the vehicle’s counters changed over a large period, such as a month for example, you would make a request such as :

GET api/rawdata?vehicles=2600&duration=P1M&fields=$counters&resample=event_time&how=$counters:diff&freq=1M&group_by=vid

This would give you values such as the total distance covered, total time driving, total amount of fuel used for that month. For a more in depth view, such as what happened each day of that month, you would adjust the freq parameter to your liking. such as 1D.

Given this frequent use case, we provide a separate, specialized API for browsing counters which automatically does the resampling for you.

The counters API has nearly all of the functionality of the rawdata API, along with some added fields.

Here is a list of the paramateres accepted by the counters API.

Parameter Description
from Date from YYYY-MM-DD[Thh:mm:ss]
to Date to YYYY-MM-DD[Thh:mm:ss]
duration ISO_8601 Duration format (PnYnMnDTnHnMnS, PnW, PT) (ex: P1D = Past 1 Day)
vehicles Vehicles to get data from
distance unit to return distance values in (default: meters)
volume unit to return volume values in (default: liters)
time unit to return time values in (defalut: second)
speed unit to return speed values in (default: distance_unit/time_unit)
groups Groups to get data from
filter Create a custom filter for the results
delta fragment size.
order Order the results by a particular field
head Get top n events from result
tail Get bottom n events from result
export Export the data to json (default), html, csv, or tsv
round Round the results to ‘x’ number of decimal places (1-10)
async Run the report in the background (returns a job id)

You may override the speed values to either kph, mph, or user.

A speed preference of 'user’ establishes either kph or mph based on the users distance preference (km or mile respectively)

Introduction

api/counters

{
    ...
    "base": {
        "dev_dist": "Distance reported by Syrus",
        "ecu_ifuel": "Fuel spent while idling, reported by ECU monitor",
        "ecu_eidle": "Idle time reported by ECU monitor",
        "ecu_dist": "Distance reported by ECU monitor",
        "dev_ign": "Engine time reported by Syrus",
        "dev_idle": "Idle time reported by Syrus",
        "dev_orpm": "Time with engine in high RPM's, reported by Syrus",
        "ecu_eusage": "Engine usage time reported by ECU Monitor",
        "dev_ospeed": "Time overspeeding, reported by Syrus",
        "ecu_tfuel": "Total fuel speng, reported by ECU monitor"
    },
    "derived": {
        "dev_tot_avg_speed": "Total average speed, Syrus. dev_dist/dev_ign",
        "ecu_tra_avg_speed": "Traveling average speed, ECU. ecu_dist/(ecu_eusage-ecu_eidle)",
        "ecu_tot_fuel_efcy": "ECU calculated Fuel efficiency. ecu_dist/ecu_tfuel",
        "ecu_tra_fuel_efcy": "ECU calculated Traveling fuel efficiency. ecu_dist/(ecu_tfuel-ecu_ifuel)",
        "dev_tra_fuel_efcy": "Syrus calculated Traveling fuel efficiency. dev_dist/(ecu_tfuel-ecu_ifuel)",
        "dev_tra_avg_speed": "Traveling average speed, Syrus. dev_dist/(dev_ign-dev_idle)",
        "ecu_fuelp_idling": "Fuel percentage used while idling. ecu_ifuel*100/ecu_tfuel",
        "ecu_tot_avg_speed": "Total average speed, ECU. ecu_dist/ecu_eusage",
        "dev_tot_fuel_efcy": "Syrus calculated Fuel efficiency. dev_dist/ecu_tfuel"
    }
}

Pegasus keeps track of various internal counters for each vehicle. The counters are an absolute value that always increase over time.

The counters api is used for knowing time, distance, and volume information for any vehicle within a given time range.

Distance, time and volume units are stored in meters, seconds, and liters respectively.

Sources for the counters

The source of the data is controlled by the managed configuration on the device. The ECU Monitor provides data from the computer onboard the vehicle, whether OBDII or J1939/1708.

Counter field Description
dev_dist Traveled distance
dev_ign Ignition time
dev_idle Time in idle
dev_ospeed Time spent speeding
dev_orpm Time spent over RPM threshold
ecu_dist Engine Distance
ecu_eusage Engine Ignition
ecu_eidle Engine Idling
ecu_tfuel Fuel consumption
ecu_ifuel Idle fuel consumption

Considering these as base counters. The Pegasus API provides derived calculated counters:

Derived field Description
dev_tot_avg_speed Total average speed, Syrus.
dev_tra_avg_speed Traveling average speed, Syrus.
dev_tot_fuel_efcy Syrus calculated Fuel efficiency.
dev_tra_fuel_efcy Syrus calculated Traveling fuel efficiency.
ecu_tot_avg_speed Total average speed, ECU.
ecu_tra_avg_speed Traveling average speed, ECU.
ecu_tot_fuel_efcy ECU calculated Fuel efficiency.
ecu_tra_fuel_efcy ECU calculated Traveling fuel efficiency.
ecu_fuelp_idling Fuel percentage used while idling.

Browser

The counters API encapsulates some of the complexities that the rawdata provides, in order to streamline the counters information.

The counters API supports two main use cases.

Absolute Changes

Total counter values for month of November

api/counters?vehicles=2600&from=2018-11-01T00:00:00&to=2018-11-30T23:59:59

{
    "units": {
        "volume": "liter",
        "distance": "meter",
        "speed": "meter/second",
        "time": "second"
    },
    "counters": [
        {
            "ecu_dist": 7285823,
            "vid": 2600,
            "ecu_ifuel": 49.6,
            "dev_tot_avg_speed": 9.7753377857,
            "from": "2018-10-31T23:59:49",
            "dev_idle": 188131,
            "ecu_eidle": 75960,
            "ecu_fuelp_idling": 1.3752564742,
            "to": "2018-11-30T23:00:00",
            "ecu_eusage": 662760,
            "ecu_tot_avg_speed": 10.9931543847,
            "ecu_tfuel": 3606.6,
            "ecu_tra_avg_speed": 12.4161946149,
            "dev_orpm": 54301,
            "dev_tra_fuel_efcy": 2049.6412707338,
            "ecu_tot_fuel_efcy": 2020.1361393002,
            "ecu_tra_fuel_efcy": 2048.3055946022,
            "dev_dist": 7290574,
            "dev_ign": 745813,
            "dev_tra_avg_speed": 13.0729950043,
            "dev_tot_fuel_efcy": 2021.4534464593,
            "dev_ospeed": 23452
        }
    ]
}

To view a vehicle’s metrics over a period of time, simply pass the vehicles or groups parameter, along with a from and to date or a duration.

Like in the rawdata api, the to parameter is defaulted to the time the request is made

The resources return an envelope with the units, and counters for the given time range.

Additionally, each counter object within the counters array, contains a from and to property. These properties are the times of the start event and end event respectively.

Fragmented changes

Daily counters requests for the past 30 Days
api/counters?vehicles=2600&duration=P30D&delta=1D

{
    "units": {...},
    "counters": [
        {
            "ecu_dist": 179603,
            "vid": 2600,
            "ecu_ifuel": 1.4,
            "dev_tot_avg_speed": 5.8565823033,
            "from": "2018-11-01T00:00:54",
            "dev_idle": 10879,
            "event_time": "2018-11-01T00:00:00",
            "dev_ospeed": 269,
            "ecu_fuelp_idling": 0.7769145394,
            "to": "2018-11-01T22:30:10",
            "ecu_eusage": 22860,
            "ecu_tot_avg_speed": 7.8566491689,
            "ecu_tfuel": 180.2,
            "ecu_tra_avg_speed": 8.67647343,
            "dev_orpm": 0,
            "dev_tra_fuel_efcy": 1001.7114093959,
            "ecu_tot_fuel_efcy": 996.6870144283,
            "ecu_tra_fuel_efcy": 1004.4910514541,
            "dev_dist": 179106,
            "dev_ign": 30582,
            "dev_tra_avg_speed": 9.0902908187,
            "dev_tot_fuel_efcy": 993.9289678135,
            "ecu_eidle": 2160
        },
        {
            "ecu_dist": 8047,
            "vid": 2600,
            "ecu_ifuel": 0.9,
            "dev_tot_avg_speed": 1.8951807229,
            "from": "2018-11-02T00:30:10",
            "dev_idle": 2906,
            "event_time": "2018-11-02T00:00:00",
            "dev_ospeed": 0,
            "ecu_fuelp_idling": 12.676056338,
            "to": "2018-11-02T22:18:52",
            "ecu_eusage": 4320,
            "ecu_tot_avg_speed": 1.8627314815,
            "ecu_tfuel": 7.1,
            "ecu_tra_avg_speed": 2.6297385621,
            "dev_orpm": 0,
            "dev_tra_fuel_efcy": 1268.5483870956,
            "ecu_tot_fuel_efcy": 1133.3802816892,
            "ecu_tra_fuel_efcy": 1297.9032258053,
            "dev_dist": 7865,
            "dev_ign": 4150,
            "dev_tra_avg_speed": 6.3223472669,
            "dev_tot_fuel_efcy": 1107.7464788723,
            "ecu_eidle": 1260
        },
        ...
    ...
}

You can also query the counters API for subranges, similar to the resampling frequency in the Rawdata API (freq paramater). This allows you to get multiple data points per request.

Say for example, you want to view the distance traveled by a vehicle per day, for the past 30 days.

You could, make 30 requests, to the counters API with varying start and end days representing each day in your desired range.

This however, is not an optimal request. Since it requires multiple requests to complete,and may also trigger the rate limiter.

In order to circumvent this, you could instead request the counters API for a fragmented snapshot of the counters.

Simply pass the from and to dates that encapsulate the desired range, along with the delta parameter representing your desired fragment size (1D for Daily for example)

Instead of 30 one day requests, you instead have 1 requests, spannig 30 days, with 1 day fragments.

Vehicle Counters

The counters mantained by pegasus are absolute, meaning they always increase. In order to facilitate the upkeep of virtual odommeters. Pegasus allows you to see counters per vehicle, globally and per user.

Global vehicle counters

Global vehicle counters for vehicle 1716
api/vehicles/1716/counters

{
  "user": [],
  "vehicle": {
    "plain": {
      "dev_dist": 67972874,
      "ecu_dist": 59729515,
      "dev_ign": 4330585,
      "dev_idle": 547952,
      "dev_ospeed": 444158,
      "ecu_ifuel": 3860,
      "ecu_eusage": 119240,
      "ecu_eidle": 29570,
      "ecu_tfuel": 232508
    },
    "calculated": {},
    "counters": {}
  }
}

Updating the global vehicle dev_dist (odometer) counter for vehicle 1716

PUT api/vehicles/197/counters

{
  "counter": "dev_dist",
  "value": 1203942
}

You can view a vehicles counters by inspecting the vehicle

GET /api/vehicles/:vid/counters

Updating Vehicle Counters

Let’s say you want to edit the vehicle’s distance counter to match the odometer on your car, simply make a

PUT /api/vehicles/:vid/counters

where the body of the request is the name of the counter and value

{
  "counter": "dev_dist",
  "value": 123456789
}

This will set the dev_dist or odometer value to 123456789 meters.

Please note that these changes are global (meaning it will be seen by other users) and they affect the counters API values, thus it’s something that you should NOT update regularly.

counter value units (these units are fixed)
dev_dist meters
ecu_dist meters
dev_ign seconds
dev_idle seconds
dev_ospeed seconds
ecu_ifuel liters
ecu_eusage seconds
ecu_eidle seconds
ecu_tfuel liters

User Counters

Get the user counters for a particular vehicle api/vehicles/197/counters

{
  "user": [
    {
      "description": "Time since new alternator",
      "set_at": 1474660977.65856,
      "counter": "dev_ign",
      "value": 19529142,
      "offset": 9690591,
      "id": 0
    }
  ],
  "vehicle": {...}
}

User counters are unique for every user. These values can be edited at any point by the user and not affect any other user’s counters.

You can create as many user counters as you’d like for the same vehicle.

To see the counters you have defined you can use:

GET /api/vehicles/:id/counters

These counters exist only in this API, the idea here is that once you create them you can query this API again at any point to see the new values for these custom user counters.

Create

Create a new user counter that starts counting distance starting at 123 from the moment it’s created
POST api/vehicles/197/counters

{
  "counter": "dev_dist",
  "initial_value": "123",
  "description": "Some description"
}

Let’s create a user counter for those new tires you just changed

Updating User Counters

In order to update a user counter you create, you can make a PUT request to the specific counter id: PUT /api/vehicles/:vid/counters/:id

the body of the request is the name of the counter, description, initial_value

{
  "counter": "dev_dist",
  "description": "front tires",
  "initial_value": 0
}

These changes apply to that particular vehicle for the user that changed.

Rawdata

Raw data consists of a list of observations within a queried time range. The rawdata API allows you to retrieve data, with a high degree of flexibility. You can transform fields to your liking, perform small calculations, and resample data.

For large data sets, the request can be delegated to a job. This will significantly improve the chances of retrieving the data set, circumventing timeouts and potential network issues.

The rawdata api has several query params that can be passed to specify the data need.

Param Description
from Date from YYYY-MM-DD[Thh:mm:ss]
to Date to YYYY-MM-DD[Thh:mm:ss]
duration ISO_8601 Duration format (PnYnMnDTnHnMnS, PnW, PT) (ex: P1D = Past 1 Day)
vehicles Vehicles to get data from
groups Groups to get data from
fields Which data fields do you want to include
exclude Exclude the following fields
types Event types to search for
labels Filter by the following labels, which are for describing the event generated
codes Filter by event code (not recommended, use labels instead)
distance unit to return distance values in (default: meters)
volume unit to return volume values in (default: liters)
time unit to return time values in (defalut: second)
speed unit to return speed values in (default: distance_unit/time_unit)
raw Show the rawdata format
filter Create a custom filter for the results
resample Activate resampling, can only be event_time or system_time
freq Resampling frequency, required for resampling.
how resampling method to use, defaults to ‘mean’.
fill How to fill empty rows after resampled (pad, ffill, bfill)
group_by group events by specific fields before resampling.
order Order the results by a particular field
head Get top n events from result
tail Get bottom n events from result
export Export the data to json (default), html, csv, or tsv
async Run the report in the background (returns a job id)

Fields

Get a list of all rawdata fields
https://pegasus1.pegasusgateway.com/api/rawdata

{
  "keys": {
    "io_exp_in1": {
      "short_desc": "exp in1",
      "long_desc": "I/Os expander input 1",
      "type": "boolean",
      "group": "IO related"
    },
    "code": {
      "short_desc": "EVC",
      "long_desc": "GPS Event code reported by 'EV' msg",
      "type": "number",
      "group": "Event identification"
    },
    "ecu_distance": {
      "short_desc": "VDist",
      "long_desc": "Vehicle dashboard odometer reported by ECUMon [m]",
      "type": "number",
      "group": "ECU monitor accessory related"
    },
    "ecu_idle_fuel": {
      "short_desc": "IFuel",
      "long_desc": "Fuel consumed in IDLE. Rep. by ECUMon [L x10]",
      "type": "number",
      "group": "ECU monitor accessory related"
    },
    "cf_rssi": {
      "short_desc": "rssi",
      "long_desc": "GSM Cell rssi (0-31)",
      "type": "number",
      "group": "Communication related"
    },
    "pid": {
      "short_desc": "Pegasus ID",
      "long_desc": "Pegasus site ID",
      "type": "number",
      "group": "Site identification"
    }
  }
}

The rawdata api allows you to select fields from the pegasus’ events table. Simply pass the fields parameter to the request with the fields you want.

To view a list of all the fields available to you, perform an empty GET request on the rawdata resource

By default all rawdata requests come with

To select fields, simply pass them to fields parameter

/rawdata?fields=comdelay,speed,cf_rssi,hdop,dev_dist...

You may also pass a JSON array to the fields parameter, this allows for higher flexibility when doing complex transformations.

/rawdata?fields=["dev_ign","dev_idle","cf_rssi","hdop","dev_dist"]

For a list of the rawdata fields please refer to the

Master Fields List

For a more detailed list of the rawdata fields please refer to:

Pegasus API Fields

Sets

you can pass sets, which are a group of fields (ex. basic, counters, network, photo …) as part of the fields parameter preceeded by $

/rawdata?fields=$basic,$network

Exclude

If you want to bring some parts of a set or sets, it may be better to include the whole set, and then exclude what you dont want. In order to do this you can pass the excludes parameter.

/rawdata?fields=$basic&excludes=speed,mph

The excludes paramater also supports regular expressions, this allows you to exclude multiple fields at once: For example, bring all device counters and exclude all ecu counters

/rawdata?fields=$counters&exclude=$ecu.*^

Instead of:

/rawdata?fields=dev_dist,dev_idle,dev_ign,dev_ospeed,dev_orpm...

Transformations

In addition to selecting fields, you can rename and create new fields.

A rawdata transformation that renames rssi, latitude, and longitude
https://pegasus1.pegasusgateway.com/api/rawdata?vehicles=197&duration=P1D&fields=latitude:@lat,longitude:@lon,rssi:@cf_rssi,speed,head

{
  "head": 9,
  "vid": 197,
  "event_time": "2016-10-16T22:12:20",
  "system_time": "2016-10-16T22:12:24.412584",
  "longitude": -75.49467,
  "latitude": 10.35501,
  "rssi": 28,
  "speed": 0,
  "id": 5014678489
}

Renaming Fields

To rename a field, simply pass the name you want, and the field it is renaming referenced with @ and separated by a :

renamed_field:@field

odometer:@dev_dist

You can do as many of these as you want.

/rawdata?fields=rssi:@cf_rssi,satellites:@sv,gps_quality:@hdop

Building fields

Rawdata request with a simple operator
https://pegasus1.pegasusgateway.com/api/rawdata?vehicles=1674&from=2016-10-05&to=2016-10-09&fields=ratio:@lat/@lon,lat,lon

{
  "system_time": "2016-10-05T00:06:40.998478",
  "ratio": -0.3205509899,
  "vid": 1674,
  "event_time": "2016-10-05T00:06:21",
  "lon": -80.16553,
  "lat": 25.69714,
  "id": 5014187981
}

Rawdata request that has more operators and manipulations
https://pegasus1.pegasusgateway.com/api/rawdata?vehicles=1674&from=2016-10-06&to=2016-10-07&fields=kph:@speed,mph,vehicle_battery_volts:@ecu_battery/1000,communication_delay:(@system_epoch-@event_epoch),centimeters_per_second:@mph*44.704,speed_in_knots:@mph*0.868976

{
  "system_time": "2016-10-06T15:51:02.014862",
  "vid": 1674,
  "event_time": "2016-10-06T15:50:58",
  "communication_delay": 4.0148599148,
  "mph": 7,
  "speed_in_knots": 6.082832,
  "centimeters_per_second": 312.928,
  "kph": 11.26538,
  "vehicle_battery_volts": null,
  "id": 5014260288
}

You can also use basic arithmetic operations to build new fields:

Divide the latitude by the longitude

ratio:@lat/@lon

or subtract epoch timestamps for the time the event was received by the time the event was generated.

comdelay:@system_epoch-@event_epoch

Remember, you can also use numbers in the transformations, for example to get the km reported by dev_dist:

km:@dev_dist/1000

vehicle_battery_volts:@ecu_battery/1000

centimeters_per_second:@mph*44.704

knots:@mph*0.868976

Casting Fields

You can also concatenate strings

/rawdata?fields:["google:'https://google.com/maps?q=' + @lat__str + ',' + @lon__str"]

/rawdata?vehicles=2600&duration=P1D&fields=%5B%22$basic%22,%22google:%27https://google.com/maps?q=%27%20%2B%20@lat_str%20%2B%20%27,%27%20%2B%20@lonstr%22%5D&distance=km&volume=liter&time=second&speed=kph&order=vid,eventtime,system_time&tz=America/New_York

If you get a validation error, make sure the castings match! How? Simply append one of

Rawdata request that casts the speed as a string
https://pegasus1.pegasusgateway.com/api/rawdata?vehicles=1674&from=2016-10-05&to=2016-10-09&fields=speed_as_string:@speed__str,speed&speed=kph

{
  "system_time": "2016-10-06T16:36:54.534108",
  "vid": 1674,
  "event_time": "2016-10-06T16:36:45",
  "speed_as_string": "20.92142",
  "speed": 20.92142,
  "id": 5014261769
}

Filtering

Rawdata request filtered by events with valid positions
https://pegasus1.pegasusgateway.com/api/rawdata?vehicles=197&from=2016-10-30T08:00:00&to=2016-10-30T23:59:59&fields=mph,valid_position&filter=valid_position

{
  "system_time": "2016-10-30T12:03:08.701770",
  "vid": 197,
  "event_time": "2016-10-30T12:03:05",
  "mph": 1,
  "valid_position": true,
  "id": 5002929550
}

Rawdata request filtered by events with valid positions and mph > 30
https://pegasus1.pegasusgateway.com/api/rawdata?vehicles=197&from=2016-10-30T08:00:00&to=2016-10-30T23:59:59&fields=mph,valid_position&filter=valid_position+and+mph>30

{
  "system_time": "2016-10-30T12:03:08.701770",
  "vid": 197,
  "event_time": "2016-10-30T12:03:05",
  "mph": 1,
  "valid_position": true,
  "id": 5002929550
}

Rawdata request with a filter that shows events after 8 with speeds greater than 20 and valid positions
https://pegasus1.pegasusgateway.com/api/rawdata?vehicles=197&from=2016-10-10T08:00:00&to=2016-10-11T23:59:59&fields=mph,valid_position,event_hour&filter=system_hour>8+and+(speed>20+and+valid_position)

{
  "system_time": "2016-10-10T09:14:59.506056",
  "vid": 197,
  "event_time": "2016-10-10T09:14:57",
  "mph": 28,
  "valid_position": true,
  "id": 5014414518,
  "event_hour": 9
}

The rawdata allows you to filter fields that meet a certain criteria. Using the filter field on the request, you can pass complex boolean logic that meets your criteria.

You can apply boolean logic to filter the desired results, available operators:

>, < , >= , <=, ==, !=, and, or, not

Some examples:

valid_position and speed > 30

label == "spd" and mph < 50

(lat < -4 and lat > -5) and ( lon < -74 and lon > -75 )

system_hour == 7 and (system_minute > 0 and system_minute < 30)

speed > 50

A more complex example:

(event_wkday == 3) and cf_rssi < 10 and ( event_hour > 7 and event_hour < 17)

Which translates to: get all events on wednesdays between 7AM and 5PM with an cf_rssi value less than 10 (low GSM signal)

Codes

You can further filter by looking at individual event codes generated, event codes depend on the managed configuration of the device.

Rawdata request of only event codes 4 and 47 https://pegasus1.pegasusgateway.com/api/rawdata?vehicles=1674&from=2016-9-30T08:00:00&to=2016-9-30T23:59:59&fields=$basic&filter=speed+%3E+10&codes=4,47

{
  "ecu_battery": null,
  "head": 7,
  "code": 47,
  "hdop": 1.16,
  "event_time": "2016-09-30T14:14:46",
  "ecu_distance": null,
  "vid": 1674,
  "lon": -80.16431,
  "sv": 7,
  "mph": 16,
  "label": "agglnchng",
  "valid_position": true,
  "type": 10,
  "lat": 25.69373,
  "system_time": "2016-09-30T14:14:49.760305",
  "speed": 16,
  "id": 5014039405,
  "device_id": 357042060068252
}

Labels

GET labels api/labels

{
  ...
  "spd": {
    "edited_at": "2017-07-21T13:56:49.184650+00:00",
    "en": "Speeding:The vehicle has exceeded the speed limit continuously for more than the threshold configured",
    "created_at": "2017-07-21T13:56:49.184766+00:00",
    "label": "spd",
    "es": "Exceso de velocidad:El vehiculo ha excedido el limite de velocidad continuamente por mas del umbral configurado"
  },
  ...
}

Filtering by labels allows you ask for all the specific events across your fleet, no matter the configuration of the device. Labels are shared for every configuration, so you can ask for all the aggressive lane changes and speeding events for all your vehicles, regardless of the configurations of the devices.

You can get a list of all labels with the following API

GET /api/labels

Response

Field Description
edited_at time it was last edited (UTC)
en english_short_description:english_long_description
created_at time it was created (UTC)
label label value
es spanish_short_description:spanish_long_description

For a list of the possible labels please look at the Detailed Fields List

Rawdata request from group 500 with speeding and aggressive lane change events https://pegasus1.pegasusgateway.com/api/rawdata?groups=500&from=2016-9-30T08:00:00&to=2016-9-30T23:59:59&fields=$basic&filter=speed>10&labels=agglnchng,spd

{
  "head": 191,
  "code": 47,
  "hdop": 0.75,
  "event_time": "2016-09-30T11:40:30",
  "type": 10,
  "vid": 1673,
  "lon": -80.20623,
  "sv": 12,
  "mph": 22,
  "label": "agglnchng",
  "valid_position": true,
  "lat": 25.82955,
  "system_time": "2016-09-30T11:40:36.382065",
  "speed": 22,
  "id": 5014035611,
  "device_id": 357042060068740
}

Types

Rawdata request for maximum speed (metric==2) in driving metric events (types=12)
https://pegasus1.pegasusgateway.com/api/rawdata?vehicles=1674&from=2016-10-01T00:00:00&to=2016-10-10T23:59:59&fields=metric,metric_value&filter=metric==2&order=metric&types=12&speed=mph

{
  "system_time": "2016-10-01T16:10:13.464688",
  "metric_value": 20,
  "vid": 1674,
  "metric": 2,
  "event_time": "2016-10-01T16:08:47",
  "id": 5014071812
}

Events reported by the devices are classified by types, the most common type is 10, which means it’s a regular GPS event. There are other useful types for example 12, which gives you the driving metric values of the vehicles (Max Acceleration, Deceleration and Speed per trip) In order to filter by types simply state:

types=12

Type Description
10 EV TAIP regular events (GPS Type)
11 PV TAIP position & velocity (GPS Type)
12 RXAIT driving metrics (GPS Type)
13 GPS BackLog (GPS Type)
20 empty GPS Event (gps time = 0)
100 Keep-alive (Connection Type)
110 XART TAIP (Connection Type)
111 XARS SIM Card Operator notice (Connection Type)
150 Message
301 Duplicate GPS Event (Other Type)

Ordering

Rawdata request ordered by code (increasing), and mph (decreasing)
https://pegasus1.pegasusgateway.com/api/rawdata?groups=500&fields=$basic&duration=PT4H&order=code,-mph

{
  "head": 102,
  "code": 3,
  "hdop": 1.48,
  "event_time": "2016-10-17T23:24:02",
  "type": 10,
  "vid": 1483,
  "lon": -80.44694,
  "sv": 4,
  "mph": 0,
  "label": "ignoff",
  "valid_position": true,
  "lat": 25.66764,
  "system_time": "2016-10-17T23:24:05.677751",
  "speed": 0,
  "id": 5014716545,
  "device_id": 356612026170920
}

You can also order the resulting data set however you choose. Simply pass the order field to the request

order=mph

This will order the events by mph in ascending order. but what about ascending?

Simple just append a -, to the field you want to order

order=-mph

What about multilevel ordering? Sure thing, no problem:

order=vid,-mph

This will return all events sorted by vehicle id (vid) and then by speed in descending order

Limiting

Rawdata request that limits the results to the first two and last 3 events
https://pegasus1.pegasusgateway.com/api/rawdata?groups=500&fields=$basic&duration=PT4H&order=code,-mph&filter=code%3E1%20and%20code%3C10&head=2&tail=3

{
  "head": 280,
  "code": 8,
  "hdop": 0.64,
  "event_time": "2016-10-17T22:43:00",
  "type": 10,
  "vid": 909,
  "lon": -83.85399,
  "sv": 13,
  "mph": 0,
  "label": "slwtrfc",
  "valid_position": true,
  "lat": 10.25766,
  "system_time": "2016-10-17T22:43:03.888619",
  "speed": 0,
  "id": 5014715284,
  "device_id": 356612026180218
}

By default the rawdata request will return all the events that match your criteria.

What if you want to see the first x events. Simply pass the head argument to the request

head=100

Will return the top 100 events from the set.

Want to see the last n events? pass tail as the argument.

tail=100

Want both? How about the first 100 and bottom 50 events?

head=100&tail=50

Resampling

Returns the difference in all counters (max-min), resampled at 1 day intervals and grouped by vids from November 1 . This gives you the total distance traveled, ignition on time, etc. per day per vehicle
https://pegasus1.pegasusgateway.com/api/rawdata?vehicles=617,654&fields=$counters&from=2015-11-01T00:00:00&to=2015-11-10T00:00:00&filter=(valid_position+and+hdop+<+3)&how=$counters:diff&freq=1D&group_by=vid&resample=event_time

{
  "dev_dist": 72542,
  "vid": 909,
  "ecu_dist": 72421,
  "event_time": "2015-11-09T00:00:00",
  "dev_idle": 21069,
  "dev_orpm": 8151,
  "dev_ospeed": 0,
  "ecu_ifuel": 19.4,
  "ecu_tfuel": 212.4,
  "ecu_eusage": 36900,
  "ecu_eidle": 14400,
  "dev_ign": 40823
}

Returns the mean value of all comdelays and the mean value of the RSSI (signal strength) sampled at 1 day intervals, grouped by vehicle IDs
https://pegasus1.pegasusgateway.com/api/rawdata?vehicles=617,654&fields=$basic,comdelay,rssi_avg:@cf_rssi&from=2015-11-1T00:00:00&to=2015-11-10T00:00:00&filter=(comdelay+<+3600)&how=comdelay:mean,rssi_avg:mean&freq=1D&group_by=vid&resample=event_time

{
  "comdelay": 155.2830875629,
  "rssi_avg": 15.835443038,
  "event_time": "2015-11-01T00:00:00",
  "vid": 617
}

Resampling is an important part of data analysis, timed data can be normalized to evenly timed chunks.

Events that pass through the Pegasus Gateway naturally contain time noticermation.

These fields are:

The Rawdata API allows you to resample data based on either one of these.

There are 5 fields important to resampling.

resample

Used to activate resampling. Can only be event_time or system_time.

freq

Establishes the frequency by which to resample. Must meet the format:

where N is equal to a number greater than 0. and F can be one of:

how

Determines how to resample the data, based on the frequency established. This must be one of.

You can also resample different fields by different methods. Simply pass the fields as a csv, with the transformation you want separated by :

field:method

how=dev_dist:diff,cf_rssi:mean,hdop:mean,hdop:max,vdop:min

want to apply the same resample method to a set? Simply:

how=$counters:diff

group_by

You can also group the events before performing a resample. this is useful if you want to keep events tied to a specific field, such as the vehicles id (vid).

group_by:vid

You can additionally group by more than one field:

group_by:vid,label

Output Formats

Export as HTML
https://pegasus1.pegasusgateway.com/api/rawdata?vehicles=197&from=2015-10-30T08:00:00&to=2015-10-30T23:59:59&fields=vid,lat,lon&export=html

event_time id label lat lon vid
2015-10-30T12:03:05 5002929550 trckpnt 9.80091 -74.76004 197
2015-10-30T12:08:06 5002929669 trckpnt 9.80670 -74.73022 197

By default, events come in a JSON envelope under the events property.

The rawdata API also allows you to export in other formats:

Simply pass the export parameter on the request

export=html

Need another format? Send us a message on our Gitter or create an issue on our github

Asynchronous Requests

An asynchronous requests that generates a job id to be queried later
https://pegasus1.pegasusgateway.com/api/rawdata?vehicles=197&from=2015-9-30T08:00:00&to=2015-9-30T23:59:59&fields=ecu_battery,ecu_distance&filter=speed>10&async=true

{
  "message": "Job created",
  "job_id": 28813
}

While the job is being processed in the background you can see the progress under /jobs/:job_id
https://pegasus1.pegasusgateway.com/api/jobs/28813

{
  "control": "run",
  "stdout": "",
  "app": "pegasus2.0",
  "notice": null,
  "id": 28813,
  "user_id": 1,
  "state": "queued",
  "params": {
    "all": false,
    "event_groups": null,
    "labels": null,
    "raw": false,
    "export": null
  ...
}

Once the job is finished you can see the data here
https://pegasus1.pegasusgateway.com/api/jobs/28813/data.json

[
  {
    "code": 1,
    "device_id": 356612022409637,
    "ecu_battery": 13350,
    "ecu_distance": 269302153,
    "event_time": "2015-09-30T14:59:06",
    "hdop": 0.94,
    "head": 225,
    "id": 5002464983,
    "label": "",
    "lat": 4.61529,
    "lon": -74.10331,
    "mph": 11,
    "speed": 11,
    "sv": 8,
    "system_time": "2015-09-30T14:59:09.565434",
    "type": 10,
    "valid_position": true,
    "vid": 197
  }
]

Results returned by the rawdata API can get big, and we mean big. This can bring up all sorts of issues when using via a web browser.

These include but are not limited to:

In order to circumvent these issues, and guarantee that data is always retreived as requested. You can leave the query and subsequent processes (transformations, filtering and resampling) running in the background.

The async flag delegates the rawdata request to a Job to ensure the data is stored and can be safely used and reused

Simply set the async flag on the request

async=1

The request immediately returns a job ID you can query the job ID to see the progress of the rawdata request /api/jobs/:jobid

When the job finishes you can see the by accesing the jobs data Data is stored depending on your export format.

For JSON (default) /api/jobs/:jobid/data.json

For CSV, TSV, and HTML /api/jobs/:jobid/data.{export_format}

Trips

Request the trips for a vehicle
https://pegasus1.pegasusgateway.com/api/trips?vehicles=45&from=2015-12-25T10:05:00&to=2015-12-25T11:00:00&fields=distance,mean_speed,duration,moving,start_time&distance=km&time=minute&speed=kph

[
    {
        "distance": 13.405,
        "mean_speed": 43.28,
        "start_time": "2015-12-25 10:04:05",
        "moving": true,
        "duration": 18.58
    },
    {
        "distance": 0,
        "mean_speed": 0,
        "start_time": "2015-12-25 10:22:40",
        "moving": false,
        "duration": 5.87
    },
    {
        "distance": 25.33,
        "mean_speed": 36.49,
        "start_time": "2015-12-25 10:28:32",
        "moving": true,
        "duration": 41.65
    }
]

With the trips api we can get summarized data about a collection of events over a time span grouped in a convenient and natural way.

For each vehicle’s trip we can request for example the summary for counters changes and have information of important trip’s events (like for maximum speed).
This information is already calculated and stored for each trip, so it is much more efficient to get this kind of data using the trips api than the more general rawdata or counters api, and of course you don’t have to deal with how to partition the raw data to get trips’ information.

These are the currently supported query params to get trips data:

Param Description
ids Trips of interest
from Time from YYYY-MM-DD[Thh:mm:ss]
to Time to YYYY-MM-DD[Thh:mm:ss]
duration ISO_8601 Duration format (PnYnMnDTnHnMnS, PnW, PT) (ex: P1D = Past 1 Day)
vehicles Vehicles to get data from
fields Which data fields do you want to include
contained Whether to return only fully contained trips within ‘from’ and 'to’
distance unit to return distance values in (default: meters)
volume unit to return volume values in (default: liters)
time unit to return time values in (default: second)
speed unit to return speed values in (default: distance_unit/time_unit)
export format to export the trips data (csv or tsv)

Fields

View the trips keys/fields and their description
https://pegasus1.pegasusgateway.com/api/trips/keys

{
    "mean_speed": {
        "units": "meter/second",
        "short_desc": "Mean speed",
        "long_desc": "Mean speed calculated with trip's distance and duration values",
        "type": "number"
    },
    "duration": {
        "units": "second",
        "short_desc": "Trip duration",
        "long_desc": "‘Total duration of the trip",
        "type": "number"
    },
    "distance": {
        "units": "meter",
        "short_desc": "Trip distance",
        "long_desc": "Preferred trip distance (ecu_dist or dev_dist)",
        "type": "number"
    },
    ...
}

Request only the units and the type for the trip keys https://pegasus1.pegasusgateway.com/api/trips/keys?data=units,type

{
    "mean_speed": {
        "units": "meter/second",
        "type": "number"
    },
    "duration": {
        "units": "second",
        "type": "number"
    },
    "distance": {
        "units": "meter",
        "type": "number"
    },
    ...
}

Getting the resource trips/keys you can check for the available fields definitions for the trips.

For this resource you can optionally request the data of interest, eg:

GET https://pegasus1.pegasusgateway.com/api/trips/keys?data=units,type

The available options for the data parameter are:

When data=none then no data for the fields is requested and only an array of available fields names is returned.


View the distance, duration, ignition time, idle time and the average speed per trip
https://pegasus1.pegasusgateway.com/api/trips?from=2016-10-17&to=2016-10-18&vehicles=598,599&fields=distance,duration,ignition,idle,mean_speed

{
  "mean_speed": 13.17,
  "duration": 3483,
  "idle": 0,
  "distance": 45876,
  "ignition": 3483
}

When getting trips, if the fields parameter is undefined, then all available trips’ fields data will be returned by default.
You can request for a specific subset of trip information by defining the fields paramater.

GET /trips?fields=moving,distance,mean_speed,duration...

GET /trips?fields=["moving","distance","mean_speed","duration"]...


Notice that one of the possible fields is the moving trip’s property. This flag indicates if the trip object corresponds to a “trip” or an “stop”.
This is offered like this because in the more general use case we want to get the events summary and partitioning within a time range, so both types (trips and stops) are returned.

Geofences

Geofences are user defined areas on the map that can be used together with triggers and tasks for a more personalized experience, for example to let you know when a vehicle reaches a particular location on the map. Geofences are also available when you request the reversegeo information so it’s included in the address response.

Geofences can be grouped into geofence_types (also referred to as geofence collections)

The geofence API is based on the geojson spec, for more information on geojson visit geojson.org

View

Read all geofences api/geofences

[
  {
    "__updated": 1503588036.6539481,
    "encoding": "}amxC|e`mNrDfB~Bc@xAeC\\uEMqEBcDz@RJdGObGSvBr@`GLzGy@bGiArBjBjCpAnAnEsAjCaIW_JgBqHc@kFjAiGw@aEcBqDmDeCoDo@uB~DkDpFqAnIf@jE",
    "geometry": {
      "type": "Polygon",
      "coordinates": [
        [
          [
            -80.943188667297377,
            25.139670888348316
          ],
          [...],
          [
            -80.943188667297377,
            25.139670888348316
          ]
        ]
      ]
    },
    "properties": {
      "name": "Flamingo",
      "visibility": "all",
      "owner": 11,
      "resolution": "name",
      "id": 12,
      "types": [
        55
      ],
      "description": "Campground"
    },
    "centroid": [
      -80.943157696183221,
      25.137118778037884
    ],
    "bbox": [
      -80.948917865753188,
      25.13503791616176,
      -80.938317775726333,
      25.13987485163733
    ],
    "type": "Feature",
    "id": 12
  },
  {
  "__updated": 1503588036.6982861,
  "encoding": "{rj|Clj`iNP@NBNHLHHLFNDN@PAPENGNILMJOFOBQ@QAQCMGMKKMGOEO?Q?QDOFOJMLILIPCPA",
  "geometry": {
    "type": "Circle",
    "radius": 50,
    "coordinates": [
      -80.289000061596184,
      25.78238262858029
    ]
  },
  "properties": {
    "name": "Warehouse 123",
    "visibility": "private",
    "owner": 54,
    "resolution": "name",
    "id": 28,
    "types": [],
    "description": null
  },
  "centroid": [
    -80.289000061596184,
    25.78238262858029
  ],
  "bbox": [
    -80.289451121587163,
    25.781931568589314,
    -80.288549001605205,
    25.782833688571273
  ],
  "type": "Feature",
  "id": 28
}
]

In order to view geofences you have to have the scope geofences assigned to your user.

Response

Field Description
__updated epoch timestamp of last update
encoding lossy compression algorithm used to store the geofence coordinates in a single string
geometry polygon or circle
properties geofence properties including the name, visibility, and if it belongs to any types or groups
centroid central point of the polygon
bbox bounding box (bottom left and upper right corner of the polygon)

Create

Create a circular fence of 52 meter radius around 24.78238, -82.28900

POST https://pegasus1.pegasusgateway.com/api/geofences

{
  "geometry": {
    "type": "Circle",
    "radius": 52,
    "coordinates": [
      -82.28900,
      24.78238
    ]
  },
  "properties": {
    "name": "warehouse 234",
    "visibility": "groups",
    "groups": [
      500
    ],
    "types": [],
    "description": "this is a sample description"
  }
}

Create a square polygon geofence Associated to geofence_type 55 POST https://pegasus1.pegasusgateway.com/api/geofences

{
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [
          -81.07642,
          26.38707
        ],
        [
          -80.96106,
          26.27383
        ],
        [
          -81.11487,
          26.21471
        ],
        [
          -81.23023,
          26.29353
        ],
        [
          -81.07642,
          26.38707
        ]
      ]
    ]
  },
  "properties": {
    "name": "Square Polygon",
    "visibility": "all",
    "types": [
      55
    ],
    "description": "Warehouse with small packages"
  }
}

When creating a geofence you have to specify the Geometry type you want to create, the API supports Polygon of 3 or more coordinates (up to 800 coordinates), or Circle types.

Polygon
geometry.coordinates = [[[lon1,lat1] ,[lon2,lat2],[lon3,lat3], [lon1,lat1]]]

Keep in mind that for Polygon types the last lon,lat pair has to be equal to the first, this tells the API that it’s closed at that point.

Circle
geometry.radius = radius in meters (minimum 50 meters)
geometry.coordinates = [lon1,lat1]

visibility description
all anyone with scope to see geofences has access to see them
groups only people within the group you belong to have access to see the geofence
private only your user has access to see the geofence

If you set the visibility to “groups” you’ll have to specify in an array called: groups the group IDs you’d like this geofence to belong to.

Updating Geofences

Update the name and radius of a geofence

PUT api/geofences/:id

{
    "geometry": {
        "type": "Circle",
        "radius": 52,
        "coordinates": [
            -80.289000061596184,
            25.78238262858029
        ]
    },
    "properties": {
        "name": "warehouse 123"
    }
}

When updating a geofence using the API, pass the geometry and properties object.

Deleting Geofences

Delete a fence

DELETE /api/geofences/:id

204 NO CONTENT

When you delete a geofence this affects the

Geofence Types

Geofence types are collections of geofences, a geofence can belong to one or many types. These collections are useful for quickly generating reports and scheduling them too.

For example, let’s say that you have a fleet of delivery trucks that make daily deliveries to specific locations. These locations can be saved as a geofence_type called: Clients. Thus when generating a trigger for Vehicle Inside Geofence and Idling for example, you want to create a single trigger that encompasses the Clients geofence type we created, rather than individual fences. Note that any future geofences you add to the Client type automatically gets updated.

Create

Create a geofence type

{
  "name": "Clients",
  "color": "#ff0404",
  "visibility": "all",
  "geofences": [
    25,
    1042,
    1044,
    1045,
    1414,
    1415,
    1416
  ],
  "icon": "material:location_city"
}

When creating a geofence type the important parameters are the name, visibility and geofences

You can optionally set a HEX color code for the geofences under the color parameter. Also you can set an icon using the material icon library

"icon": "material:location_city"

or a custom URL

"icon": "url:https://goo.gl/bQFcW5"

Reports

Job-Engines

Pegasus Gateways allow for external job-engines to create its reports. The Pegasus Gateway API handles all user authorizations and scheduling, allowing the job-engines to focus on the reporting logic, in whichever enviroment they choose.

The default job-engine for all gateways is located at:

https://d1.pegasusgateway.com/jobs-engine

You can extend your gateway with your own job-engine.

Required endpoints

Job engines require 3 endpoints to work

Manifest

GET [job_engine_url]/manifest

{
    "definitions": {},
    "scripts": []
}

The manifest is a JSON Schema that represents the parameters required for your scripts to work.

The manifest allows UI applications (like Pegasus App) to build forms for creating the reports, as well as scheduling and running them with your gateways /job_manager API

You can use the default engines manifest as a guide

https://d1.pegasusgateway.com/jobs-engine/manifest

definitions

definitions defined on schema

{
    "definitions": {
        "from": {
            "description": "Events starting time",
            "type": "string",
            "format": "date",
            "peg_type": "$from"
        }
    }
}

referencing definitions from the scripts object

"scripts": [
    ...
    "properties": {
        "from":
            "$ref: #/definitions/from",
    ...
    }
]

You can establish shared definitions that will be used throughout the scripts object. Definitions represent all the resources that you can work with on the Pegasus API (entities, geofences, triggers, etc), they cannot be modified.

use the JSON schema $ref construct to reference definitions within your script elements.


 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

scripts

{
    "script": "my_report",
    "title": "My Custom Report",
    "desc": "My custom report description",
    "icon": "https://imgur.com/link/to/image.svg",
    "app_url": null,
    "category": "trip_analysis",
    "schedule": true,
    "parameters_schema": {...}
}

The scripts object contains all of the available reports on your engine.

param type description
script string unique name for the API to identify each report, no spaces allowed
title string name of the report, spaces are allowed here, up to 50 characters
[desc] string short description of the report, up to 150 characters
[icon] string url with the icon’s location (png or svg), url should be accessible via https
[app_url] string url for adding an embedded app to the Pegasus App UI, url should be accessible via https
[category] string allows you to group the reports on the Pegasus application UI (see table for possible categories)
schedule boolean true to allow the report to be scheduled periodically
[parameters_schema] object defines the parameters the report will use

If you define an app_url, when clicking a report an iframe will be embedded with the app_url loaded, otherwise, pegasus loads a default template.

Example with app_url (custom template)

alt text

Example without app_url (default template)

alt text

category

category name
live_reports Live Reports
accessories Accessories Reports
trip_analysis Trip Analysis Reports
vehicle_metrics Vehicle Metrics Reports
device_behavior Device Behavior Reports
fleet_status Fleet Status Reports

parameters_schema

script’s parameters_schema [job_engine_url]/manifest

    ...
    "parameters_schema": {
        "type": "object",
        "required": ["from", "to"],
        "properties": {
            "from":
                "$ref: #/definitions/from",
            "to":
                "$ref: #/definitions/to",
            "bases":
                "$ref: #/definitions/bases"
            ...
        }
    }

The parameters schema tells applications what parameters are required for the script to run. You define your own schemas, or reference them from your root definitions object.

param type description
type string object
required array which definitions are obligated to be filled in order for the report to execute
properties object reference the definitions from the manifest to ask the user for the parameters

You can see how pegasus reports section displays the engine’s manifest here.

alt text

POST to job_engine

Pegasus makes a POST request to your job engine POST [job_engine_url]/jobs

{
    "configuration": {
        "site_id": "gateway id",
        "site_url": "gateway URL",
        "user_id": "user_id",
        "api_token": "token",
        "tz": "timezone",
        "job_id": 1,
        "job_name": "script_name",
        "job_created_at": timestamp,
        "job_expires": 86400
    },
    "parameters": {
        /* parameters specified by the parameters_schema for this report */
    }
}
{
    "configuration": {
        "site_id": 1,
        "site_url": "https://pegasus1.pegasusgateway.com",
        "user_id": 86,
        "api_token": "9e34d311fc4ad45d726ab731917554ee279bf23cfa5b148df7c30e01",
        "tz": "UTC",
        "job_id": 22222,
        "job_name": "trips",
        "job_created_at": 1527613165.181
    },
    "parameters": {
        "from": "2018-01-01T00:00:00",
        "to": "2018-01-07T23:59:59",
        "vehicles": [5,6,7],
        "tz": "UTC"
    }
}

This is the endpoint where your magic comes through. Pegasus Gateway provides your job engine the necessary parameters to construct a report by sending a POST to [job_engine_url]/jobs with the following info:

param type description
site_id number unique id for every gateway site
site_url string url for the gateway that made the request
user_id string user id that made the request
api_token string api token for the job
job_id number job id used for updating the job on the pegasus api
tz string originating timezone
job_name string name of the script
job_created_at string time the report was ran
job_expires string expiration time of the job

The configuration object contains a site_url and api_token, which enables you to interact with the Gateway’s APIs (/rawdata, /counters, etc) and generate your report.

The job_expires parameter refers to the duration of the jobs time on the gateway (in seconds), it is relative to the jobs job_created_at timestamp, done_at is marked once the job is updated with result error or done.

Note The api_token is restricted to the user’s scopes. You must handle this in your reporting logic (user is asking for a geofence report but does not have access to geofences)

You must use these parameters to report the state of the job back to the gateway

PUT [site_url]/api/job_manager/:job_id


 
 
 
 
 
 
 
 
 
 

Updating the Jobs

Update a report’s progress:

PUT [site_url]/api/job_manager/15

{
    "progress": {
        "percentage": 50
    }
}

Update the parameters for a report if a vehicle id (7) was not found for example:

PUT [site_url]/api/job_manager/15

{
    "parameters": {
        "from": "2018-01-01T00:00:00",
        "to": "2018-01-07T23:59:59",
        "vehicles": [5, 6],
        "tz": "UTC"
}

Update the state to done

PUT [site_url]/api/job_manager/15

{
    "state": "done"
}

Update the job when report is done

PUT [site_url]/api/job_manager/15

{
    "parameters": {},
    "progress": {
        "percentage": 100
    },
    "state": "done",
    "result": {
        "files": ["custom.json", "custom.csv", "custom.xlsx", "custom.pdf"],
        "email": {
            "files": ["custom.xlsx", "custom.pdf"],
            "message": "<h2>Custom Report</h2><br><p>Attached detail with scheduled custom report</p>",
            "subject": "Custom Report"
        },
        "error": ""
    }
}

Report returns an error message

PUT [site_url]/api/job_manager/15

{
    "parameters": { ... },
    "progress": {
        "percentage": 60
    },
    "state": "error",
    "result": {
        "error": "Failed to execute rawdata request"
    }
}

You need to inform the Gateway that started your Job of its progress and available data, to do so you can make PUT requests with the api_token given in the configuration block.

Note site_url refers to the pegasus site url

PUT [site_url]/api/job_manager/:job_id

The payload can contain one or all of the following:

{
  "parameters": { ... },
  "progress": {
    "percentage": 50
  },
  "state": "running"
  "result": {
    "files": [],
    "email": {
      "files": [],
      "message": "",
      "subject": ""
    },
    "summary": {},
    "error": ""
  }
}

When the report is done, you must update the job with other parameters, in this case with the result field, this field has the files before explained.

Updating the job state to error or done closes the job to any further updates. You won’t be able to modify it further.

Getting data from Jobs

GET [site_url]/api/job_manager/15/script_name.json results in [job_egine_url]/jobs/1/15/script.json

{
    "vid": 5,
    "name": "Test 1",
    "from": "2018-01-01T00:00:00",
    "to": "2018-01-07T23:59:59",
    "idleTime": 258929,
    "primary_group": null,
    "resolved": true,
    "percent_idle": 57
},
{
    "vid": 6,
    "name": "Test 2",
    "from": "2018-01-01T00:00:00",
    "to": "2018-07-07T23:59:59",
    "idleTime": 57911,
    "primary_group": null,
    "resolved": true,
    "percent_idle": 25
}

Once your report is finished, This is endpoint used by pegasus to fetch the files generated:

GET [site_url]/jobs/:site_id/:job_id

For example,

GET [site_url]/api/job_manager/15/script_name.json

results in:

[job_engine_url]/jobs/1/15/script.json

Pegasus Job Manager

[site_url]/api/job_manager/engines

[
    "https://d1.pegasusgateway.com/job-engines",
    "..."
]

Each gateway has a /job_manager API designed to interact with the job-engines registered on the gateway

You can view what job-engines are available on [site_url]/api/job_manager/engines

Making the POST request

Create a report POST [site_url]/api/job_manager

{
    "script": "name",
    "name" : "report name",
    "expires": 0,
    "engine": "engine_name",
    "args" : { ... }
}

example creating an idling report from the d1 manifest

POST [site_url]/api/job_manager

{
  "script": "idling",
  "name": "Idling Usage",
  "expires": 432000,
  "engine": "http://d1.pegasusgateway.com/jobs-engine",
  "args": {
    "from": "2018-07-10T00:00:00",
    "to": "2018-07-10T23:59:59",
    "vehicles": [],
    "groups": [
      500
    ],
    "prefs": {
      "distance": "mile",
      "speed": "mph",
      "language": "es",
      "volume": "gallon"
    },
    "tz": "UTC"
  }
}

RESPONSE

{
    "engine": "http://d1.pegasusgateway.com/jobs-engine",
    "transaction": null,
    "name": "Idling Usage",
    "script": "idling",
    "created_at": 1532031389.04,
    "expires": 432000,
    "state": "created",
    "__v": 2,
    "params": {
        "tz": "UTC",
        "vehicles": [
            1673
        ],
        "to": "2018-07-10T23:59:59",
        "groups": [],
        "from": "2018-07-10T00:00:00",
        "prefs": {
            "volume": "gallon",
            "distance": "mile",
            "speed": "mph",
            "language": "es"
        }
    },
    "result": {},
    "done_at": null,
    "owner": 54,
    "progress": {},
    "cache_key": null,
    "id": 251336
}

To create a report pegasus sends a payload to the /job_manager resource [site_url]/job_manager with the following info:

param type description
script string name of the script defined in your manifest
name string name of the report
expires number expiration of job once it’s finished (seconds)
engine string name of the job_engine
args object arguments for the report that was executed

Scheduling

Scheduling a report POST [site_url]/tasks

{
  "id": "task_id",
  "name": "task_name",
  "processes": [
    [
      {
        "name": "report_name",
        "script": "script",
        "tz": "timezone",
        "engine": "job_engine_url"
      },
      {
        "vehicles": [
          5,
          6
        ],
        "recipients": [
          "example@example.com"
        ],
        "user": [
          11
        ],
        "groups": [],
        "back": {
          "days": 7,
          "hours": 0
        },
        "tz": "UTC"
      }
    ]
  ],
  "schedule": []
}

Custom report task POST [site_url]/api/tasks

{
    "name": "Custom Report Task",
    "processes": [
        {
            "name":"Custom Report",
            "script":"my_script",
            "tz": "UTC",
            "engine":"http://mycustomjobengine.com"
        },
        {
            "vehicles": [5,6],
            "recipients": ["example@example.com"],
            "users": [11],
            "groups":[],
            "back": {
                "days": 7,
                "hours": 0
            },
            "tz": "UTC"
        }
    ],
    "schedule": ["0-15 9 * * 1"]
}

Jobs can additionally be scheduled, with the Pegasus /tasks API

Task parameters:

param type description
name string how you want to name the scheduled report
processes array Contains the configuration and parameters
schedule string Cron format. Allows you to define time and frequency to run the task. For more information about Cron, go here: Cron

Configuration parameters:

param type description
name string report name
script string script report
tz string originating timezone
engine string engine where the report will be running

Parameters:

param type description
resource varies specifies the resources from your params object in the script
recipients string array of emails that will receive the scheduled report
users number array of user ids that will receive the scheduled report
back object how many days / hours to run back the report
tz string originating timezone

alt text

Configurations

There are two ways you can configure your Syrus device. One is with “Managed” or legacy configurations, and the other is with advanced “Device Control” configurations.

Managed configurations are scripts that we create and upload under the configurations API, these can be used to configure the device with basic reporting, but their behavior is more restricted in the sense that they have predefined thresholds and limited parameters that can be edited.

Device Control configurations are completely flexible and allow you to create your own configurations as well as edit parts of it using your own parameters. Essentially, with Device Control you can build your own API to configure the unit.

Managed (Legacy) Configurations

Get a list of the managed/legacy configurations

GET api/configurations

{
  "p120": {
    "ky": "p120",
    "name": {
      "en": "Syrus 2 ECU Monitor + Temperature",
      "es": "Syrus 2 ECU Monitor + Temperature"
    },
    "restricted_fw": {
      "max_number": 9999999,
      "allow_only_flavor_string": null,
      "min_number": 2001000
    }
  },
  "p988": {
    "ky": "p988",
    "name": {
      "en": "m2mCloudConnect v10 non ack lite",
      "es": "m2mCloudConnect v10 no ack lite"
    },
    "restricted_fw": {
      "max_number": 3999999,
      "allow_only_flavor_string": null,
      "min_number": 3001050
    }
  }
}

To get a list of the managed configurations the gateway has you can go to

GET api/configurations

Response

Field Description
ky Key that identifies the configuration
name Name of
restricted_fw Min and max device firmwares allowed to upload configurations

ky refers to a unique key that identifies each configuration, when you’re looking at the parameters for a particular configuration you use the api/configurations/ky to reach it.

restricted_fw has 3 fields, two for the min & max firmware, these have the format ABBBCCC where A is the first digit of the firmware BBB is the second digit CCC is the third digit Using the example on the right for “min_number”: 3001050 It’s 3 001 050, removing the 0 in front, we end up with a minimum device firmware required to upload the configuration of 3.1.50, compare this to the version field in the /devices api to know if your device supports that configuration


 
 
 
 
 
 
 
 
 
 
 
 

::View

View a particular managed configuration

GET api/configurations/p988

{
  "ev_labels": {
    "0": "prdtst",
    "1": "trckpnt",
    "2": "ignon"
  },
  "ignition_on_event_code": 2,
  "ignition_off_event_code": 3,
  "tracking_resolutions": {
    "1": [
      null,
      1800
    ],
    "2": [
      null,
      720
    ]
  },
  "allowed_cmds": [
    ">SRT;ECU<",
    ">SXAQQ",
    ">SXAICAA1",
    ">SXAIC"
  ],
  "gps_codes_names": {
    "0": {
      "short": {
        "fr": "évènement 0",
        "en": "Periodic test",
        "es": "Test periódico"
      },
      "long": {
        "fr": "évènement rapporté 0",
        "en": "Periodic test",
        "es": "Test periódico"
      }
    }
  }
  ...
}

To view a managed configuration

GET api/configurations/:ky

Response

Field Description
name Name of configuration
allowed_cmds Commands that are permitted in the device console
ev_labels Event labels
gps_codes_names Names of the events
ignition_off_event_code Event code that’s used for Ignition OFF
ignition_on_event_code Event code that’s used for Ignition ON
ky Unique id for the configuration
params Parameters that can be edited using /remote control api
restricted_fw Minimum firmware needed to load the configuration
sms_alias_actions SMS alias actions
tracking_resolutions Tracking resolutions

View the Commands

View the device commands of a configuration

GET /api/configurations/:ky/cmds

In order to view the device commands of the configuration just go to the GET api/configurations/:ky/cmds


 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

::Set

Set a new managed configuration

POST api/vehicles/197/remote/configuration

Body

{
    "ky": "p988"
}

Response

{
  "msg": "instruction set to device. ",
  "device_is_online": false,
  "oids": [
    543757
  ]
}

View progress of configuration on device

GET api/devices/350000000000001/configuration

Response shows us the state of this configuration is pending (state: 1)

{
  "values_rpmlimit_rpm": null,
  "values_satcom_wait_time": null,
  "values_slowtraffic_distance": null,
  "values_satcomevents": null,
  "values_speedlimit_secs": 10,
  "values_satcom_networktest_time": null,
  "values_tracking_resolution": 5,
  "values_idle_secs": null,
  "values_slowtraffic_secs": null,
  "values_tt_alarm_from_deattach": 0,
  "values_photocamevents": "",
  "id": 7765,
  "state": 1,
  "values_timeonlyreport_mins": null,
  "values_speedlimit_mph": 50,
  ...

In order to change the managed configuration of the device you need to make a POST request to api/vehicle/:vid/configuration passing the ky parameter, which corresponds to a particular configuration.

Once the configuration has been set, you can view the vehicle’s device to get the status of the configuration, whether or not it’s in progress, pending, or done. To do this you need the IMEI of the vehicle you sent the configuration to, then make the following request: GET api/devices/:imei/configuration

the state field has the following values

state description
-2 Configuration error
-1 Configuration mismatch, invalid configuration
0 Inital state, nothing done since configuration assigment
1 Device has pending configuration messages
3 Configuration ready (synchronized)

Device mute

Formerly known as SilenceEvents, this api enables muting, un-muting Syrus’ event codes generation.

When a mute action is POSTed for an imei the following occurs:

When an un-mute action is POSTed:

GET

GET api/device-mute/356612024151062

{
  "evc-1": {
    "state": "querying",
    "oid": 161,
    "ev_code": 1,
    "uid": null,
    "time": 1520865531.0303299
  }
}

As device object too (live package and /devices API):

{
  "imei": 356612024151062,
  "muted_evs": {
    "_epoch": 1520881684.852546,
    "events": {
      "evc-1": {
        "uid": 1,
        "oid": 123,
        "qed_response": "RED01NV0;C00+",
        "state": "muted",
        "restore_command": "SED01NV0;C00+",
        "ev_code": 1,
        "time": 1520881682
      }
    }
  }
}

An object containing muted-events is returned. Its keys follow the format evc-{evcode}

Note

Only possibly muted event codes are returned. Check state to confirm event is actually muted/un-muted

Muted event object

Param Description
ev_code Event code
state Muted-state, see below
oid OutBox ID of last OutBox push
uid User that gave the last instrucion (mute/un-mute)
time Object update epoch

state

State Description
querying QED sent, waiting response. Code is in process of being muted
muting Got QED response, SEDxxS sent. Code is in process of being muted
muted Got confirmation of SEDzzS. Code is muted.
un-muting SEDxx-restore sent. Code is in process of being un-muted
un-muted Got response to SEDxx-restore. Code is un-muted. This state is is equivalent as not having the muted-event returned on the muted-events object. This is state is temporal, yields to object being eliminated.
ev-undefined Tried silencing an undefined event. This is state is temporal, yields to object being eliminated.

POST

POST api/device-mute/460001331053605

{
  "code": 1,
  "action": "mute"
}
{
  "action": "mute",
  "imei": 350000000000001,
  "code": 1,
  "events": {
    "evc-1": {
      "state": "querying",
      "oid": 42,
      "ev_code": 1,
      "uid": 1,
      "time": 1520868125.9707451
    }
  }
}

POST Params

Params type description
action string mute or un-mute
code number numeric event code

Returns

Param Description
action action
code code
imei device imei
events the same object returned by GET /device-mute/

Remote Control

The remote control API is used for editing the parameters of managed configurations, managed configurations are limited in the amount of editable parameters that can be edited, whereas the device control configurations are much more flexible in the definition and execution of commands.

Methods

View a list of remote commands to interact with a vehicle’s device

GET api/vehicles/197/remote

{
  "fwupdate": {
    "POST": []
  },
  "configuration": {
    "POST": [
      "ky"
    ]
  },
  "console": {
    "POST": [
      "cmd"
    ],
    "GET": [
      "cid"
    ]
  }
  ...
}

In order to view a vehicle’s remote control commands you can head over to the api/vehicles/:vid/remote API

The response to this request gives you a list of commands and the method used to access each command, along with any parameters if needed.

Commands Method Params Description
call POST index Call an authorized number
configuration POST ky Send a managed configuration
console GET cid View the response of a command sent
console POST cmd Send a command to a unit
diagnostic GET Quick connect the unit to the diagnostic server
ecu_state GET View the status of the ECU Monitor parameters
fwupdate GET Firmware update to the latest stable version
gps_status POST Get the device’s GPS diagnostic information
location GET Get the last location with gps diagnostic info
location2 GET Get the last location, no event is generated
location2 POST Get the last location, no event is generated
mdt POST message Send a message via the MDT
output POST otype, out, state Set the device’s output
outputsetlog GET View a list of the output commands sent
phones DELETE phone Delete an authorized number
phones GET View a list of the authorized phone numbers
phones POST phone Authorize a phone number on the device
rpm GET Get the current rpm limit configuration
rpm POST rpm, persistencesecs Set the RPM threshold that generates an ‘over rpm’ event
safe_immo POST action Send a Safe Immobilization to the device
sms_alias GET View the SMS alias that are configured
sms_alias POST smsaliases Create a new SMS alias
sms_alias PUT alias, action Update an SMS alias
speed GET View the current speed limit threshold
speed POST mph, persistencesecs Set the speed limit threshold
state GET Get the status of the device’s inputs and outputs
tracking_resolution GET View the current configuration of the tracking resolution
tracking_resolution POST resolution Set a new tracking resolution for the device
trigger_position_event POST Query the location and generate an event

In order to perform GET remote requests you need 'read’ permission on remote scope, and POST methods require write permission on remote scope.

Make a Call

Authorize phone number +13058675309

POST https://pegasus1.pegasusgateway.com/api/vehicles/1956/remote/phones

{
    "phone":"+13058675309"
}

Response

{
    "msg": "instruction set to device. ",
    "imei": 357042062920955,
    "oids": [
        48
    ]
}

View the phone number we just configured

GET https://pegasus1.pegasusgateway.com/api/vehicles/1956/remote/phones

{
    "phones": [
        {
            "action": "1",
            "access": "0",
            "phone": "+13058675309"
        }
    ],
    "errors": [],
    "pending": true
}

Make a call to the number +13058675309

POST https://pegasus1.pegasusgateway.com/api/vehicles/1956/remote/call

{
    "index": 0
}

This section describes how to generate calls directly from the device (this is unlike the trigger’s phone call generation because this is directly from the device, triggers uses a third-party api in order to make the call). Note that in order for your device to be able to make a phone call the SIM card has to be provisioned with voice services.

Start by authorizing a phone number on one of the 5 available slots for every device. (index 10-14)

POST /api/vehicles/:vid/remote/phones

or

POST /api/devices/:imei/remote/phones

{
  "phone":"+13058675309"
}

then make a call to that number with the remote method call

POST /api/vehicles/:vid/remote/call

{
  "index": 0
}

Note that the indexes must be between 0 and 4.

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Change configuration

Set the configuration with ky: q118 Syrus Bluetooth TAG for Developers V1

POST https://pegasus1.pegasusgateway.com/api/vehicles/1956/remote/configuration

{
  "ky": "q118"
}

To set a legacy or managed configuration simply choose a ky from the api/configurations response which corresponds to the managed configuration you want to set.

 
 
 
 
 
 
 
 
 
 
 
 

Send any device command

Restart the device (>SRT< command)

POST /api/devices/:imei/remote/console

{
    "cmd": ">SRT<"
}

Response

{
    "msg": "instruction set to device. ",
    "imei": 357042062922183,
    "via": "outbox",
    "cid": 981,
    "oids": [
        981
    ]
}

See commands in queue (devoutbox api)

api/devoutbox?imei=:imei

Shows us there’s two commands in queue

{
    "queue": [
        {
            "useky": true,
            "_last_try": 1505466920.614913,
            "_tries": 183,
            "state": false,
            "ctype": "setoutput",
            "otype": "e",
            "time": 1505426401.141027,
            "msg": "SSSXE40",
            "id": 980,
            "out": 4
        },
        {
            "msg": "SRT",
            "id": 981,
            "ctype": "consolecmd",
            "time": 1505712766.7529349
        }
    ],
    "outbox": {
        "_epoch": 1505712766.752985,
        "last_id": 982
    }
}

See the device’s commands history (once it’s successfully received the command)

api/commandhistory?imei=:imei

[
    ...
    {
        "cid": 981,
        "epoch": 1505712766.806,
        "user": "root",
        "msg": ">SRT",
        "type": "apiset",
        "pending": true
    }
]

Sending a device command can be done with the api/devices/:imei/remote/console api, with the cmd parameter where you put the command you want to send.

In order to see the response you have to make a GET to the devoutbox api, with the IMEI and/or command_id

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Immobilize a vehicle

Legacy safeimmo activation

POST api/vehicles/:vid/remote/safe_immo

or

POST api/devices/:imei/remote/safe_immo

{
  "action": true
}

response

{
    "msg": "instruction set to device. ",
    "imei": 356612022409637,
    "response": null,
    "oids": [
        166
    ]
}

you can monitor the state of the immobilization via API or Websockets

GET api/vehicles/:vid/remote/state

{
    "ionames": {
        "io_pwr": "pwr",
        "io_in1": "in #1",
        "io_out1": "Engine Cut",
        "io_out2": "Output #2",
        "io_ign": "ign",
        "io_in2": "in #2",
        "io_in3": "in #3"
    },
    "ios": {
        "io_pwr": true,
        "evid": 19711112435180,
        "io_in1": false,
        "evtime": 1505711767,
        "io_exp_state": false,
        "io_out1": false,   <<<<<<<<<<<<<<<<<<<<<
        "io_out2": false,
        "systime": 1505711770.180109,
        "trip_id": 19711108701981,
        "io_ign": true,
        "io_in2": false,
        "io_in3": false
    }
}

Syrus devices have a immobilization mechanism that waits for certain conditions to meet before activating, in this way the immobilization is “secure”. We’ll refer to immobilization as 'safeimmo’ from now on.

The first step in knowing whether or not safeimmo is supported by a particular device is to look at the device’s configuration, if it’s using a managed (legacy) configuration then you can look at the device’s api response in the config object,

api/devices/:imei?select=config

there’s a boolean in this response that tells you if the configuration supports safeimmo.

After you send the command you can monitor the response via api or via websockets, the api/devices/:imei/remote/state will give you the state of the safeimmo status. Safe immobilization is complete when the key io_out1 is set to true.

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Activate output 2

Activating embedded output 2 on vehicle 2063

POST api/vehicles/2063/remote/output

{
    "otype": "n",
    "out": 2,
    "state": true
}

Deactivating embedded output 1 on vehicle 2063

POST api/vehicles/2063/remote/output

{
    "otype": "n",
    "out": 1,
    "state": false
}

State of output

GET api/vehicles/:vid/remote/state

{
    "ionames": {...},
    "ios": {
        "io_pwr": true,
        "evid": 19711112435180,
        "io_in1": false,
        "evtime": 1505711767,
        "io_exp_state": false,
        "io_out1": false,
        "io_out2": false,        <<<<<<<<<<<<<<<<<<<
        "systime": 1505711770.180109,
        "trip_id": 19711108701981,
        "io_ign": true,
        "io_in2": false,
        "io_in3": false
    }
}

Activating output 2 is done with the /api/vehicles/:vid/remote/output api, making a POST request with otype, out, state as parameters.

If using an IO expander accessory check out this section.

Param Type Description
otype String Use device embedded output: “n”, or external IO Expander accessory: “e”
out Number Output number
state Boolean True to activate output (when an output is activated it’s grounded)

Device Control

The Device Control API gives you the ability to send commands to a device and build your own scripts.

Everything starts with creating your own API definitions.

Intro

Viewing model & configuration definitions

Model with an instruction that tells the device to restart itself

Model: syrus.core.restart.model

GET api/dcontrol/definition/syrus.core.restart.model

{
  "tag": "syrus.core.restart.model",
  "type": "simple",
  "cmds": [
    ">SRT<"
  ]
}

Model with multiple instructions (commands) for the device

Model: syrus.standard.hour_report.model

GET api/dcontrol/definition/syrus.standard.hour_report.model

{
  "tag": "syrus.standard.hour_report.model",
  "type": "simple",
  "cmds": [
    ">SGC00TR03600<",
    ">SED00NV0;C00+<"
  ]
}

Configuration definition with the two models above

Configuration: syrus.standard.testing.config

GET api/dcontrol/definition/syrus.standard.testing.config

{
  "name": "Sample Config",
  "allowedConsoleCmds": [],
  "models": [
    "syrus.core.restart.model",
    "syrus.standard.custom_periodic_reporting.model"
  ],
  "evLabels": {},
  "tag": "syrus.standard.testing.config",
  "ky": "a1kt",
  "description": "Syrus Sample Config for use in docs"
}

The Device Control API is made up of definitions.
A definition is an API, which you can define, that holds the device commands used to configure the unit. It’s also used to reference which commands can be sent to the device.

There are two types of definitions, Models and Configurations.

Models are definitions that have the actual device commands, while Configurations are a collection of models.

A device is configured with one Configuration at a time, this configuration can have any number of models defined.

To simplify this, imagine you’re working with the standard device configuration, you can think of models as the commands needed to execute an event. For example, almost all configurations have a tracking resolution, which is an event that’s used to define how often the device reports when the ignition is ON, you can have a model called standard_tracking_resolution with editable parameters that define the time & heading between reports, or you can make your own model standard_tracking_resolution_with_distance that includes a new parameter for defining a distance between reports.

Note that all Models definitions API end with .model while Configurations definitions API ends with .config. So when we defined the earlier models, they should actually be named: standard_tracking_resolution.model and standard_tracking_resolution_with_distance.model.

Finally, remember that in order to send a command to the unit it MUST exist in that device’s configuration.
In other words, if you want to send a command that calibrates the accelerometers movement (>SXAICAR1<) for example, the model that accomplish this must be included in the device’s configuration .config.

Applications and Uses

The Device API has many applications and can be used a number of ways, while there’s no right or wrong way to use it we do encourage you to stick with the following.

Models

Configurations

Things to Consider

The Device Control API has lots of benefits and features, some of the more notable benefits are:

however there are some things that you need to keep in mind:

Permissions

GET api/dcontrol/access

{
  "edit": [
    "pegasus.*",
    "syrus.*"
  ],
  "create": [
    "pegasus.*",
    "syrus.*"
  ],
  "delete": null,
  "view": [
    "pegasus.*",
    "syrus.*"
  ]
}

The last thing you need to know before you get started creating your first definitions is that you need to have access to create them. By default you’re only allowed access to create models whose name start with the list found here: api/dcontrol/access

The response to this API will tell you what the name of the definitions you’re able to edit, create, view, and delete start with.

For example,

  "edit": [
    "pegasus.*",
    "syrus.*"
  ],

means you can edit definitions that start with the word pegasus. and syrus.

Definitions

View

View all definitions

GET api/dcontrol/definitions

[
  "syrus.core.restart.model",
  "pegasus.test.all.config",
  "pegasus.lr.standard.config",
  "syrus.list.geofences.circular.model",
  ...
]

View definitions that start with ‘syrus.core’

GET api/dcontrol/definitions?name=syrus.core.*

[
  "syrus.core.restart.model",
  "syrus.core.baud_rate.model"
]

To view the definitions you can make a GET request to api/dcontrol/definitions The definitions resource accepts a URL param called name which lets you filter the definitions using a regular expression.

Create

Creating a new definition

{
  "dryRun": false,
  "definition": {
    ...
    insert model or configuration params here
    ...
  }
}

In order to create a model or configuration definition, we need to make a POST request to api/dcontrol/definition with the following two parameters dryRun and definition.

Parameter Description Type
dryRun true if you want to test the request Boolean
definition The actual definition, model or configuration Object

Models

View

View all models

api/dcontrol/definitions?name=*.model

[
  "syrus.core.gps.filter.model",
  "syrus.acc.ecu.vin.model",
  "pegasus.standard.harsh_accel_braking.model",
  "pegasus.standard.position_request.model",
  ...
]

View all models that contain the word 'gps’

api/dcontrol/definitions?name=.gps.model

[
  "syrus.core.gps.filter.model",
  "pegasus.standard.no_gps.model",
  "syrus.core.gps.filter.copy.model",
  "pegasus.standard.no_gps.copy.model"
]

To view all the models you have access to, you can make a GET request to the api/dcontrol/definitions resource, with a URL param filter called: name, where you can pass it a regexp that matches the definition you’re looking for, in this case we can use name=.*.config to refer to all definitions

Particular Model

View a particular model

api/dcontrol/definition/syrus.acc.ecu.vin.model

{
  "name": "VIN Number",
  "description": "Get the Vehicle's VIN",
  "tag": "syrus.acc.ecu.vin.model",
  "type": "simple",
  "cmds": [
    ">QXAZV<"
  ]
}

Get tracking with Ignition ON model

api/dcontrol/definition/pegasus.standard.tracking.ignition.on.model

{
  "name": "Tracking Resolution",
  "description": "Periodic reports while the ignition is ON."
  "tag": "pegasus.standard.tracking.ignition.on.model",
  "paramsDefs": {
    "min_time": {
      "units": "seconds",
      "range": [
        5,
        86400
      ],
      "type": "number",
      "label": "Minimum time between events"
    },
    "heading": {
      "units": "degrees",
      "range": [
        5,
        120
      ],
      "type": "number",
      "label": "Heading in degrees"
    },
    "max_time": {
      "units": "seconds",
      "range": [
        5,
        86400
      ],
      "type": "number",
      "label": "Maximum time between events"
    }
  },
  "initialValues": {
    "min_time": 10,
    "heading": 45,
    "max_time": 180
  },
  "type": "simple",
  "cmds": [
    ">SXAGH001{{params.heading|fix 3}}<",
    ">SED97SV0;F00+;ACT=SGC01TR{{params.max_time}};ACT=SGC19TC{{params.min_time |fix 5}}<",
    ">SED95SV0;J00F00&+;ACT=SGC01TR{{params.max_time |fix 5}}<",
    ">SED01NA0;C01J00|C19&+;XCT=SGC19TC{{params.min_time |fix 5}}<",
    ">SED82SV0;F00!+;ACT=SGC01U<"
  ]
}

To see a particular model you can make a request to the api/dcontrol/definition resource.

Response

Param Description Type
name Name of the Model String
description Descriptive text for the model String
tag Short name of the model String
paramDefs Parameters for the model Object
initialValues Initial values using the parameters of the model Object
cmds Programming commands for the Syrus Array
evLabels Event Labels for the model Object
keywords Short codes that can be used to group similar models Array


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Create

Create a simple model for restarting the device

POST api/dcontrol/definition/syrus.core.restart.model

{
  "dryRun": false,
  "definition": {
    "name": "Restart",
    "description": "Restart device",
    "type": "simple",
    "cmds": [
      ">SRT<"
    ],
    "keywords": [
      "core"
    ]
  }
}

Create a ulist model for creating circular regions

POST api/dcontrol/definition/syrus.list.regions.circular.model

{
  "dryRun": false,
  "definition": {
    "name": "Circular Regions",
    "description": "Create circular regions on the device",
    "type": "ulist",
    "initialValues": {
      "0": {
        "radius": 50
      }
    },
    "ulistRange": [
      0,
      99
    ],
    "paramsDefs": {
      "radius": {
        "type": "number",
        "range": [
          50,
          65000
        ]
      }
    },
    "cmds": [
      ">SXAIR{{uindex|fix 2}}{{uparams.radius|fix 6}}<"
    ],
    "keywords": [
      "list"
    ]
  }
}

In order to create a model you have to make a request to the
api/dcontrol/definition/modelname.model
where modelname is the unique name you want to give to your model.

POST Body

Simple Model

Parameter Description Type Required
name Name of the model String
type Type of model (simple) String yes
cmds Syrus commands Array yes
paramsDefs Parameters for model Object
initialValues Initial values for model Object
evLabels Labels for the event generated Object
keywords Shortcodes that can be used to group similar models Array

UList Model

Parameter Description Type Required
name Name of the model String
type Type of model (ulist) String yes
cmds Syrus commands Array yes
paramsDefs Parameter definitions for the model Object
initialValues Initial values for model Object
ulistRange List range Array yes
ulistUnsetCmdUIndex Index location to Undefine command Integer yes
keywords Short codes that can be used to group similar models Array

Parameter Definitions

There are 3 main types of paramDefs in a simple model:

When making these paramDefs you’re able to define the following additional parameters

Parameter Description Type
type Parameter type: number, text, boolean String
range Range of numbers Array
list List of items (number & text types) Array
labels Short description String
units Units for parameter String

Number

Create a model for setting the camera resolution

POST api/dcontrol/definition/syrus.acc.photocam.resolution.model

{
  "dryRun": false,
  "definition": {
    "name": "Camera Resolution",
    "description": "Set the camera resolution",
    "type": "simple",
    "initialValues": {
        "resolution": 2
    },
    "paramsDefs": {
      "resolution": {
        "type": "number",
        "range": [
            1,
            3
        ]
      }
    },
    "cmds": [
      ">SXASCM20{{params.resolution}}<"
    ]
  }
}

Create a model that defines a periodic report on the device. Notice how the cmds have a filter called ’fix’ that adds a padding to the number

POST api/dcontrol/definition/pegasus.standard.periodic_report.ign_off.model

{
  "dryRun": false,
  "definition": {
    "keywords": [
      "events",
      "common",
      "ios"
    ],
    "paramsDefs": {
      "time": {
        "units": "seconds",
        "range": [
          5,
          86400
        ],
        "type": "number",
        "label": "Periodic report with ignition off"
      }
    },
    "name": "Events - Periodic Report with Ignition Off",
    "initialValues": {
      "time": 7200
    },
    "cmds": [
      ">SGC00TR{{params.time|fix 5}}<",
      ">SED00NA0;C00+<",
      ">SED98SV0;F00-;ACT=SGC00TR{{params.time|fix 5}}<",
      ">SED99SV0;F00+;ACT=SGC00U<"
    ],
    "type": "simple",
    "description": "Reports with the ignition Off"
  }
}

Create a model for setting the device baud rate

POST api/dcontrol/definition/syrus.core.baud_rate.model

{
  "dryRun": false,
  "definition": {
    "name": "Baud Rate",
    "description": "Set the baud rate",
    "type": "simple",
    "initialValues": {
        "baud_rate": 9600
    },
    "paramsDefs": {
      "baud_rate": {
        "type": "number",
        "list": [
            9600,
            115200
        ]
      }
    },
    "cmds": [
      ">SXABR{{params.baud_rate}}<"
    ]
  }
}
Range of Numbers
Parameter Description Type
type number String
range Range of numbers (min, max) Array
labels Short description String
units Units for parameter String

When working with a range you can specify a filter on the cmds that will fill the values according to how many digits the device accepts for that parameter.

List of Numbers
Parameter Description Type
type number String
list List of numbers Array
labels Short description String
units Units for parameter String

The number type parameter definition can be used for creating a variable on the Syrus command that accepts a numeric value.

For example, the command to change the photocam accessory resolution is: >SXASCM20#< where # refers to a number between 1 - 3 which corresponds to the photo resolution

we can make a model that can accept a variable called: resolution that accepts a number between 1 - 3 that corresponds to this resolution. We can pass the parameter a range or list of numbers with the range and list parameters.

Text

Create a model for setting the device extended tags

POST api/dcontrol/definition/pegasus.standard.extended_tags.model

{
  "dryRun": false,
  "definition": {
    "name": "Extended Tags",
    "description": "Parameters reported on standard configuration",
    "type": "simple",
    "initialValues": {
      "signals": "AC;AL;BL;CF;DOP;IX;JO;SV;VO;CL;CE;CS;CR;TI"
    },
    "paramsDefs": {
      "signals": {
        "type": "text"
      }
    },
    "cmds": [
      ">SXAEFA;{{params.signals}}<"
    ]
  }
}

The text type parameter definition can be used for creating a variable that accepts any string value. This is useful for commands where you have to write something such as the extended tags or parameters you want reported in the events.

Numberbool

Create a model for controlling the 1-wire accessories

POST api/dcontrol/definition/syrus.core.one_wire_management.model

{
  "dryRun": false,
  "definition": {
    "name": "One Wire Management",
    "description": "One wire accessory management",
    "paramsDefs": {
      "ibutton": {
        "type": "numberbool",
        "label": "Enable iButton"
      },
      "io_expander": {
        "type": "numberbool",
        "label": "Enable IO Expander"
      },
      "ecu_monitor": {
        "type": "numberbool",
        "label": "Enable ECU Monitor"
      },
      "temperature": {
        "type": "numberbool",
        "label": "Enable Temperature Sensor"
      }
    },
    "initialValues": {
      "io_expander": true,
      "ecu_monitor": true,
      "ibutton": true,
      "temperature": false
    },
    "type": "simple",
    "cmds": [
      ">SXAWA{{params.ibutton}}{{params.io_expander}}{{params.ecu_monitor}}{{params.temperature}}0000<"
    ]
  }
}

The numberbool type is used for setting 1 and 0 values using true and false. Note that the 1 and 0 values can be obtained with the number type but as you will see in the example it makes more sense (and it’s more legible) to assign a boolean value (true/false) rather than 1 or 0.


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Update

Updating the tracking with Ignition ON model to include distance

PUT api/dcontrol/definition/pegasus.standard.tracking.ignition.on.model

{
  "name": "Tracking Resolution",
  "description": "Periodic reports while the ignition is ON with Distance parameter."
  "tag": "pegasus.standard.tracking.ignition.on.model",
  "paramsDefs": {
    "min_time": {
      "units": "seconds",
      "range": [
        5,
        86400
      ],
      "type": "number",
      "label": "Minimum time between events"
    },
    "heading": {
      "units": "degrees",
      "range": [
        5,
        120
      ],
      "type": "number",
      "label": "Heading in degrees"
    },
    "max_time": {
      "units": "seconds",
      "range": [
        5,
        86400
      ],
      "type": "number",
      "label": "Maximum time between events"
    },
    "distance": {
      "type": "number",
      "range": [
        100,
        99999
      ],
      "units": "meters",
      "label": "Distance between reports"
    }
  },
  "initialValues": {
    "min_time": 10,
    "heading": 45,
    "max_time": 180,
    "distance": 1000
  },
  "type": "simple",
  "cmds": [
    ">SXAGH001{{params.heading|fix 3}}<",
    ">SED97SV0;F00+;ACT=SGC01TR{{params.max_time |fix 5}};ACT=SGC19TC{{params.min_time |fix 5}};ACT=SGC18DR{{params.distance |fix 5}}<",
    ">SED95SV0;J00F00&+;ACT=SGC01TR{{params.max_time |fix 5}}<",
    ">SED01NA0;C01J00|C18|C19&+;XCT=SGC19TC{{params.min_time |fix 5}}<",
    ">SED82SV0;F00!+;ACT=SGC01U<"
  ]
}

To update a model you simply make a PUT request to the API endpoint for that model passing all the parameters of the definition in the request.


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Execute

Execute the commands in a model for a device (Single command or multiple command example)

PUT api/dcontrol/device/:imei/model/:model_with_commands

no payload

This will execute the command >SRT< for the device


 

Execute the commands in a model with a single parameter for a device

PUT api/dcontrol/device/:imei/model/:model_with_parameters

{
  "execValues": {
    "resolution": 3
  }
}

Execute the commands in a model with multiple parameters

PUT api/dcontrol/device/:imei/model/:model_with_mult_parameters

{
  "execValues": {
    "heading": 45,
    "time": 60
  }
}

Another example of executing commands for a model

POST api/dcontrol/definition/syrus.core.one_wire_management.model

{
  "execValues": {
    "io_expander": false,
    "ecu_monitor": false,
    "ibutton": false,
    "temperature": true
  }
}

To execute the commands in a model you make a PUT request to the Model API endpoint. If the model has no parameters you can simply make a PUT request with no payload to execute it.

If the model has parameters look at it’s definition to see how they are executed, your best bet is to look at the initialValues object and send this.

Finally, to execute the parameters you have to send it in an object called execValues.


  "execValues": {
    "command": value
  }
}

Delete

In order to delete a model definition you can make a DELETE request to the definitions URI.

Configurations

Remember that a Configuration is a collection of models, and models are the instructions that the device uses to program itself to report and behave how you want it to. In this section we look at how to interact with API definitions that end with .config

View all

View all configurations

api/dcontrol/definitions?name=*.config

[
  "pegasus.standard.config",
  "pegasus.standard.photocam.config",
  "pegasus.standard.high_reporting.config",
  "pegasus.test.all.config"
]

View all configurations that start with 'pegasus.standard’

api/dcontrol/definitions?name=pegasus.standard.*.config

[
  "pegasus.standard.config",
  "pegasus.standard.photocam.config",
  "pegasus.standard.high_reporting.config"
]

To view all the configurations you have access to, you can make a GET request to the api/dcontrol/definitions resource, with a URL param filter called: name, where you can pass it a regexp that matches the definition you’re looking for, in this case we can use name=*.config to refer to all definitions

View one

View a particular configuration

api/dcontrol/definition/pegasus.standard.config

{
  "name": "Pegasus Standard Test All Models Config",
  "description": "Configuration to test all possible models",
  "allowedConsoleCmds": [],
  "evLabels": {},
  "models": [ ... ],
  "tag": "pegasus.test.all.config",
  "ky": "a3m8"
}

To see a particular configuration you can make a request to the api/dcontrol/config_definition.config resource.

Response

Param Description Type
name Name of the Configuration String
description Descriptive text for configuration String
allowedConsoleCmds Which commands are allowed via the device console Array
evLabels Required, for now you can use an empty object {} Object
models Names of models the configuration uses Array
tag Short name of the configuration String
ky Unique shortcode that allows synchronization with the device String


 

 

 

 

 

 

 

 

 

Create

Create a standard custom configuration

POST api/dcontrol/definition/pegasus.standard_custom.config

{
  "dryRun": false,
  "definition": {
    "name": "Sample Config",
    "description": "An example of creating a configuration",
    "allowedConsoleCmds": [],
    "models": [
      "syrus.core.restart.model",
      "pegasus.standard.ignition_events.model",
      "pegasus.standard.periodic_report.model"
    ],
    "evLabels": {}
  }
}

In order to create a configuration you need to make a POST request with the name of the configuration as part of the URI, the body of the request will use the parameters mentioned above.

Param Description Type
name Name of the Configuration String
description Descriptive text for configuration String
allowedConsoleCmds Which commands are allowed via the device console Array
evLabels Required, for now you can use an empty object {} Object
models Names of models the configuration uses Array
keywords Short codes that can be used to group similar configurations Array


 

 

Update

Add another model to a configuration

PUT api/dcontrol/definition/syrus.standard_custom.config

{
  "dryRun": false,
  "definition": {
    "name": "Sample Config",
    "description": "An example of creating a configuration",
    "allowedConsoleCmds": [],
    "models": [
      "syrus.core.restart.model",
      "pegasus.standard.ignition_events.model",
      "pegasus.standard.periodic_report.model",
      "syrus.list.geofences.circular.model"
    ],
    "evLabels": {}
  }
}

Updating a configuration requires that you make a PUT request to the api/dcontrol/definition/configuration_name.config When doing this it will update the configuration across all devices that share this configuration.


 

 

 

 

 

 

 

 

Execute

Send a configuration to a device

PUT api/dcontrol/device/:imei/config

{
  "configName" : "pegasus.syrus_standard.config",
  "overwriteConfig" : true
}

This will set the configuration named: pegasus.syrus_standard.config to the device


 

To set the configuration for a device you make a PUT request to the api/dcontrol/device/:imei/config. This method accepts 2 parameters, configName and overwriteConfig.

parameter type description
configName string config api endpoint pegasus.syrus_standard.config
overwriteConfig boolean true if you want to overwrite the device’s current configuration (default)

Delete

In order to delete a configuration definition you can make a DELETE request to the definitions URI.

Forwarders

For examples please look at the PHP tab

Forwarders are realtime redirections of data to an endpoint. They are useful when you want to obtain all the data from one group or your entire fleet and optionally store it in a database.
The biggest difference between a forwarder and live communication via websockets is that the forwarder requires a confirmation that the message was received by the endpoint, so there’s an active queue that makes sure all data is sent.

Pegasus supports forwarding of data in an array of JSON objects to an endpoint.

The way it works is that you define a URL (endpoint) that’s going to be used as a receiver for HTTP POST requests sent from Pegasus. The data Pegasus sends is an array of JSON objects that correspond to the different events generated by the devices in real time.

Pegasus forwards

[{"lat": 25.23432, "lon": -80.24912, "id":10001},{"lat": 25.23435, "lon": -80.24913, "id":10002}]

The forwarder service expects the endpoint to ‘confirm’ the reception of the message Pegasus sends.

In order to confirm the reception of all events successfully, you can respond with an empty array []

Response from client

[]

Should there be any events that we sent in the forward that you did not process correctly in your database you can reply with the ID of the event that was not processed

[10002]

and Pegasus forwards that event again

[{"lat": 25.23435, "lon": -80.24913, "id":10002}]

Requirements

In order for Pegasus to forward data to your endpoint you must allow HTTP traffic to a path in your server where the code will reside.
Check to make sure there are no firewall restrictions and the site is reachable by an external application.

Fields forwarded

By default the fields that are forwarded are the one’s found in the Master Fields List.

Depending on what accessories the device has connected, the fields will be sent accordingly. In other words only a device with an ECU Monitor accessory connected will report ecu_ related fields, otherwise these fields will not be forwarded in the POST request.

Editable Parameters

Dates The default format for sending Date fields are ISOFORMAT (YYYY-MM-DDThh:mm:ssTZD), but you may choose to edit this to any format.

Time Zone The default time zone is UTC (recommended), but you are able to adjust the timestamp fields to any timezone.

Headers The default header is: Content-Type: application/json, but you are able to add any header to the forwarder.

Fields We could customize the forwarder to send only the fields you request, see limiting the data for more info.

Vehicle Info You can request to include the vehicle’s information along with every event, see adding vehicle data

Event Types The following are event types that can be forwarded

Type Description Included
10 EV TAIP regular events (GPS Type) Default
11 PV TAIP position & velocity (GPS Type)
13 GPS BackLog (GPS Type)
20 empty GPS Event (gps time = 0)
100 Keep-alive (Connection Type)
110 XART TAIP (Connection Type)
111 XARS SIM Card Operator Info (Connection Type)
150 Message
301 Duplicate GPS Event (Other Type)

Limiting the data

Since there’s so many fields that are sent by default, you may choose to limit what fields you receive, when making the request for a new forwarder just specify which keys you’d like to exclude

{   "keys_exclude": [     "source",     "age",     "hdop",     "sv"   ] }

This will exclude the GPS related keys from the forwarder.

Updating a forwarder

Changing the date format

PUT /api/forwarders/:id

{
  "forward_gps_events": true,
  "include_evname": "",
  "__updated": 1533241097.1656611,
  "dates_format": "%Y-%m-%d %H:%M:%S",
  "protocol": "FWD:json_fwd",
  "MAX_MESS_PER_CALL": 50,
  "forward_other_eventtypes_csv": "",
  "groups_filter": [],
  "resource": "https://testserver.com/receiver/fwd_test",
  "include_vinfo": false,
  "time_zone": "America/New_York",
  "INBOX_DB_DUMP_AT": 766080,
  "general": {},
  "forward_conn_events": false,
  "vehicle_count": 2128,
  "id": 109,
  "extra_headers": {},
  "port": null
}

this gives you dates with: YYYY-MM-DD hh:mm:ss, example: 2018-12-25 23:59:59

for more info visit datetime


Changing the forwarder timezone

PUT /api/forwarders/:id

{
  "forward_gps_events": true,
  "include_evname": "",
  "__updated": 1533241097.1656611,
  "dates_format": "ISOFORMAT",
  "protocol": "FWD:json_fwd",
  "MAX_MESS_PER_CALL": 50,
  "forward_other_eventtypes_csv": "",
  "groups_filter": [],
  "resource": "https://testserver.com/receiver/fwd_test",
  "include_vinfo": false,
  "time_zone": "UTC",
  "INBOX_DB_DUMP_AT": 766080,
  "general": {},
  "forward_conn_events": false,
  "vehicle_count": 2128,
  "id": 109,
  "extra_headers": {},
  "port": null
}

Adding additional keys

PUT /api/forwarders/:id

{
  "forward_gps_events": true,
  "include_evname": "",
  "__updated": 1533241097.1656611,
  "dates_format": "ISOFORMAT",
  "protocol": "FWD:json_fwd",
  "MAX_MESS_PER_CALL": 50,
  "forward_other_eventtypes_csv": "",
  "groups_filter": [],
  "resource": "https://testserver.com/receiver/fwd_test",
  "include_vinfo": false,
  "time_zone": "America/New_York",
  "INBOX_DB_DUMP_AT": 766080,
  "general": {
    "keys_include": [
      "btt_wreason",
      "tec_fn",
      "ecu_speed"
    ]
  },
  "forward_conn_events": false,
  "vehicle_count": 2128,
  "id": 109,
  "extra_headers": {},
  "port": null
}

Adding additional headers

PUT /api/forwarders/:id

{
  "forward_gps_events": true,
  "include_evname": "",
  "__updated": 1533241097.1656611,
  "dates_format": "ISOFORMAT",
  "protocol": "FWD:json_fwd",
  "MAX_MESS_PER_CALL": 50,
  "forward_other_eventtypes_csv": "",
  "groups_filter": [],
  "resource": "https://testserver.com/receiver/fwd_test",
  "include_vinfo": false,
  "time_zone": "America/New_York",
  "INBOX_DB_DUMP_AT": 766080,
  "general": {},
  "forward_conn_events": false,
  "vehicle_count": 2128,
  "id": 109,
  "extra_headers": {
    "Authorization": "Bearer YWRqZmFsZGpmbGFqc2RmbGFhZGxmam"
  },
  "port": null
}

To update a forwarder, you can use a PUT request on the forwarder ID to update the general configuration. When sending the request, make sure to use the entire JSON object as the body of the PUT request, with the modifications.

param type description
legacy boolean when true it sends the lat/lon as integers values
protocol string when set to “rpc”, it wraps the json array of events in the following envelope {“params”:[1,[…]],“method”:“pushevents”,“id”:1}
keys_include array use it to include keys that are not defined in the keys output
keys_exclude array use it to exclude any keys from the forwarder
codes_map json object with key-value pairs, the keys should be the original event_code, the value represents the value to which it will be switched
filter_in array only forwards events from these event codes
filter_out array removes any unwanted event codes from forwarding data
stop_send boolean when true it pauses the forwarder
stop_queue boolean when true it stops queuing events, therefore they are discarded
labels_in array only allows certain labels to forward data
labels_out array exclude the following labels from forwarding data
default_values json object with key-value pairs, the key is the field that you want to have a default value when the data is not present, value is the value you want to assign

Tutorials

PHP & phpMyAdmin

The following tutorial demonstrates how to handle the messages forwarded by the Pegasus Sites through PHP (version 5.3 or later).

Requirements - Running PHP Server - PHP Template : receiver examples in our repo - Moderate/Advanced knowledge of PHP and MySQL

Configuring the PHP template

Download and extract the PHP template receiver.zip into your servers desired path. You may rename the root directory (eg. receiver).

receiver.zip

- config.php - index.php - json.php - rpc.php - resources --- jsonRPCserver.php --- rpchandler.php

The root file must be allowed access from an url, such as http[s]://[YOURDOMAIN]/[PATH TO TEMPLATE]/ Open the ‘config.php’ file with your favorite text editor. Modify the constants to suit your PHP installation and Database access credentials.

date_default_timezone_set("America/New_York"); //Change to your desired timezone

define("DB_SERVER", "YOURDATABASE_SERVER");
define("DB_USER", "DATABSE_USER");
define("DB_PASS", "DATABASEP_PW");
define("DB_NAME", "DATABASE_NAME");
define('DB_TABLE_NAME', 'PEGASUS_TEST');

Once you have verified your Database credentials, remove/comment the first exit() statement within the ‘index.php’ file.

// in the index.php comment the following line
//exit()
define('PEGASUS_PROTOCOL', JSON);

If you do not want to store the data on to a database, you can disable it by setting the variable ‘$db_storage’ to false within the ‘config.php’ file. This will prevent the table from being created (if it hasnt been created already), and will prevent all new events from being inserted into the database.

//update to store in your DB
$db_store = true;

Note: This does not delete the table if it has been previously created, this only prevents the sql statement that creates the table from executing. Events Object data structure

In most cases, it may be may be suitable for the events object to be handled differently or in addition to the database storage mechanism discussed in the previous section. In this instance you may add your logic directly into the ‘pushevents’ function of the ‘rpchandler.php’ file. You can use the $events object at your discretion, and modify it to your will. The $events object is a PHP associative array which contains all the events sent from the pegasus gateway. You may add any logic here, which can include sending emails, forwarding the data to another script, or storing to a file. You must make sure that any errors are handled appropriately.

NOTE: It is important that you make sure your logic returns the value “ok” (string, lowecased). As this lets pegasus know that the events have been handled accordingly and the queue can be cleared.

Once done you can test the forward here: Testing the Forward

Video

Windows, .NET, Microsoft SQL

Download the following zip ms_receiver.zip

In the receiver.ashx there’s 3 places where you must input data

Line 50: Replace [dbo].[UNIT_EVENTS_RPC] with your Database Table Name

Line 105: Replace SERVERNAME with the name of your server

Line 106: Replace Pegasus_db with the name of your database

Please note that this solution uses: Windows Authentication Mode

Run the following in Microsoft SQL Server to create the DB. eventKeysMSSQL.sql

Make sure your Microsoft server has IIS, Active Directory services running and port binding correctly done DNS/DHCP services are optional but recommended.

Testing the forward

In order to simulate what Pegasus would send to your server/database you may use an application that sends HTTP requests, like POSTman, or cURL. Just use the URL with the path to your JSON listener and follow one of the examples on the right.

curl -X POST "http://yourlistener.com/path/to/receiver" \
-H "Content-Type: application/json" \
-d '[{"io_pwr": true, "ac": 2, "code": 1, "type": 10, "vid": 1392, "cf_lac": 103, "ip": "208.131.186.63", "port": 26052, "pid": 110, "al": 521, "vo": 6356212, "io_ign": true, "event_time": "2016-01-12T19:40:31+00:00", "source": 3, "lon": -77.32573, "io_exp_state": false, "id": 4348333385, "cv10": 580, "cv11": 0, "cv12": 268, "cv13": 0, "head": 315, "vdop": 83, "hdop": 97, "bl": 4394, "mph": 28, "valid_position": true, "lat": 18.08918, "pdop": 128, "device_id": 357666050758579, "system_time": "2016-01-12T19:40:32.799671+00:00", "cf_rssi": "10", "age": 2, "sv": 9, "io_out1": false, "io_out2": false, "io_in1": false, "io_in2": false, "io_in3": false}]'

Tips & Recommendations

Receiving data from multiple forwarders

If you are looking to receive data in your database from multiple forwarders, it is recommended that you create tables based on the PID field. This field corresponds to the Pegasus site ID, every forwarder received from different servers will have a unique PID per site.

Working with large data

When working with large data it is important to separate the database into manageable tables. For example, you could have a table for every 1 or 2 vehicles.

You may partition the vehicle tables per week or trimester. Every partition has a constraint over the Date column that way you only look over the table with the dates you’re looking for. This is especially important when you have to drop tables in the future.

Enabling a Forwarder on your site

In order to enable to create the forwarder please make sure you test with cURL or POSTman. After successfully testing you may request enabling your forwarder on your site using the following form: Submit Application

It takes approximately 8-24 hours to enable the application on your Gateway.

Live Communications

Pegasus supports live communications via web-sockets.

Web sockets allow you to subscribe to a variety of events generated from pegasus. As a developer you can catch these events, and bring some life to your applications.

Pegasus Live communications ease programming by pushing the events to you, the developer, removing the need for periodic requests.

All live communications are handled by the server https://live.pegasusgateway.com

You can go there to check a quick demo, once loaded use the JS console to see the payload of the devices.

Requirements

Pegasus’ Live communications uses socket.io as its backbone. We highly recommend you take a look at their website to get a deeper understanding of how websockets work, as well as their implementation. socket.io

In order to use the live functionality on your application. You need to download and run then socket.io client. Get the socket client

Emits

The live server emits some basic data, simply register some callbacks to the following handlers

socket.on('...', function(data){...})

Handler Description
_authenticated Authentication successful, sent when the live server has validaded your token with your gateway’s API. Includes output of resources handler.
_error Generic error message. Authentication not successful, missing permissinos, etc.
_update Generic update message. ex. ‘Listening to …’, or 'Stopped listenting to …’, etc.
resources Returns the resources you are allowed to register to. (vehicle ids, for vehicle events, triggers, etc.)
events Primary events entry point. All events you have registered to will come in through here.

You can also emit some messages, with data to the live server as soon as you connect.

Handler Description
authenticate Send source and auth token to inititate authentication with live server.
resources Request resources that are available to you.
listen subscribe to some or all entities for a given namespace
stop unsubscribe to some or all entities in a given namespace

Namespaces

All events generated by the Pegasus Gateway fall into namespaces. By understanding the namespaces in use, you can further tune your application to only the events you need. This allows for more specialized programming.

Currently the gateway manages the following Namespaces:

Namespace Description
jobs Job related events (running, error, finished, etc)
triggers Trigger fired, trigger disabled, etc.
vehicle-events events generated by the devices.
vehicle-nstat* deprecated on 1.9 changes in vehicle connectivity: ONLINE/OFFLINE state

Creating a socket


//intialize the socket
var socket = io('https://live.pegasusgateway.com/socket')

Once you have the socket.io client loaded, lets make a fresh socket by initializing it.

Authentication

// Set up basic handlers
socket.on('_authenticated', function(data){
    // this will fire when we are succesfully authenticated.
    // 'data' is equal to the output of /api/user/resources
    console.log(data)
})
socket.on('_error', function(message){
    console.error(message)
})
socket.on('_update', function(message){
    console.info(message)
})
socket.on('resources', function(resources){
    console.log(resources)
})
socket.on('events', function(envelope){
    console.log(envelope)
    namespace = envelope.namespace
    vehicle = envelope.object
    events = envelope.payload
})

var credentials = {
    pegasus: "https://pegaus1.pegasusgateway.com", // replace with your gateway.
    auth  : "aebf772e8aa25491ed273c699baf4d35aa5c4c0342cd7b51606bbf8c" // Retrieve the token by logging via /api/login
}

socket.emit("authenticate", credentials)

The first step in receiving events live from your Pegasus Gateway, is getting authenticated.

On successful authentication you’ll be returned with the api/user response.

Now that you’re authenticated you can subscribe to namespaces.

Listening

...

var envelope = {
    "namespace":"vehicle-events",
    "objects": 617, // [197,297] or "all"
}

socket.emit("listen", envelope)

In order to start listening to events, you must send an envelope via the listen message to the live server.

the evenlope must have the following properties.

Check the console for any error or info messages reporting the status of the operation. Remember that these were handled via the _error and _update callbacks.

If everything checks out you will start receiving envelopes from the vehicle-events namespace via the events message.

socket.on('events', function(envelope){ ... })

The envelope will contain the following properties :

Payload

The payload varies according to namespace.

vehicle-events

Received whenever a vehicle sends a tracking event.

The payload has a lot of keys, but the most important/relevant ones are:

device - contains information about the device, like connection/network status, trip info, state of the Inputs/Outputs

event - contains the values of the event keys reported

primary - info on the primary object/entity (vehicle, asset, etc)

secondary - info on the secondary object/entity (asset, bluetooth tag, etc)

updates - tells you what key updated (the event, or device, or both)

As mentioned above the primary and secondary keys correspond to the vehicle or asset that reported the value.
For example, when a driver (an asset) is identified via an iButton with the vehicle, the primary would be the vehicle, and secondary would be the asset. When the secondary_id is null it means that the secondary info shows the last active info. In other words, if the secondary_id shows a value it means the secondary is current, if there’s no value in secondary_id the secondary is the last known. So this would be useful for knowing if a vehicle currently has an asset assigned, if so, which one, and if not, which was the last asset assigned.

The payload keys and values are the same as the one’s you will expect when consulting via Rawdata

Please note that the same payload may be received twice, what you have to keep track of is the updates key, because it will tell you if it’s a device update such as a connection state change (from online to offline for example) or an event update, which means that a new event came in. On your applications you’ll want to show only when a new event came in, and handle the connection states when the device key is received.

Payload

Payload for vehicle-events

{
    "$$hashKey": "object:1229",
    "category": "vehicle",
    "device": {"ios_state": {}, "gpsknit": {}, "network": {}, "lastrx": {}, "trip_setup": {}, …},
    "event": {"code": 12, "gpsknit_prev_lat": 3257884, "sv": 8, "dev_dist__mi": 3899, "event_time": 1504909832, …},
    "pid": 1,
    "primary": {"info": {}, "associations": Array(3), "__updated": 1504110100.755031, "name": "Syrus 3 SIENNA", "trackers": Array(0), …},
    "primary_id": 686,
    "secondary_id": null,
    "type": "events",
    "updates": ["device"],
    "_pkey": "pka.05",
    "_site_url": "https://pegasus1.pegasusgateway.com",
    "_source": "pcore.listener",
    "_source_epoch": 1504910674.863004,
    "_ver_core": "1.9.0-rc1",
    "_ver_pcel": "2.1.1-r2"
}
Key Description
$$hashKey internal use
category event category (vehicle)
device information on the device more info
event event information reported by device
pid unique ID to the pegasus site
primary primary entity
primary_id primary entity id
secondary secondary entity
secondary_id secondary entity id
type type of payload
updates keys that are updated on this payload
_pkey internal use
_site_url pegasus site URL
_source internal use
_source_epoch internal use
_ver_core internal use
_ver_pcel internal use

Detailed payload description

device

asset

asset information

Key Description
aid asset id
aid_source source of the asset, ib for ibutton, btt for bluetooth tag, fp for fingerprint
btt_mac bluetooth tag mac address
ib ibutton HEX ID

config

configuration description

Key Description
ky unique key for managed or device control configuration
legacy_safeimmo_support true if it’s using managed configuration and it supports safe_immobilization on output 1

connection

connection state / information

Key Description
fno internal use
lid internal use
offline_reasons reason for the device to be offline
online true if device is online
pid site_id
reason reason why the connection is online (typically it’s a new connection)
seq internal use
_epoch epoch timestamp of last connection change

dcounters

device counters

for a detailed description you can check the counters description

gpsknit

gps information

Key Description
ack_id internal use
event_time__epoch epoch timestamp of the event time
lat latitude
lon longitude
no_gps_time_count time in seconds with no gps coordinates
no_location_count number of consecutive events with no gps
no_location_fepoch no location epoch timestamp
prev_ack_id internal use
prev_event_time__epoch previous event epoch timestamp
prev_lat previous latitude
prev_lon previous longitude
_epoch epoch timestamp

ios_state

state of the inputs and outputs

for a detailed description you can check the master field list

last_rx

last communication time

Key Description
msg_type type of message
value timestamp it reported that message type
_epoch timestamp it was received

latest

latest data reported by the device

Key Description
counters latest counters reported
data latest data reported, same keys as rawdata more info
ios latest ios reported
loc latest location information
prefix internal use
vcounters latest vehicle counters

legacy_safeimmo_state

current state of the safe immobilization

Key Description
cid command id
instruction current instruction
set_at epoch time it was set at
uid user id that set it
_epoch timestamp

legacy_set_out_state

current state of the outputs, useful for knowing if output is pending to be set/reset

Key Description
io_out[index] outputs 1-2 on device
io_exp_out[index] io expander output 1-4
cid command id
instruction current instruction
set_at epoch time it was set at
uid user id that set it

network

network information from device

Key Description
cnum carrier sim phone number (doesn’t always reflect the number of the sim card due to restrictions from some carriers)
imsi sim imsi
op operator
sim sim id
_epoch epoch timestamp

outbox

state of the device pending messages

Key Description
last_id last message id that was queued up
_epoch epoch timestamp

photos

state of the cameras connected to the device

Key Description
cams object with each camera’s event id
evid event id for photo captured
ncams number of cameras connected to device
_epoch timestamp the data was reported

trip

device trip information

Key Description
aid asset id associated to trip
dev_msgs internal use
groups id of the groups the vehicle belongs to during trip
id trip id
ky device configuration
method trip’s method (gps)
moving true if vehicle is currently on a trip, false means parked
signal internal use
src_id internal use
src_type internal use
start_evdistance distance traveled at the start of trip
start_lat start latitude
start_lon start longitude
start_time_epoch event time at start of trip
system_time_epoch system time at start of trip
vid vehicle id
_epoch epoch timestamp

trip setup

Key Description
method how the trip is formed
_epoch epoch timestamp

vcounters

user editable vehicle counters, for more information go to counters

vehicle

vehicle information

version

Key Description
device device model
extras firmware extra information
msg device message
number version firmware number

virtual distance

virtual distance calculated via lat lon deltas

Key Description
evtime_epoch time the event was generated
lat latitude
lon longitude
value distance for device
_epoch

event

list of event parameters reported by device, check out master field list for more info

vehicle-nstat *

Deprecated on 1.9 Received whenever a vehicle changes its ONLINE/OFFLINE status.

Payload keys:

You may receive other keys, they exist for testing, they may not exist on future releases.

Stopping

...

var envelope2 = {
    "namespace":"vehicle-events",
    "objects": "all", // [197,297] or 617
}

socket.emit("stop", envelope2)

In order to stop receiving events from some objects in a certain namespace, you simply send an envelope identical to the one used for subscribing via the stop message

FAQ

Device Network State

The device network state can be found under device.connection.online, true whenever the device is ONLINE.

Valid Position

There are 3 keys that can be used to find out whether the position of the event is valid, they’re all essentially the same: device.data.valid_gps also in the event’s keys: event.valid_gps device.data.valid_position also in the event’s keys: event.valid_position device.latest.loc.valid

Authentication Errors

Try updating the socket.io client to version 2.0.3 or higher.

Data Upload API

Pegasus allows you to upload custom device data via an HTTP POST method. For example, position related information from other telemetry devices for analysis in the Pegasus API & visualization in the PegasusApp.

Authentication / Asset linking

To get started we’ll need to generate a token that we’ll use to reference the device or asset that we want to populate data with on Pegasus Gateway. In order to create this token you’ll have to make a POST request to /assets here you can populate the asset with the included parameters such as first_name, last_name, email, etc.

After you create the asset you’ll need to activate a token for it, to do this make a PUT request to /assets with tracker_mode: true.

This will generate a unique token for that particular asset that we can use to POST data to. Example token: RSR9CD3C

Upload data

POST https://api.pegasusgateway.com/assets/event?tracker=6I4WFH9H

note that the POST is always made to ‘api.pegasusgateway.com’

{
    "latitude": 20.993852,
    "longitude":-89.710796,
    "mph":10,
    "heading":342,
    "altitude":10,
    "label":"ignon",
    "use_server_time":true
}

200 OK

{
    "message": "event processed successfully"
}

In order to publish telemetry data to Pegasus server node, send POST request to the following URL:

https://api.pegasusgateway.com/assets/event?tracker=:token

replacing :token with the token generated previously.

The exposed keys are:

param type description
latitude number WGS84 latitude
longitude number WGS84 longitude
mph number speed in mph
heading number heading in degrees 0-359 0=north, 90=east, etc.
altitude number device altitude in meters
[label] string event label (if not specified a trckpnt is automatically assigned) see list of labels below
use_server_time boolean true to use a server timestamp for the incoming data

Common labels

label description
prdtst Periodic report with ignition OFF
trckpnt Periodic report with Ignition ON (default if no label is set)
ignon Ignition was turned ON
ignoff Ignition was turned OFF
panic report when a panic button is pressed
pwrloss Main power was lost
pwrrstd Main power was restored
lwbatt Low internal device battery
spd Speeding
idl Idling
stt Device motion
stp Device stopped moving
in1on Input 1 ON
in1off Input 1 OFF
in2on Input 2 ON
in2off Input 2 OFF
in3on Input 3 ON
in3off Input 3 OFF

Please note that if the use_server_time is not set, the server-side timestamp will be assigned to uploaded data!

In case your device is able to get the client-side timestamp, you can use following format:

{“timestamp”:1532452713}

In the example above, we assume that “1532452713” is a unix timestamp with seconds precision. ‘1532452713’ corresponds to ‘Tuesday, July 24, 2018 5:18:33 PM GMT’

Geocoding

Reverse geocoding for 1 coordinate
POST https://pegasus1.pegasusgateway.com/api/reversegeo

{
    "lat": 26.30219,
    "lon": -80.24692
}

Response

{
  "location_full": "(US - Florida) Sawgrass Expressway, Parkland (US) ~~",
  "address": "Sawgrass Expressway, Parkland (US) ~~"
}

Reverse geocoding for multiple coordinates
POST https://pegasus1.pegasusgateway.com/api/reversegeo

[
  {
    "key": "first",
    "lat": 26.30219,
    "lon": -80.24692
  },
  {
    "key": "second",
    "lat": 25.82955,
    "lon": -80.20623
  }
]

Response (notice how there’s a key for ‘first’ and 'second’)

{
  "second": {
    "location_full": "(US - Florida) I 95, Miami (US) ~~",
    "address": "I 95, Miami (US) ~~"
  },
  "first": {
    "location_full": "(US - Florida) Sawgrass Expressway, Parkland (US) ~~",
    "address": "Sawgrass Expressway, Parkland (US) ~~"
  }
}

You can obtain the address information for any lat lon using the reversegeo api.

This api is also useful when you want to see the names of the geofences that the vehicle is in.

You can choose to send a single point or up to 50 points simultaneously in the request.

To make request to reversegeo simply make

POST /api/reversegeo

with the fields lat and lon respectively

The response will show you the

When you send multiple points you must specify a key, this will help you identify which json object corresponds to which lat, lon requested

Master Fields List

For more information please refer to the following spreadsheet

*Please note that by default all fields are included in the forwarders with the exception of the ones marked in the column : Included in Forwarder?

Field Description Value (units) Docs Included in Forwarder?
ac Instant Acceleration mphs
ad Analog Digital Value mV
age GPS Age
al Altitude meter
aid Asset Name assets Upon Request
asset_id Asset ID Not Available
asset_name Asset Name Not Available
bl Device Battery Level mV
cf_cid Cell ID HEX
cf_lac Local Area Code HEX
cf_rssi RSSI dBm
code Event Code
cvXX Counter Value
device_id IMEI (unique identifier per device)
dev_dist Distance traveled meters counters Upon Request
dev_idle Idling count seconds counters Upon Request
dev_ign Ignition ON count seconds counters Upon Request
dev_orpm Over RPM Time seconds counters Upon Request
dev_ospeed Over Speed Time seconds counters Upon Request
dphoto_ptr Photo ID photocam Upon Request
ea_a Analog / temp sensor probe A mV / °C temperature
ea_b Analog / temp sensor probe B mV / °C temperature
ea_c Analog / temp sensor probe C mV / °C temperature
ecu_dist Engine distance traveled meters counters Upon Request
ecu_eidle Engine engine idling time seconds counters Upon Request
ecu_eusage Engine ignition on count seconds counters Upon Request
ecu_ifuel Engine fuel consumed while Idling liters counters Upon Request
ecu_tfuel Engine total fuel consumed liters counters Upon Request
ecu_battery Vehicle battery level mV ecu monitor
ecu_brake_pedal Brake pedal pressed % ecu monitor
ecu_cool_lvl Coolant level % ecu monitor
ecu_cool_psi Coolant pressure psi ecu monitor
ecu_cool_tmp Coolant temperature °C ecu monitor
ecu_distance Total Distance meter ecu monitor
ecu_eng_oil_lvl Oil level % ecu monitor
ecu_eng_oil_psi Oil pressure psi ecu monitor
ecu_eng_oil_tmp Oil temperature °C ecu monitor
ecu_errorX Engine Error Code ecu monitor
ecu_fan_state Fan state ecu monitor
ecu_fuel_iconsumption Fuel consumed while idling liter ecu monitor
ecu_fuel_level Analog fuel level mV ecu monitor
ecu_fuel_level_real Fuel level % ecu monitor
ecu_hours Total engine usage hours ecu monitor
ecu_hours_idle Total engine usage while idling hours ecu monitor
ecu_hydr_oil_lvl Hydraulic oil level % ecu monitor
ecu_hydr_oil_psi Hydraulic oil pressure psi ecu monitor
ecu_hydr_oil_tmp Hydraulic oil temperature °C ecu monitor
ecu_idle_fuel Fuel consumed while idle liters ecu monitor
ecu_ins_efficiency Fuel instant efficiency kpl ecu monitor
ecu_intake_manif_tmp Intake manifold temperature °C ecu monitor
ecu_mil_error_code Malfunction Indicator Lamp code ecu monitor
ecu_mil_error_count Malfunction Indicator Lamp count ecu monitor
ecu_mil_state Malfunction Indicator Lamp state ecu monitor
ecu_oxygen Oxygen level mV ecu monitor
ecu_pgX ecu monitor
ecu_rpm Revolutions per minute rpm ecu monitor
ecu_serv_distance Distance left to service vehicle km ecu monitor Upon Request
ecu_speed Engine Speed kph ecu monitor Upon Request
ecu_throttle Throttle % ecu monitor
ecu_tires_tmp Tires temperature °C ecu monitor
ecu_torque Torque ecu monitor
ecu_total_fuel Total fuel consumed liters ecu monitor
ecu_trans_lvl Transmission oil level % ecu monitor
ecu_trans_psi Transmission oil pressure psi ecu monitor
ecu_trans_tmp Transmission oil temperature °C ecu monitor
ecu_trip_distance Trip distance meter ecu monitor
ecu_weights Vehicle weights kg ecu monitor
ecu_with_mil_distance Distance traveled with MIL on meter ecu monitor
event_time Time event was generated by the device YYYY-MM-DDThh:mm:ss
fpr_code Fingerprint code
fpr_conn Fingerprint connection
fpr_id Fingerprint ID
has_photo True if device has photo associated to the event Not Available
hdop HDOP value
head Vehicle direction 0 = North, 180 = South degrees
ib iButton unique ID
id Event unique ID
ii Second IMEI
io_exp_in1 Input 1 from expander status
io_exp_in2 Input 2 from expander status
io_exp_in3 Input 3 from expander status
io_exp_in4 Input 4 from expander status
io_exp_out1 Output 1 from expander status
io_exp_out1_short Output 1 from expander short circuit detected
io_exp_out2 Output 2 from expander status
io_exp_out2_short Output 2 from expander short circuit detected
io_exp_out3 Output 3 from expander status
io_exp_out3_short Output 3 from expander short circuit detected
io_exp_out4 Output 4 from expander status
io_exp_out4_short Output 4 from expander short circuit detected
io_exp_state Input/Output expander state
io_ign Ignition status
io_in1 Input 1 status
io_in2 Input 2 status
io_in3 Input 3 status
io_out1 Output 1 status
io_out1_short Output 1 short circuit
io_out2 Output 2 status
io_out2_short Output 2 short circuit
io_pwr Power status
ip IP address
ky Device configuration key Upon Request
lat GPS Latitud
lon GPS Longitude
metric *Deprecated refer to trips api
metric_units *Deprecated refer to trips api trips
metric_value *Deprecated refer to trips api trips
mgrs MGRS (Military Grid Reference system) coordinates
mph Speed mph
pc Pulse counter
pdop PDOP value
pid Pegasus site ID
port Port
prev_extended_id Previous event ID with extended information Upon Request
re_index Region index
re_sense Region sense
re_type Region type
short_desc Short description of event generated Upon Request
source GPS source
sv Satellites in view
system_time Time event was received by the device YYYY-MM-DDThh:mm:ss
tcXX Time counter values
tec_ff Technoton fuel frequency Hz Upon Request
tec_fn Technoton fuel level liters*10 Upon Request
tec_ft Technoton fuel temperature °C Upon Request
tec_st Technoton status Upon Request
trip_id Trip ID Upon Request
tx RS-232 data
type Event type
valid_position Valid position
vdop VDOP value
vh_hours *Deprecated see counters api (dev_ign) counters
vh_mins *Deprecated see counters api (dev_ign) counters
vid Vehicle id
vinfo Vehicle Info Upon Request
vo *Deprecated see counters api (dev_dist) counters

Syrusmart

SyrusMART is an application marketplace that lives inside of every Pegasus gateway.

It can be used to expose the applications you make!

Gateway owners are exposed to the applications and they can choose to install it

SyrusMART image

To submit one of your applications please fill out the following form: SyrusMART view the guidelines for submitting apps here

Examples

Please visit our Github repo for examples to get started with real life examples using the API