Geotab offers more data points of connection with robust, scalable and reliable tools. The SDK features sample code and projects to get first-time developers with Geotab started.
Introduction
The Geotab SDK (Software Development Kit) is a powerful set of tools for automating tasks and working with data in MyGeotab. Within these documents you will find information on how to develop JavaScript and C# applications, build and integrate Add-Ins and use MyGeotab with third-party systems.
Various working examples are included in this SDK for use as a starting point with your own code e.g.:
Integrate an embedded MyGeotab frame in your web application (real time map, vehicle listing and more)
Create your own web interface to import and export Geotab data
Accessing the device’s data
The Geotab Data Feed API is a scalable, efficient and secure method to access all the device’s data.
There are three different types of data that can be requested from the API:
LogRecords (such as position and speed)
StatusData (readings of vehicle measurements e.g. oil temperature or acceleration)
FaultData (fault codes and measurements reported by the engine)
The data feed service sample application allows the feed to be installed as a Windows service and run continuously in the background downloading data from the server (see here).
Importing, exporting and synchronizing
Geotab has a set of pre-made applications (which include full source code) for synchronizing MyGeotab data and can be used for example to:
Import your customer list from a CRM (Customer Relationship Management) system
Download your vehicle maintenance records into a maintenance system (DVIR)
Keep your routes up to date based the day’s deliveries
Synchronize your vehicle groups based on the vehicle’s role in the company
Track Hours of Service (HOS) for regulations compliance
You can start using these tools right now by downloading the C# examples here and the JavaScript examples here.
Automating tasks
Common tasks that you perform online using MyGeotab can all be automated using the Geotab API. You can create time-saving scripts or automated processes such as:
When a new pick-up arrives, automate the dispatching by sending a text message to the vehicle’s Garmin through an attached GO device
Synchronize your customer’s location with the closest vehicle when a new work order is created
Working with Add-Ins
Geotab has developed a number of Add-In products which can be easily integrated into your MyGeotab UI. The benefits of using Add-Ins are:
Ready availability of Add-Ins to instantly integrate into your MyGeotab. Visit the Geotab Marketplace and the Developing Add-Ins SDK page to see the available Add-Ins
Versatility to create your own Add-In to customize a page or button to suit your needs
Integrating with MyGeotab
You can integrate an embedded version of MyGeotab into your own web application. This is perfect for providing a website to your customers with insight as to where their deliveries are and when they will arrive. You have control of which features appear on the embedded MyGeotab to create a seamless integration between your software and ours.
By using single sign-on authentication with the Geotab API, you have the ability to manage several options from your MyGeotab user accounts including:
Receiving an authentication token from MyGeotab for a valid username/password
Accepting the end user agreement on behalf of the user (this has legal implications)
Updating a user’s password
Adding and removing a user
Each of the MyGeotab pages has a URL (Uniform Resource Locator) associated with the page that allows that page to be embedded in your own application or linked to. This is a great way to leverage MyGeotab and make it part of your services. See here for more details
Integrating third-party tracking devices into MyGeotab
Third-party tracking devices can have their data added into the MyGeotab database. The Geotab API is used to provision and upload the devices data. Additionally data from these devices can be used in conjunction with data collected by Geotab GO devices. Contact Geotab support to have your third-party device added (each device type will receive a unique prefix code) and contact your reseller to handle billing.
Note: There may be differences in how devices from third-party manufacturers record the data; frequency of data collection and accuracy of the device record may vary. The rich information contained in the MyGeotab reports may not be fully available. Testing of these tracking device will be required to properly integrate the data into MyGeotab.
The Geotab API (Application Program Interface) is fully available to MyGeotab customers. Geotab provides helper libraries for C# and JavaScript; however, any language or application capable of making HTTP (HyperText Transfer Protocol) requests can access its full functionality. Only valid MyGeotab user credentials are required; special API keys or tokens are not necessary. Nonetheless, we recommend that the API be accessed with a dedicated user.
Note: The examples and source code presented in the Geotab SDK (Software Development Kit) require a modern browser. We recommend using the latest versions of Chrome, Firefox, Internet Explorer or Safari.
Steps to get started
For testing purposes we recommend setting up a test database and adding test devices to it. Remember, if you decide to test against a production database, data could be accidentally modified or lost.
You can now signin to my.geotab.com and access your database. Spend some time working through this guide and familiarize yourself with the key components of the application
Add your GO device serial number to this database so you can collect some GPS, Engine and other useful data
What’s next?
There are several other items in the SDK to help you get started:
Concepts—Be sure to read through this before building your application
API Reference— the reference documentation that explains what each API call does and documents the parameters and results for each call
API Runner— an easy way to “play” with the API. Click on the “Runner” link from the API Reference. It is a tool that can be used to make method calls to a MyGeotab server and see what the results look like
Note: Remember you are not in a sandbox — you are executing API commands against a real database. For example, removing a Device via the API will really delete that device from the database!
JavaScript or .NET Code samples. The JavaScript sample are “live” and can be run against your database hosted on my.geotab.com. The .NET examples are downloadable and can be compiled and run against your MyGeotab server.
For additional support use the SDK forums. A number of solutions have already been provided in the forums. They are monitored by Geotab staff and other users of the SDK.
Concepts
Requests made to the Geotab API are performed over HTTPS. The current API is version 1 — this is denoted in the API endpoint URL the web application will send requests to:
https://<myserver>/apiv1
Note: The portions of the examples noted with < and > (e.g. <myserver>) indicate where the user will enter information specific to their requirements.
API request parameters and the results are transported in the lightweight JSON format. The API reference contains a listing of the methods that can be invoked, the parameters they expect and the results they return.Below are examples to illustrate the capabilities of the Geotab API.
Requests to the API can be invoked using HTTP GET or POST. HTTP POST requests uses the JSON-RPC standard. The following sections explain how to construct HTTP GET and POST requests to the Geotab API.
HTTP GET request
Methods can be invoked via HTTP GET request as follows:
Here is a simple example of invoking the method GetVersion. This method does not require any parameters and can be called without credentials:
https://my3.geotab.com/apiv1/GetVersion
The HTTP response is returned as JSON.For example:
{"result":"5.7.1508.122"}
Where the version will be the current version on the server.
Make your first API call
Here is a more complex example that requires parameters. For the sake of clarity, the example below is not URI (Universal Resource Identifier) encoded (more on this below). Both POST and GET requests are supported. This example shows a GET request that returns all devices (vehicles) and their properties.
The full set of API methods and objects returned can be viewed by clicking on theAPI Reference. When utilizing methods which require the user to send their login credentials as part of the URL, it is advised to take precautions regarding visibility of their password to other parties.
To understand how the parameters were passed in the URL, consider the following JSON object that needs to be passed to the method:
Using an HTTP query string, all the JSON object properties above are serialized after the method name in the query string as key/value pairs, separated by ampersand characters as follows:
Note that in the examples above, the property credentials are objects. In this case, stringify the JSON object and set that as the property value. Also take note that the query string should be properly URI encoded; paste the example below here and select decode URL. The final HTTP GET request looks as follows:
The MyGeotab API also supports JSONP when doing HTTP GET requests from JavaScript. This can be useful when writing a standalone HTML/JavaScript app. See the Using in JavaScript section for more information.
HTTP POST request
When using HTTP POST request to invoke an API method, the same endpoint as the GET is used:
https://<myserver>/apiv1/
However, instead of encoding the method name and parameters in the query string, it is passed in the HTTP body using the JSON-RPC format. Geotab API version 1 supports JSON-RPC version 1.0.
The following is a JavaScript example that shows how an HTTP POST can be used to invoke a method. Note that this can be done from any language that has support for HTTP, for example the java.net.HttpUrlConnection class in Java or System.Net.HttpWebRequest in Microsoft .Net can be utilized.
var request = new XMLHttpRequest();
request.open("POST", "https://my.geotab.com/apiv1", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status === 200) {
var json = JSON.parse(request.responseText);
if (json.result) {
// Work with your result
// Simple example just alerts its presence
alert("Received Data");
}
}
}
};
// Send the HTTP BODY in the JSON-RPC format. ID is ignored
// and can be set to -1.
// The method being called is “Get”.
// The “Get” method’s parameters are then passed in the “params” property
var apiMethod = {
"id" : -1,
"method" : "Get",
"params" : {
"typeName" : "Device",
"credentials" : {
"database" : "demo",
"userName" : "bob@geotab.com",
"sessionId" : "xxx"
}
}
};
request.send("JSON-RPC=" + encodeURIComponent(JSON.stringify(apiMethod)));
Results & errors
Using the example above, a successful call to the server will result in an object with property “result”, in this format:
Generic:
{"result":"results"}
Specific:
{"result":"5.7.1508.122"}
However, when the call is incorrect or an error is triggered on the server, the error will be returned as an object with property “error”. For example:
For all JSON-RPC errors this is always “JSONRPCError”.
message
The description of the likely root cause of the error.
errors
An array of individual errors that were caught. Usually, there is at least one error in this array.
The properties for objects in the “errors” array are:
Property
Description
name
The name of the server exception. For example, “InvalidUserException”, “NullReferenceException”, etc.
message
The description associated with the server exception.
stackTrace
If there is a stack trace, this will be a string of method calls that led to this server exception triggering. This field may not always be present, depending on the server exception that was triggered.
See Example 3: Dealing with a database move or credential expiryfor an example of a case where it would be useful to catch and handle errors.
Authentication
Data is stored on one of many servers in our cloud. A group of servers is referred to a federation of servers. For example, the my.geotab.com federation consists of my1.geotab.com, my2.geotab.com andmany other servers.
While it is tempting to simply “hard code” the application to point to a particular server, such as my20.geotab.com, this is the incorrect approach. Over the course of time adatabase is not guaranteed to remain on the same server. It is common for load balancing to occur and resources to be transferred from one server to another as necessary. To prevent the application from losing its connection to the correct database, authentication calls must be made to the root federation server instead of making the request to a particular server.
As an example; making an authentication call to “my.geotab.com” and authentication occurring. Such a call could be made as:
If a redirect is necessary, the application will be informed and the correct server can be targeted. Below are special cases whichshould be considered when accessing the federation.
Example 1: Currently on the correct server
In this example, an authentication call is made to my.geotab.com to loginto the database “acme” and the server responds that the server is correct (e.g. no need to redirect).
Steps:
The Authenticate method is called with the given credentials
The response from the server contains two important properties: path and credentials
The path will either contain the URL of a server or the string value ThisServer. Since the database “acme” in this example is on my.geotab.com, it simply returns ThisServer as highlighted below. This means that the correct server has been targeted and there is no need for a redirect.
The credentials object contains the username, database and session ID. This object will be used in all subsequent calls (password not required when used).
As the authentication method stated the server is correct, other methods can be called. For example GetCountOf, to my.geotab.com. Pass the property called credentials and send along the contents ofcredentials that was returned in step 2
The result of the GetCountOf is returned, in this case it is 1234
Example 2: Redirect to different server
In this example, an authentication call to my.geotab.com is made trying to log into database “acme”. Here the server responds that the database is located on my23.geotab.com. Subsequent calls are then directed to my23.geotab.com
Steps:
The Authenticate method is called with the given credentials
The response from the server contains two properties: path and credentials
The path will either contain the URL of a server or the string value ThisServer. Since the database “acme” in this example is on my23.geotab.com, the return is “https://my23.geotab.com” meaning that all subsequent requests should be directed at my23.geotab.com.
The credentials object contains the username, database and session ID. This object will be required in all subsequent calls to the server for security reasons (password not required when used).
As the authentication method stated that acme is on the my23.geotab.com server, other methods can be called, for example GetCountOf, to my23.geotab.com. Pass the property called credentials and send along the contents of credentials that was returned in step 2
The result of the GetCountOf is returned, in this case it is 1234
Example 3: Dealing with a database move or credential expiry
The examples in the previous sections demonstrated how to specify which server to communicate with during authentication. There are however two additional situations to consider:
the database has moved to a different server
the credentials object returned willeventually expire
When this happens the next API call will fail with the following error object:
When the errors collection contains an object with name “InvalidUserException”, the authentication process must be repeated. This will indicate what the new server is and provide a new credentials object. If the authentication process returns an error, the user was likely changed, in this case another user will be required for the login.
Working with dates
When exchanging dates as parameters to API methods, you must ensure that they are formatted properly as an ISO 8601 string (format yyyy-MM-dd-HH-mm-ss). In addition, all dates will have to first be converted to UTC in order to ensure time zone information and daylight savings times are accounted for correctly.
Unit of measure
As a general rule, MyGeotab uses the metric system for values such as speed (km/h) and distance (m). For example, if you queried the odometer reading for a vehicle, the value would be returned in meters or if you retrieved the current speed of a vehicle it would be in km/h. It does not matter in which region in the world the vehicle or user of MyGeotab system is located — we always return the values in metric.A simple conversion can be applied to these values should you wish to work in imperial units or other customized units instead.
Please note that MyGeotab also records various other status data (i.e. engine data) from the vehicle and these values can be in various units of measure. The units of measure are not provided by Geotab in all cases. Refer to the applicable SAE standard of the specific code for the associated unit of measure.
Entities
All objects in the MyGeotab system are called entities. Entities have an ID property that is used to uniquely identify that object in the database. The ID is an opaque string value that uniquely identifies the entity and no assumption about the format or length of this ID value should be made when comparing or storing the values.
ID
An ID is used to uniquely reference entities in the API. IDs are represented by opaque strings. Generally the contents of the IDs are not significant for the user. Building logic around the value of the string should be avoided — unless it is a system ID (see the examples below).
Example 4
In this example, a vehicle in the system and its ID value will be examined. Here is a partial JSON representation of a device object:
Note the “id“ property with value “b0a46”. This is the unique identifier for the device (vehicle) with description “007 – Aston Martin”.
To find Trips for this vehicle all of the properties of the device do not have to be passed to the Get method. Instead, only the ID property of the device object is required. Below is an example of a valid parameter object (TripSearch) for passing into Get method. The deviceSearch with the ID property set to the value “b0a46” (as indicated in the example above) is passed.
Calling the Get method with the parameter defined above will return all trips for the vehicle “007 – Aston Martin”.
Example 5
There are certain IDs that are predefined for system entities. For example the group that has been defined as the root group of all user groups, and called the CompanyGroup, will have an ID of “CompanyGroupId” rather than other characters (such as “b0a46” above). For example:
{
"id": "CompanyGroupId",
"name": "The Company Group",
"children": [..]
}
If the system entities do not have any properties then they are specified as strings with their ID’s name. For example the source “Obd” will be identified as “SourceObdId”.
The results of a call to our API will only contain literal values and the identities of contained objects — not the actual fully populated child objects. This provides a predictable system that efficiently serializes objects to JSON and back. Additional lookups of the nested objects will be required to retrieve additional properties of the objects.
For example, an engine status data record has a device property. If 1000 engine status data records are retrieved for a device, the status data’s device property will only contain the ID of the device. An additional retrieval for the devices object will be required to obtain the status data records. This approach has several benefits:
Saves bytes over the wire
Reduces request time
Avoids redundant copies of entities
More flexible since the child objects may not always be required
In the example below it can be seen how, by creating a dictionary of devices where the key is the device ID and the value is the device object, devices can be easily “stitched” into the status data records:
Depending on the process, for some entities like diagnostics, it may be desirable to maintain a local cache from which the status/fault data can be populated. In this case it will be necessary to refresh the cache whenthe cache is missing the required entity making an API call.This will allow the API to get the required entity and add it to the local cache. An example of maintaining a diagnostic cache would occur when consuming a feed of data from the API. An example of this process is included in both the C# and JavaScript DataFeed examples.
MultiCall
A MultiCall is a way to make several API calls against a server with a single HTTP request. This eliminates potentially expensive round trip costs.
Why use a MultiCall?
Making an HTTP request over a network has overhead. This can be in the form of Network overhead, the round trip time to send and receive data over the network and HTTP overhead, the HTTP request and response headers. A MultiCall can be used to reduce amount of overhead in situations where many small requests need to be made to a server.
For example, if we make a request to get the max road speed from a set of points. The request would be constructed in a format similar to:
Making the assumption that it takes 100 milliseconds for this call round trip (the time from sending request to receiving the response), 40 milliseconds to send the request, 20 ms to process the data on the server and 40 ms for the response to be returned.Google’s SPDY research project white paper states that “typical header sizes of 700-800 bytes is common”. Based on this assume a 750 byte cost when making a request. From the example,there would be 80 ms of network overhead and 750 bytes of HTTP overhead, this is accepted as the “cost of doing business” when making a request over a network.
Taking the previous assumptions, what would the overhead be for making 1000 requests for road max speeds? When individual calls are made to the server for 1000 addresses; the base (minimum) HTTP and Network overhead is required for each of these calls. This would result in 80 seconds (80,000 milliseconds) of network overhead and 5.72 MB (750,000 bytes) in headers just going to and from the server. It can be clearly seen that a great deal of overhead can be generated by making small but repeated requests.
By using a MultiCall, the network and HTTP overhead remains at the cost of a single request. This brings the overhead back down to our original 80 milliseconds and 750 bytes. The server processes each request andreturns an Array of results when complete.
The above illustration is an extreme example to demonstrate the benefits of using a MultiCall. A MultiCall can (and should) be used to make short running calls of 2 or more requests more efficient than individual calls.
Basic implementation
Making a MultiCall is very simple, use the method “ExecuteMultiCall” with the parameter “calls” of JSON type Array. Each call should be formatted as an Object with property “method” of type string with the method name as its value and a property “params” of type Object with the method parameters as its properties. The “params” object will also need to contain the user credentials if they are required for the method being called.
Both the C# and JavaScript API wrappers supplied (included with the samples) have native support for making multi calls. See the examples below:
JavaScript API multi-call example:
var calls = [
["Get", { typeName: "Diagnostic" }],
["Get", { typeName: "Source", search: {id: "SourceGeotabGoId"}}],
["Get", { typeName: "Controller" }]
];
api.multiCall(calls, function (results) {
var diagnostics = results[0];
var sources = results[1];
var controllers = results[2];
}, function (errorString) {
alert(errorString);
});
C# API multi-call example:
object[] calls = new object[] {
new object[] { "Get", typeof(Diagnostic), typeof(List<Diagnostic>)},
new object[] { "Get", typeof(Source), new { search = new SourceSearch { Id = KnownId.SourceGeotabGoId}} typeof(List<Source>)},
new object[] { "Get", typeof(Controller), typeof(List<Controller>)},
};
List<object> results = api.MultiCall(calls);
List<Diagnostic> diagnostics = (List<Diagnostic>)results[0];
List<Source> sources = (List<Source>)results[1];
List<Controller> controllers = (List<Controller>)results[2];
MultiCall FAQ
Can I use a search in a multicall?
Yes, it is possible to use a search in a multicall.
When shouldn’t I use a multicall?
If you need to make a few requests that are long running and return a large amount of data.In these casesit may be preferable to make these requests singularly instead of running one request that continues for a very long time before completion. When the connection is held open for a long period of time you become increasingly susceptible to network interference that could terminate the request.
How many request can I put in a multicall?
There is no limit on the number of requests that can be made in a multicall. When making a large number of requests it may be desirable to “chunk” the requests into several requests of a smaller and more manageable size.
What if the call doesn’t return a result? (For example: a set operation)
The index in the array of results will have a null value.
What if an error occurs in one of the MultiCall requests?
In a MultiCall, each request is run on the server in succession, when one fails the error results are returned immediately and unreached calls are not run.
To illustrate, let’s assume an array of calls (api.multicall([call-a, call-b, call-c])) where call-b is formatted incorrectly. On the server this would look similar to:
[
call-a, // ran successfully
call-b, // error occurred, throw and return error
call-c // never ran
]
results = {"error":{...}}
Alternatively, a successful MultiCall would look similar to:
[
call-a, // ran successfully
call-b, // ran successfully
call-c // ran successfully
]
results = [[...], [...], [...]]
Using in JavaScript
GeotabApi object
Geotab provides JavaScript developers with easy to use and consistent access to our API through the GeotabApi object.The GeotabAPI provides authentication handling, asynchronous method calling, error handling and multi–call support.A copy of api.js has been included in the JavaScript examples.
Creating a Geotab Api object
When creating the GeotabApi object, prepend a reference to the file api.js before the main JavaScript code:
In the main JavaScript code, initialize the GeotabApi object by providing the constructor with a callback function to handle the authentication:
var api = GeotabApi(function (authenticationCallback) {
// Handling getting credentials. Deals with these cases:
// a) No credentials yet (first page load)
// b) The credentials have expired (password changed or server moved)
// c) "api.forget()" has been called
//
// Show the dialog now & set up listener to callback with credentials
//
document.getElementById("submit").addEventListener("click", function () {
var
server = document.getElementById("server").value,
userName = document.getElementById("username").value,
password = document.getElementById("password").value,
database = document.getElementById("database").value;
authenticationCallback(server, database, userName, password,
function (errorString) {
alert(errorString);
});
}, false);
});
When the GeotabApi object has been set up, the first call to a method will trigger the callback to get the credentials.Once the credentials have been entered by the user, the authenticationCallback will be called with the entered credentials.Then the original method result will then be retrieved.After this method has been called, the server, database, username, and session are stored in localStorage.
Using the GeotabApi object
The following example demonstrates how to use the GeotabApi object to request the location of a vehicle.
var deviceId = "b93B";
// Sample API invocation retrieves all "Device" objects
api.call("Get", {
typeName : "DeviceStatusInfo",
search : {
deviceSearch : {
id : deviceId
}
}
}, function (result) {
if (result != null && result.length > 0) {
alert(JSON.stringify(result[0]));
}
}, function (errorString) {
alert(errorString);
});
The Call method arguments
The Call method is used to “Call” any of the APIs that the MyGeotab SDK provides.It takes 4 arguments:
Argument
Description
method
The API method that is being called.For example, “Get” or “GetCountOf”.See the API reference for the full set of methods.
params
The parameter object that the API method expects.For example: { typeName: “DeviceStatusInfo”, search { deviceSearch: { id: deviceId } }
callbackSuccess
The function that will be called back when the API call succeeds.The callback function has a single argument called “result” that will contain any results returned by the API call.
callbackError
The function that will be called back should the API call fail.The callback function has a single argument that will contain error information.
A note about state
The GeotabApi object is designed to be stateless.The main reason for this is that a call could fail at any point due to session expiry or the database moving.The authenticationCallback will automatically be called when this situation is detected.The application will then prompt (or read from file etc.) for the required credentials.The call that was being attempted will resume when new credentials are received.This also means that there is no concept of being “logged in” or “out” of the server.
Working with JSONP
Creating aJSONP request is similar to creating a HTTP GET request — but with one minor change.An additional parameter that specifies the callback in the requested URL will be required to be passed as follows:
When the examples are downloaded, the GeotabApi object has an option to use JSONP requests.In this way the examples can be run without placing them on a Web server.
Next steps
Once you have a basic understanding of how api.js and the JavaScript API work and want to learn more, you can take a look at our examples here.
Using in .NET
Overview
The .NET SDK tools provide an easy way to integrate MyGeotab into .NET software. All of the communication to Geotab’s services is accomplished over HTTPS with data serialized in JSON format. The .NET library provided will automatically handle the JSON serialization and deserialization into MyGeotab objects.
Geotab.Checkmate.ObjectModel.dll
Including this assembly in the project allows forthe interaction with theGeotab API. It is a convenient “wrapper” around Geotab’s HTTP/JSON API to allow developers focus on writing code instead of moving data over the wire. It includes tools to assist authenticating against Geotab’s servers, automatically serializing/deserializing JSON, and providing definitions for Checkmate object classes.
Download the Geotab.Checkmate.ObjectModel.dll and .NET examples from the .NET example ZIP file and add a reference to it from the .NET project.
API class
Step 1: Initialization & authentication
In order to have access to the API class, add the following to the file’s includes section:
using Geotab.Checkmate;
using Geotab.Checkmate.ObjectModel;
An instance of API can now be constructed to be used in the code. For the most basic use case, all the data that is needed is user credentials and a database name:
API api = new API(userName, password, null, databaseName, server);
At this point there has not been any communication with Geotab’s servers. In order to make calls to Geotab’s API, an authentication call must be made:
api.Authenticate();
When the call is made to Geotab’s servers to authenticate, a token is returned for security. For more information regarding how Geotab handles authentication, please review the “Authentication” section intheConcepts documentation.
Behind the scenes, the Authenticate call makes a JSON-RPC request to Geotab’s “Authenticate” method. The resulting security token and server information are stored in order to make further calls to the API.
Step 2: Making calls
When authenticated, calls are made to the API by invoking the “Call” method of the API class.
The example below illustrates how to make a generic call to get all devices in the system.
In the example below it is shown how to delete a device using the generic “Remove” method. Notice that it is not required to send all of the device’sinformation to remove it, the device’s id is sufficient:
api.Call<object>("Remove", typeof (Device), new { entity = new Device { Id = “b1a34” }});
The last parameter to this Call method is an anonymous object which contains the parameters for the method (please review the API reference to see which parameters the method expects, and whether the parameters are required or optional). The parameter order is not significant, and it is acceptable to omit optional parameters. Optional parameters will revert to their default values, typically “null” or “false” values.
The API class automatically handles databases that are moved to different servers in the federation and expired tokens (token are typicallyvalid for 2 weeks) by automatically re–authenticating and continuing.
Example code
The following is a simple console app that will output the latitude and longitude of each device in a list of devices:
static void Main(string[] args)
{
// Create the API object and authenticate
API api = new API("bob@geotab.com", "password", null, "demo", "server");
api.Authenticate();
// Get all devices
List<Device> devices = api.Call<List<Device>>("Get", typeof(Device));
Console.WriteLine("SerialNumber\\tLatitude\\tLongitude");
foreach (Device device in devices)
{
// Get the Device Status Info which contains the current latitude and longitude for this device
List<DeviceStatusInfo> results = api.Call<List<DeviceStatusInfo>>("Get", typeof(DeviceStatusInfo), new
{
search = new {
DeviceSearch = new { device.Id }
}
});
if (results.Count <= 0)
{
continue;
}
DeviceStatusInfo deviceStatus = results[0];
// Print the results to the console
Console.WriteLine(device.SerialNumber + "\\t" + deviceStatus.Latitude + "\\t" + deviceStatus.Longitude);
}
}
After entering your credentials into the API constructor, this example will produce results similar to this in your command prompt window.
Next steps
Once you have a basic understanding of how the .NET SDK works, we recommend reviewing the examples that we have created here.
Data Feed
The data feed is the primary method used to synchronize data from the telematics system to another system using the API. The GetFeed method can be polled at intervals to get new and updated data from the system. The feed API works with a token that is passed on every request and sent back with the payload on every response. This allows Geotab to track “up to which point in time” we have already sent the receiver data. It also allows the receiver to stop and seamlessly resume the data feed.
Lightweight incremental poll
The feed API is designed to be lightweight and scalable. There is virtually no cost on Geotab’s side for a poll request that yields no data. For example, a poll request when the round trip has no GPS coordinates will return no payload data. The requests themselves, the amount of processing time taken, and the amount of data returned via the internet are all extremely small.
Here is a small trace showing < 100 bytes for an empty poll request with response time of 19ms. The last request contains a payload with 2 GPS coordinates.
The polling frequency is dictated by the requirements of the integration. It could be as infrequent as once a day or as frequent as every few seconds.
Dealing with volume
In each request the caller can specify the maximum number of data points that can be returned in a request. This allows the caller to have control over the maximum size of the responses. This value can be adjusted down from the default of 50,000 — with fewer data points yielding a faster response time. When the limit is reached, the response will be returned with the payload and a token which can be used to specify the point in time from which the next request should start.
The request-response approach also allows for incremental processing. For example, if there were a large backlog of data, the caller would be able to process the chunks of data at its own rate until the backlog ofdata has been cleared.
The API can be consumed by small and large customers alike. Larger customers can consume tens of millions of records per day via the API.
Searching by date
The data feed was designed to be an efficient means of getting a continuous feed of new data from a given token. When a feed is first started it is possible to provide search criteria with a “from date” argument. This specifies the token that will be used to start the feed. This will guarantee that the feed will start at a point that will include any data that is at or after the “from date” argument, but may also include data timestamped before the “from date” argument. For example when performing a “TripSearch” and setting “IncludeOverlappedTrips” to True.
While “from date” is supported, “to date” is not. The feed is not designed to return data within discrete dates. If you wish to obtain data in a particular date range, then use the standard Get methods associated with the entity search objects. If a version is specified, then the argument “from date” is ignored.
Caching can improve performance
It may be required to populate nested entities of data retrieved via the feed. Entities that are static or semi-static will respond well to caching.
For example, status data and diagnostics are separate entities in the system. Status data references a diagnostic. Status data returned by the feed will only have the ID property of the diagnostic populated. If the diagnostic is required by your process then you must get the diagnostic in a separate API call and populate it in the status data record.
This is a good example of where caching can be implemented to improve efficiency, as diagnostic data rarely changes. A cache of diagnostics can be held in memory, refreshed at some interval of your choosing (24 hours, 12 hours, etc.) and may vary depending on the entity type being cached. Entities that may respond well to caching include Unit of Measure, Diagnostic, Source, Device and User.
Active versus calculated
There are two types of data that can be retrieved using a data feed: active data and calculated data. Active data is data that does not change and is not calculated from any other type of data in the system. This data is generated by the device, sent to the system, and is then added to the database. Active data is rarely updated and will not be invalidated by the system. Calculated data is derived from active data. As new active data arrives, it is processed to calculate Trips and Exceptions. Data processing happens in real time.
Active data feeds (only new data)
Log Record
Status Data
Fault Data
DutyStatusLog
DVIRLog
AnnotationLog
ShipmentLog
Calculated data feeds (new and updated data)
Trip
Exception Event
Invalidated data
As calculated data is processed in real time, the state of the data can change causing it to become invalidated. There are a few reasons why calculated data can become invalid or need to be updated by the system.
A trip or exception is in progress
The system receives new data that invalidates previous data
Manual reprocessing was triggered
Trips
Trips are calculated data. As new data arrives for a trip currently in progress, the older data for the trip is dropped from the database. The dropped data is then replaced with the newer, more current trip data. Theupdated trip data will have a different trip ID than the previous record of the trip. Thus the “unique trip ID” cannot be used to match an updated trip to an earlier state.
The unique “key” that is used to associate the earlier “version” of the trip in progress to the updated trip is the pairing of the deviceId and the trip stop date. Most of the time, a trip which is in progress will have its stop date continuously updated until the trip has actually ceased (ignition off). If there is no trip in the trip history that matches the combination of deviceId and trip stop date of theupdated trip data, and the updated trip has a stop time of zero, then the historical trip which matches the updated trip data will be replaced with the newer trip data.
Exception events
Like trips, exception events are calculated data. As the system receives updated device data, that data is processed and evaluated against the Rules set up in the system. Exception events that are in progress will be updated by the system and will retain the same unique id. Exception events can be invalidated and dropped from the database when a manual process is triggered. Reprocessed exception events will have a new unique id.
HOS and DVIR feeds
The HOS and DVIR related objects under the “Active data feeds” (DutyStatusLog, DVIRLog, AnnotationLog, ShipmentLog) are likely to be edited on a frequent basis. An example is a “DutyStatusLog” that was created (Add) at the beginning of the day with an “ON” duty status, and then edited (Set) to add the “verifyDateTime” at the end of the day.
Each time one of these data records is manipulated, it will retain its original unique GUID “Id” but will receive an incremented “version”. This way you can match new feed records to existing data you obtained from an earlier feed request.
FAQ
Why do I have to poll data, can’t you push it to me?
A push-based approach would require Geotab to connect to another organization and this invariably means firewall traversal is required. To accomplish this, network administrators will need to be involved and will be required to maintain the process. This is very often a cumbersome process and sometimes disallowed due to security risks. Geotab wants to provide a zero configuration solution. The poll-based approach avoidsthese issues because all traffic is initiated from within your network, secured via SSL. No certificates need to be installed, no firewalls configured, and no other onerous security requirements are necessary.
There are definitely advantages and disadvantages to both approaches. However, in our experience, we have found the polling based approach is scalable, solves practical network problems, requires zero configuration, and meets the needs of our customers.
MyGeotab URLs
This guide explains how to format a URL (Uniform Resource Locator) to obtain access to a specific page/feature in MyGeotab. This can be used to link to MyGeotab from an Internet application, sending an email notification, third-party applications and other customized functions.
Link to a page
To create a link to a page, the following URL structure is used:
Note: The portions of the examples noted with < and > (e.g. <serverName>) indicate where the user will enter information specific to their requirements.
Item
Description
serverName
The name of the server the database is on. For example, my.geotab.com
databaseName
The name of the database. This is typically the company name used during registration. If there are spaces in the name, they are replaced with underscore characters (_)
page
The MyGeotab web application page name
parameters
Additional arguments to apply to the request. For example, ‘currentSortMode:deviceName’ will sort the devices on the device list page by name. Note: each additional parameter is separated by a comma
Example:
Browse to your database using this URL format
https://<my3.geotab.com>/<g560>/#devices
Note: If you are not yet logged in, you will be prompted for your credentials.
Standalone pages
Standalone pages are used to get a my.geotab.com page without the header and side menu. This is useful when specific functionality is required, for example adding a new vehicle to the system.
To create a link to a page, the following URL structure is used:
Note: If you are not yet logged in, you will be prompted for your credentials.
Passing parameters to a page
Parameters are added at the end of the URL and each is separated by a comma. They work the same for both the normal and standalone page types. It is also important to note when no parameters are requested, the page will load with the default settings. The parameter and its value are always separated by a colon (“:”).
Example:
These links will navigate to the map pages showing the live position of a device with id ‘b21’, and with the group ‘b1234’ highlighted.
Default: edit user preferences page, no parameters required.
Example:
https://<serverName>/<databaseName>/#options
Credentials
Links That include username and database
It is possible to insert username and database credentials into a URL. Note that the user will be required to be logged in to utilize these types of links.
Refer to the ‘Concepts’ page, under the section ‘Authentication’. Within that section the instructions explain the process of authenticating a user to obtain their session id.
Security Using the Session Id
By using the sessionId, a valid login is created for that account. Another user will be able to fully access that account as long as the sessionId credential remain valid. If an application is being created where the sessionId could potentially be viewed by another party, it is advised to generate the credentials using an account with access limited only to the necessary data.
Using GO devices in your software
Who is this for?
Geotab offers an option where the GO device hardware can be used without using the MyGeotab fleet management software. The rich telematics data that is captured by Geotab’s hardware can be utilized in a customized software solution. This document covers the necessary steps to set up a customized solution. Note that the same API is used to retrievethe data from Geotab’s hosting solution and is identical to the regular MyGeotab configuration.
Overview
Data flows from the GO device to the MyGeotab hosted solution automatically. The first step is to create a database to receive the device’s data (as outlined in Getting Started). Once that is complete, the device can be accessed using the APIs defined below.
Device hierarchy
Different devices can support different features. Device objects are designed to extend from shared objects that have mutual support. In this way, each device object will only have properties that are supported and relevant for its specific type. The image below illustrates how different device types relate to each other and their hierarchy.
API to add vehicles
Geotab has a robust API that allows third-party developers to create their own applications that use data from Geotab hardware. A partner using Geotab hardware with their own software must use the API to add their Geotab devices to the database, as discussed above.
Adding a single device
C# API
API api = new API(username, password, null, database);
Device device = Device.FromSerialNumber("GT970000006A");
device.Name = "My First Car";
device.Id = api.Call<Id>("Add", typeof (Device), new { entity = device });
JavaScript API
var newDevice = {
name: "My First Car",
serialNumber: "GT970000006A"
};
api.call("Add", {
typeName: "Device",
entity: newDevice
},
function (result) {
newDevice.id = result;
},
function (errorString) {
alert(errorString);
});
HTTP request
https://YourServerName.geotab.com/apiv1/Add?typeName=Device&entity={"serialNumber":"GT970000006A","Name":"My First Car"}&credentials={"database":"Your Database Name","userName":"Your User Name","password":"Your Password"}
The above code samples show a sample call to add a single device to a database using the C# API, JavaScript API and an HTTP request. Please refer to the API documentation for more information.
Adding Multiple Devices
Both the C# and JavaScript examples contain a comprehensive demonstration of how to add multiple devices to a database.This can be used as a starting point for additional development.
API to extract data
The simplest way to extract data efficiently and reliably is to create a data feed. There are special methods for this application — see the Geotab Data Feed documentation. The document contains examples of how to create a data feed in C# and JavaScript.
Enable in-vehicle features
To enable or disable vehicle features, the appropriate properties of the Device/GoDevice object must be set. For example, to enable beeping before adding the device to MyGeotab, the C# example above would be changed to:
API api = new API(username, password, null, database);
// GoCurve extends from Device and models a GoDevice with beeping features
GoCurve device = (GoCurve)Device.FromSerialNumber("GT970000006A");
device.Name = "My First Car";
device.DisableBuzzer = false;
device.Id = api.Call<Id>("Add", typeof (Device), new { entity = device });
Please note that GO devices use a byte value to track parameter changes. If an in-vehicle feature like a speeding alert was enabled, increment the parameterVersion property by 1.
If a device has already been added to MyGeotab it can have features enabled or disabled by first obtaining the device parameters, changing the desired properties, and then calling the ‘Set’ method instead of ‘Add’.The API documentation has a number of examples on how to Get, change, and Set a device.
GO device logging
Overview
GO devices use intelligent patented logging algorithms to decide when to record speed, position, and other engine information. The device is constantly monitoring various inputs, for example: second-by-second GPS data, hundreds of accelerometer readings per second, and engine diagnostic inputs. The device monitors the data and determines the appropriate time to store a value.
Various data loggers exist on the market today that use a simple time- or distance–based logging algorithm. These approaches, though simple, have significant drawbacks:
Important high or low values for speed (or other metrics) could be missed.
Positions during cornering are missed (producing inaccurate mileage or poor display on map).
Increased data costs by logging redundant information (for example, recording data for a vehicle that is not moving or moving in a straight line at a constant speed).
Logging accurately
The main concept behind GO device logging is to produce an accurate representation of the original data by logging the essential points on a graph and discarding redundant points. We sometimes refer to this ascurve-based logging. This is best illustrated by example:
In this graph, the actual trip is represented by the blue curve. The red dots represent a simple time-based sampling where a speed value is recorded at regularly spaced time intervals. Notice how some high points and low points are missed by this approach. Also notice that, even when the speed does not change, the time-based approach continues reading the same value.
The green dotsrepresent a more accurate record of the data by establishing the ideal way to reproduce the data with with the fewest number of data points. This is the basic principle that underpins the intelligent logging of the GO device.
Position and speed
The GO device monitors both position and speed at the same time, using the approach discussed above, to log the data. By doing so, the speed profile can be very accurately reproduced and the location of the device determined. This also means the trip will be logged properly around corners (yielding a very accurate mileage calculation).
Engine diagnostics
The GO device also monitors key engine diagnostic values and applies the approach above to log these values (data such as RPM curve, fuel level and many other parameters) in an optimized manner that allows an accurate reproduction of events without the drawbacks associated with time- or distance-based logging.
Note: The intelligent logging approach means the rate at which the data is logged will vary; we cannot specify a fixed logging rate such as “x times per hour” because the logging rate depends on the driving behaviour of the vehicle. The GO device will log as as many times as required to accurately represent the data being recorded while minimizing redundant data.
Technical details
The methodology used to determine the optimal time to log GPS points is a curve-based algorithm that utilizes the Ramer-Douglas-Peucker (RDP) algorithm. The purpose of the RDP algorithm is to create a simplified curve compared to the original data. This is done by removing trivial and redundant data points, and keeping only the relevant data points within the allowable error limit. The curve-based algorithm is used to determine which of the second-by-second GPS points need to be saved and transmitted to MyGeotab. The curve logging algorithm allows the GO device to keep only the points that are necessary in order to provide an accurate representation of the events logged. Accuracy is dictated by the predetermined allowable curve error values.
When the algorithm runs on the set of data points, it starts with the first and last points in the data set and automatically marks these as to-be-saved. It then considers the points between the first and last points; the data points will be continually divided until a line segment within the allowable error limit is obtained; this point will then be marked as to-be-saved. The algorithm will then run again for any points between the first point and the new point as well as any points between the new point and the last point.
The curve-based algorithm is run first on Latitude vs. Longitude and then on Speed vs. Time. The curve algorithm is run on speed values between the to-be-saved points predetermined by running the curve on position.
Based on the curve reduction method and the chosen allowed error values, the requirement is that the data between two saved GPS points will be acceptably linear in both position and speed.
GPS logging
When the curve algorithm is run on the data is dependent on several factors, which are listed below:
The curve buffer becomes full.
The actual position of the GO device differed excessively from the predicted position of the GO device.
Another event triggered the running of the curve.
Below is a list of parameters which utilize the curve algorithm for data logging.
Fault and status data logging
Curve logging on engine data
Where appropriate engine data is logged using the curve-based algorithm. The following is a list of the engine data now logged using the curve-based logic:
Battery Temperature
Brake Lining Remaining
Brake Temperature
Cab Interior Temperature
Charge State
Coolant Level
Coolant Temperature
Cruise High Speed Limit
Engine Cooling Fan Speed
Engine Oil Level
Engine Oil Life Remaining
Engine Oil Pressure
Engine Oil Temperature
Engine Speed
Fuel Alcohol Composition
Fuel Filter Life Remaining
Fuel Level
Maximum Road Speed Limit
Outside Temperature
Starter Brush Life Remaining
Starter Current
Tire Pressure
Transmission Oil Level
Transmission Oil Temperature
Washer Fluid Level
Vehicles will not necessarily return all of the above information; the list is based on all the supported engine protocols.
Total fuel used
Total Fuel Used is generic status data. No matter how fuel information is received from a particular vehicle, be it OBD2, J1708, J1939 or another diagnostic standard, a generic Total Fuel Used record will be saved after ignition off. An additional record, Device Total Idle Fuel Used, which is the fuel used while road speed is 0, is also saved on ignition off. Device Total Fuel Used (Telematics Device Code 2187) and Device Total Idle Fuel Used (Telematics Device Code 2188) are the parameters used to track fuel consumption.
Seat belt and odometer
Seat belt and odometer requests are proprietary on most passenger cars. It is Geotab’s goal to support seat belt and odometer across all the major vehicle manufacturers. If you are unable to obtain seatbelt or odometer requests for your vehicle, please contact Geotab Support. You can query the percentage of seat belt, odometer and other engine based data is supported for different vehicle types via MyAdmin.
Seat belt use is logged on status change: a value of 1 represents the seat belt unbuckled, while a value of 0 represents the seat belt buckled. Odometer is logged both on ignition on and ignition off.
Using third party devices in MyGeotab
Overview
This document describes how Geotab provides support for third-party devices in MyGeotab. Third-party devices are defined as any asset tracking device that is not manufactured or sold by Geotab but is used in conjunction with Geotab’s fleet management platform.
Device identification
A serial number will be provided for each device by Geotab. The serial number will be very similar to a standard Geotab GO device serial number. It consists of a 12 digit alphanumeric string and contains two pieces of important information:
a) What type of device this is
b) The unique identifier of the device
For example, a serial number for a custom device will look like this:
C1-800-000-0001
where C1 indicates the custom device type and 800-000-0001 is the unique identifier
Device type allocation
The device type in the serial number (for example C1) is specific to each third-party device and will be allocated by Geotab for a particular vendor (i.e. the person or company interested in third-party integration).
MyGeotab user interface
When entering a serial number, the device type will be used to show or hide features in the device editor. The standard set of fields for custom devices include:
Device description
Device identifier (not the serial number but third-party device identifier, as required)
Groups
Comments
Odometer
Engine hours
Work Hours
Time Zone
Systems integration
Geotab provides various systems (MyAdmin, install.geotab.com, etc.) that tie in closely with its line of GO products. By using a standardized serial number scheme as described above, Geotab will be able to provide additional services in the future with regards to third-party devices. For example, recording a successful installation or summarizing to a MyAdmin user how many third-party devices are linked to their account.
Costs
Geotab continues to invest in the software and services it provides to resellers and customers. There is a monthly fee charged to host devices on MyGeotab. Geotab will set up a rate plan for the reseller to issue monthly charges.
This fee includes:
Map licences
Future development and software improvements
Support
my.geotab.com hosting fees
Ongoing support for hosting custom devices
Nokia posted road speed maps
SDK support
API
The Third-Party Devices API is accessible through HTTPS and JSON. The following method calls are supported:
ProvisionDevice
ProvisionResult ProvisionDevice (string username, string password, int productId, string server)
This is a provisioning call that adds a device to MyAdmin and generates a Serial Number to be used for referencing the device or viewing it on MyGeotab. Parameter description:
string username — The third party email address to authenticate with.
string password — The third party password to authenticate with.
int productId — Integer code used to specify the type of the device to provision. This code will be provided by Geotab.
server — The name of the server used to process the GPS data. This can be left blank to automatically use the default value of “service.geotab.com:81”. Note that the port number is required.
This call is used to feed the device data to checkmate. Parameter description:
string username — The third-party email address to authenticate with.
string password — The third-party password to authenticate with.
List of ThirdPartyLogRecord containing the data.
Referencing Geotab.Checkmate.ObjectModel.dll will give access to all namespaces and objects needed to make the calls to the Third-Party Devices API.
Overview of needed namespaces and objects:
Namespace Geotab.Checkmate.Web contains classes through which the remote calls can be made.
WebServerInvoker — The object can be used to make the remote JSON call MyAdminAPI server via an HTTP/HTTPS GET command. A demonstration of its usage is provided in the .NET examples.
Namespace Geotab.Checkmate.ObjectModel contains objects used as parameters and return types for the remote calls. The list of the objects is:
ProvisionResult — Return type for provisioning call
string SerialNo — Device serial number generated by MyAdmin
bool IsSuccess — Is provisioning call was successful
string Error— Reason for provisioning call failure
ThirdPartyLogRecord — Used to describe the device data.
string SerialNo — MyAdmin assigned serial number of the device, which will be returned during device provisioning
DateTime DateTime — DateTime of the log
float Longitude — Longitude component of the GPS coordinates
float Latitude — Latitude component of the GPS coordinates
bool IsGpsValid — Are the coordinates valid
float Speed — Device speed
bool IsIgnitionOn — State of the Ignition
bool IsAuxiliary1On to IsAuxiliary8On — State of the auxiliary relays
AddGPSResult
bool IsSuccess — Is the sending of the results successful
string Error — What was the error during the sending of the data
Please refer to the provided example for the usage of the objects in the SDK .NET examples.
Developing Add-Ins
Overview
Add-Ins are used to extend the functionality provided by MyGeotab. An Add-In is just JavaScript, HTML and CSS loaded into the MyGeotab portal and resides directly inside the MyGeotab user interface. This allows third-parties to create a seamless user experience and provide solutions that would otherwise require the user to visit a different website altogether. Click here to find our sample Add-Ins.
Geotab Add-Ins can be of two types:
Pages
A custom page Add-In can be thought of as a complete web application inside your Geotab account. A custom page Add-In has access to the MyGeotab API and the current page state. With custom pages you can develop business-aware Add-Ins by combining MyGeotab data with your own APIs.
Buttons
Custom button Add-Inscan be included to perform different functions. Additional navigational buttons can bedynamically inserted inside certain areas of the MyGeotab user interface. This allows custom buttonAdd-Ins to provide a simple way for users to reach your custom page Add-In (see Image 1). Buttons can also be placed on pages to execute functionsfor automation of routine tasks, such as report generation (see Image 3).
Use cases
Consider a manager who regularly performs similar tasks each day. Their workflow may consist of comparing fleet metrics with local data from your software. By creating a custom page Add-In, you can combine both of these tasks into one easy–to–use page where all the information is readily available.
Another example is to quickly navigate between different areas of Geotab. A simple–to-use one–click button Add-In can be made for most pages. The button will guide the user between areas, and can optionally use the page state to automatically fill in URL parameters to run reports with a single click.
Requirements
The Add-Ins created can either have their source code embedded and stored on Geotab’s servers or can be stored externally using your own hosting provider or your own servers. Any referenced files must be publicly accessible.
Add-Inconfiguration files
Each Add-In created will have one configuration file. The configuration file is a JSON file (http://www.json.org) of keys and values which describes the Add-In, who is responsible for it, what source code it contains, and a digital security signature.
Table 1 — Add-In configuration file keys/values
Property
Description
Type
name
The name of this Add-In
String
supportEmail
Email address for support related to this Add-In
String
items
Array of custom pages and/or buttons (External references)
Array
files
Custom pages and/or buttons (Embedded code)
Object
key
Unique MyGeotab Add-In key assigned by Geotab
String
signature
Digital signature of the Add-In
String
version
Which Geotab API version to use
String
Note: If you do not know your MyGeotab Add-In key, please contact your authorized Geotab reseller for support.
The Add-In configuration file can specify the contents using either the Items, Files property, or a combination of both. It is recommended to use Items and externally referencing the source code to make development and debugging easier. When ready, the code can be embedded directly on Geotab’s servers.
Example Add-In configuration file
The Add-In configuration file below demonstrates how to define a simple Add-In which references an HTML page specified by its URL. Any CSS or JavaScript which is required by the Add-In would be specified in the referenced HTML.
Listing 1 — A simple Add-In configuration JSON file
{
"name": "My First Geotab Add-In",
"supportEmail": "myname@mycompany.com",
"version": "1.0",
"items": [{
"url": "https://my3.geotab.com/g560/customerPage1.html",
"path": "ActivityLink",
"icon": "https://www.geotab.com/geoimages/home/icon-solutions.png",
"menuName": {
"en": "English Menu Text",
"fr": "French Menu Text"
}
}],
"files": { },
"key": "12345-MYAPIKEY",
"signature": "12345-MYSIGNATURE"
}
Test the example above by navigating to Administration → System → System Settings → Add-Ins. Select New Add-In and paste the example in the configuration tab. Be sure to select save then refresh the page.
Each Add-In can create a navigation entry in the left hand side menu. This allows quick and easy access to all of the Add-Ins. The placement of the navigation entry for the Add-In is specified in the configuration file, relative to another built-in navigation entry. In the section below, a navigation entry is placed directly after the Activity entry. A user with English as their interface language will see “English Menu Text” as the label. Note that we show only two properties for brevity.
{
"path": "ActivityLink",
"menuName": {
"en": "English Menu Text",
"fr": "French Menu Text"
}
Image 1 — Modified left hand side menu
The Add-In navigation entry can be placed after any of the following built-in values:
GettingStartedLink
ActivityLink
EngineMaintenanceLink
ZoneAndMessagesLink
RuleAndGroupsLink
AdministrationLink
To place the navigation entry as a sub-menu entry in one of the main entries place a slash (“/”) character after the name. The custom entry will be the first item inside the sub-menu.
For example, by changing “ZoneAndMessagesLink/” as the value for the “path” key:
"path": "ZoneAndMessagesLink/",
This will insert the custom navigation entry as follows:
Navigation entries cannot be set at the third level (sub-sub-menu) and below. If done so by the steps outlined above, the entry will simply appear as a non-formatted bullet point in the menu.
Note: A user may not have access to some entries of the left hand side menu. The custom navigation entry will be shown after the nearest entry which is accessible to them.
Listing 2—Add-Inconfiguration section for submenu
To create a sub-menu, add to the items array a special JSON object that looks nearly identical to the page item — with the exception of the URL property.
To place buttons inside a new sub-menu, use subMenuPath property as illustrated in Listing 3. This sub-menu will be shown only if there are at least two items inside it.
Host files on Google Drive by creating a folder to place the html, js and css files for the Add-In. Share this folder with the “Anyone on the internet can find and view” setting. While your browser is on the shared folder, copy the part of the URL after the “folders/”; which in the case of:
and by placing it in a browser address bar verify that your Add-In’s folder can be viewed. Next, construct the URL for your Add-In’s startup page like the example:
Use the resulting URL for the Add-In configuration file.
Referencing source items
Each Add-In can define zero or more items as part of its configuration file. An item is a collection of keys and values which represent a page or a button.
Table 2 — Parent menu item
A parent menu item defines a new menu item and where it should reside within the menu hierarchy. It does not have a URL that activates a page and serves only as the container for sub-menu items.
Name
Description
Type
menuId
A unique identifier for this menu. This string value of your choice but should be unique. See built–in ones above “GettingStartedLink”, “ActivityLink”, etc.
String
path
Specifies where in the menu hierarchy this menu item should reside. It will follow the menuId specified or become a child item if a trailing slash is provided, such as “ActivityLink/”.
String
menuName
An object containing key–value pairs for the text that appears on the menu item. The key is the language and the value is the text, for example: {“EN”, “New menu item”}.
Object
icon
A URL to the image (svg, png, jpg, etc.) that is placed in front of the menu item. Note that the current image size is 32×32 but it is recommended that SVG icons are used to allow for scaling.
String
Table 3 — Menu item
Name
Description
Type
URL
A URL to the HTML page to load when clicking on this menu item.
String
path
Specifies where in the menu hierarchy this menu item should reside. It will follow the menuId specified or become a child item if a trailing slash is provided, such as “ActivityLink/”.
String
menuName
An object containing key value pairs for the text that appears on the menu item. The key is the language and the value is the text, for example: {“EN”, “New menu item”}.
Object
icon
A URL to the image (svg, png, jpg, etc.) that is placed in front of the menu item. Note that the current image size is 32×32 but it is recommended that SVG icons are used to allow for scaling.
String
Table 4 — Button item
Name
Description
Type
page
Which built-in page to place the button on
String
click
A URL to a JavaScript file which is executed when the button is clicked
String
buttonName
An object containing key value pairs for the text that appears on the button. The key is the language and the value is the text, for example {“EN”, “New menu item”}
Object
icon
Reference to the image for placing it in the button label
String
At least one language is required in each item definition. The following language options are currently supported in MyGeotab:English (“en”), French (“fr”), German (“de”), Spanish (“es”) or Japanese (“ja”).
Note: Reference to the image can be an external URL such as: https://mysite.com/images/icon.png; or a link to the image from the images folder of your Add-In.
When using the items property to include your source code exclusively, you can set the files property an empty object using “{ }” as seen in Listing 1.
Every Add-In has a JavaScript objectwhich is set in your addin.js file. For example, the Add-In class name “myaddin” is provided by the following JavaScript entry point:
The name you provide should be unique for each database the Add-In is deployed to and should take care to avoid invalid include characters in the name. Additionally, when referencing Add-Ins hosted externally, the absolute path to the Add-In should not include the following characters anywhere in their URL:
“-” The dash symbol
“@” The “at” symbol
“#” The hash symbol
For example, the following is an invalid absolute URL due to its dashes and will not be loaded correctly by MyGeotab:
When developing a custom page or button Add-In, you have the option to embed the source code for your project in the JSON configuration file. When using this method, there is no requirement to host your own HTML, CSS or JavaScript files as they will be converted into strings and written inside the configuration file itself.
Listing 3 — Add-In configuration file using embedded source code
Note: Please be aware that some characters may need to use HTML escape characters (HTML ISO-8859-1 Reference) and Character Reference for the overall JSON object to be validated.
By reproducing the previous example, there would be two folders, one named “js” and the other “css”. Inside the folders are two JavaScript files and one CSS stylesheet; respectively.
The user experience of your custom Add-In can be enhanced by including images in the configuration file. This can be performed in two ways; see Listings 4, 5, and 6 below.
Listing 4 — Absolute path to image in HTML
Referencing an external image using an absolute URL in the HTML or CSS.
Listing 6 — Add-In configuration file with Base64 encoded image
The other method is to embed the images along with the rest of the source code in the markup. First the images will need to be encoded using Base64 encoding (http://en.wikipedia.org/wiki/Base64), then the references to the image files replaced with the encoded version directly in the HTML or CSS.
Add-Ins can include references to external libraries that have been custom developed or to existing libraries such as jQuery. This is performed in the traditional way by including a <script> tag to the URL of the file.
Keep in mind that the end-user using the Add-In will be viewing your Add-In from a Geotab server. The files referenced must be publicly available on the Internet. Firewalls cannot be configured with a specific IP address for the Geotab server as the address may change in the future.
References to external source files can either be absolute URLs such as the example in Listing 7 or can be relative references to local files as demonstrated in Listing 3.
Listing 8 — Avoiding CSS naming conflicts
When referencing the CSS files, keep in mind that naming conflicts are possible. Geotab’s outer framework defines a number of CSS styles for common HTML tags which the custom Add-In may inherit. When designing HTML tags, it is recommended to prefix the HTML tags with a common name when they are stylized with the CSS.
When designing a custom page Add-In,it is important to understand the JavaScript events that take place on Geotab’s servers. The user–defined JavaScript code must supply an entry point object which will be created with a predefined parameter signature. From these parameters a signed–in Geotab API object will be received, along with the page state and a callback synchronization function.
Every page on Geotab’s servers, including custom page Add-Ins, have the following three methods called during their lifecycle:
Table 5 — Add-In lifecycle methods
Method
Description
Signature
initialize
Called only once when your custom page is first accessed. Use this method to initialize variables required by your Add-In.
function(api, state, callback) { … }
focus
This method is called after the user interface has loaded or the state of the organization filter is changed. Use this method for initial interactions with the user or elements on the page.
function() { … }
blur
This method is called when the user is navigating away from your page. Use this method to save any required state.
function() { … }
Visual diagram
Understanding the workflow and methods called will help you design a responsive custom page Add-In. Keep in mind that your initialize method will only be called once, unless the user explicitly refreshes their web browser. When the user interface is ready, the focus method will be called. Finally, when the user is navigating away from your custom page Add-In, theblur method will be called, completing the Add-In lifecycle.
Image 2 — Add-In lifecycle workflow diagram
Lifecycle implementation
The following code can be used as a starting point for a custom page Add-In. All of the lifecycle methods are defined and the optional focus and blur methods will be called due to the callback method being called in the initialize method.
Use the commented area to define and then assign variables in the scope of the Add-In. Each of the Add-Ins will need to define its own unique namespace with the prefix geotab.addin (note that the namespace is not hyphenated). In the example below the full namespace is geotab.addin.myCustomPage1.
Listing 9 — HTML and JavaScript entry point example
<!DOCTYPE html>
<html>
<head>
<title>Custom Page Add-In</title>
<script>
geotab.addin.myCustomPage1 = function(api, state) {
// Initialize required Add-In variables
// Example:
// var element = document.getElementById("myButton");
// if (element) {
// element.addEventListener("click", function (event) {
// event.preventDefault();
// alert("Action performed");
// });
// }
return {
initialize: function(api, state, callback) {
callback();
},
focus: function() {
// User interface is available
},
blur: function() {
// Save any Add-In state
}
};
};
</script>
</head>
<body>
<button id="myButton">Do Action</button>
</body>
</html>
Custom button Add-Ins
Custom button Add-Ins allow you to extend the capabilities of a built-in Geotab page by appending a new button the top menu of the page. When a user clicks the custom button Add-In, the JavaScript method that has been defined will be called. This JavaScript method has access to the event which was generated by the click, the Geotab API under the credentials of the current user and the page state variables.
Button Add-In configuration file
The following example adds a custom button Add-In to the live map page. When clicked, the button will redirect the user to the vehicles page. Use this example as a starting point for creating your own custom buttonAdd-Ins.
The exact position of the custom button Add-In within a built-in page is defined by the developer. For instance, in Image 3, a new button labelled Perform Action is added to the toolbar of the live map page.
Note: This example uses external references to the source code. Similar to custom page Add-Ins, the Files property of the configuration file can be used to embed the source code on the Geotab servers.
Image 3 — Custom button Add-In on live map page
Use cases
The action your custom button Add-In performs is decided by your specific business requirement.The following are example actions that can be implemented:
Almost any page is available to have a custom button Add-In added to it. Use a web browser’s address bar to find the correct value for the Page property. Geotab pages will have a trailing hash (“#”) symbol followed by the page name. Determine the page name and then set the “page” value of your custom button Add-In configuration file to that value.
When a custom button Add-In is clicked by a user, it will execute a predefined method from the JavaScript file referenced. This methods provides the button action with access to the generated event, the Geotab APIas the signed-in user, and the page state.
Note: To avoid conflicts with multiple Add-Ins enabled on an account, be certain to create unique namespaces for each Add-In.
The state object is a powerful tool for creating navigational components by changing the current page state. The state object has access to a number of methods as follows:
Table 6 – Geotab page state methods
Method
Description
Parameters
Return Type
getState
Gets an object the current URL state
None
Object
setState
Sets the current URL state. The object parameter is a modified state retrieved from getState.
Object
Void
gotoPage
Redirects the user to another page with optional parameters.
Checks whether the current user has the security clearance to view a page by its # (hash) value.
Example:
var result =
state.hasAccessToPage(“map”);
String
Boolean
getGroupFilter
Gets an array with ids of the selected groups in the organization filter.
Example:
var result = state.getGroupFilter();
None
Array
Note: The second parameter to the gotoPage method is optional and is used for query string parameters.
Complete integration example
Using all the concepts outlined in this document, the following is a complete integration example which creates a custom page Add-In with real-world functionality. In this example, the custom page has JavaScript methods that make requests using the Geotab API to retrieve the current vehicles on your account. The result of the API request is shown on the custom page in a list. Finally, when the user leaves the page, the custom page performs cleanup during the lifecycle methods.
Note: For the purpose of this example, the integrationExample.css and integrationExample.js are empty files.
Source code
Listing 13 — HTML and JavaScript code for integration example
When developing Add-Ins, the use ofGoogle Chrome and its Developer Tools window is recommended. To open the Chrome Developer Tools on Windows, press CTRL + SHIFT + I; on a Mac, press CMD + OPTION + I.
The contents of console.log(“…”) statements can be examined using the Developer Tools, the timeline of XML HTTP requests can be viewed, and breakpoints to step through the JavaScript source code can be created.
It is also recommendedto read Google’s extensive learning resources available on using Chrome Developer Tools to get started debugging or learn about the advanced features they have available.
Drive Add-Ins
Note: Geotab Drive Add-Ins are in preview release and subject to change
Overview
The MyGeotab Add-In structure can be applied to the Geotab Drive application as well, providing you the ability to extend the functionality for drivers in an environment with sensors (e.g. geolocation and acceleration) and actuators (e.g. voice alerts and notifications). This environment must also been completely operable in an offline state — so your Add-In must be able to handle having no internet connection, or sleeping in the background of the mobile device.
Please read the Developing Add-Ins guide first before attempting a Geotab Drive Add-In.
All Add-Ins that have been designed to work with MyGeotab will work on the Geotab Drive app as well. Your Add-In will be completely downloaded for all referenced links, images, and scripts upon user login. This way, as the user is authenticated over the internet — they will have your Add-In with them as they travel or disconnect from the network. If your Add-In requires dynamic loading of CSS, images, or JavaScript — these requests will fail if the user does not have a network connection. As such you should either: include all dependencies on creation of the Add-In, explicitly link to them, or provide a fallback if state.online returns False. Geotab Drive Add-Ins will also display differently, on both the dashboard and the menu.
To make an Add-In on the Geotab Drive app, the item in your configuration file must have a path that equals “DriveAppLink/” (including a trailing forward slash). The menuName, url, and version will remain unchanged. For example:
Note: The array of items also allows you to have one link item in MyGeotab, and another link item to Geotab Drive
API and State Documentation
Inside the Geotab Drive app, we provide the same api and state properties for your initialize method that we do for our normal Add-Ins. In addition to this, we provide you with properties and methods to allow access to mobile device sensors/actuators. See Table 1 below for a list of the properties and methods provided.
Table 1 — Geotab Drive additional properties and methods
Description
Parameters
Return Type
api.mobile.exists
Returns true if Geotab Drive is running within a native application, and false if just as a HTML5 web application
None
Boolean
api.mobile.getVersion
If api.mobile.exists(), gets the Geotab Drive version from the native application
None
String
api.mobile.speak
If api.mobile.exists(), uses the text to speech functionality on the mobile device
String
Void
api.mobile.notify
If api.mobile.exists(), will add a notification to the top bar of a native operating system
Example:
api.mobile.notify(“Fill up your vehicle”, “Low on gas”)
TextToSpeechContent has been renamed to GoTalkContent and RelayContent has been renamed to IoxOutputContent * .Net users will require a dll update
January (5.7.1601.XXX)
New recipient types added that will send even if there is a delay in data. (BeepTenTimesRapidlyAllowDelay, BeepThreeTimesAllowDelay, BeepThreeTimesRapidlyAllowDelay , TextToSpeechAllowDelay) * .Net users will require a dll update
Access to third party messages via API. * .Net users will require a dll update
New Objects
IoxAddOn
KnownIoxAddOnType
IoxAddOnSearch
IoxOutputContent
GoTalkContent
2015
December (5.7.1512.XXX)
Fixed operator overloading for Id object in .Net dll (id1 == id2 is the same as id1.Equals(id2)) – *If you are using dll version 5.7.1508-1511 this will require a dll update.
ViewMarketplacePaidItems: Allow user to see paid Marketplace items
DeviceAdminDeleteUnplugReplace: Access to removing vehicle, unpluging device, and replacing device.
*If you are using dll version 5.7.1508-1510 this will require a dll update.
September (5.7.1509.XXX)
New SDK. Featuring the new SDK Runner, new methods and objects (click here to see the preview items)
Code snippets in the reference documentation. Now you can see working examples of the methods as they are used in the runner.
.Net users will require a .DLL update to access the latest features.
New Methods:
CreateDatabase
DatabaseExists
GenerateCaptcha
GetVersionInformation
New Objects:
AnnotationLog
AnnotationLogSearch
CaptchaAnswer
CaptchaException
Color
CompanyDetails
DVIRLog
DVIRLogSearch
DiagnosticCategory
DistributionList
DuplicateException
DutyStatusAvailability
DutyStatusAvailabilityDuration
DutyStatusAvailablitySearch
DutyStatusLog
DutyStatusLogSearch
DutyStatusLogType
DutyStatusViolation
DutyStatusViolationSearch
DutyStatusViolationType
EntityWithVersion
FuelEconomyUnit
FuelEvent
FuelTransaction
FuelTransactionProvider
HosRuleSet
IncludeGroups
InvalidMyAdminUserException
MapView
NameEntity
NameEntityWithVersion
RadioDownloaderSearch
Recipient
RecipientType
RegistrationException
Search
ShipmentLog
ShipmentLogSearch
TextMessageContentType
Trailer
TrailerAttachment
TrailerAttachmentSearch
TrailerSearch
VersionInformation
VolumeUnit
Deprecated
BingMapStyle
EngineType
EngineTypeSearch
StatusDataRequestContent
August (5.7.1508.XXX)
DriverChangeSearch received new search points including: DeviceSearch, DriverSearch, FromDate and ToDate. Checkout the API Reference for more details
DistributionList is now supported by the API. Checkout the API Reference for more details. Some related objects are still pending support (Notification, NotificationTemplate, BinaryData)
When searching for Zones you can now specify a traversal method of the group tree. You can choose to include just the specified element, just the ancestors, just the descendents, or both ancestors and descendents. See the ZoneSearch object in the API Reference for more details
Fix documentation for object properties
Added KnownIds: DiagnosticDeviceTotalIdleFuel
Added FuelTransaction API (Beta)
HOS/DVIR objects supported in API. Key objects are AnnotationLog, DVIRLog, DutyStatusAvailability, DutyStatusLog, DutyStatusViolation, and ShipmentLog. Checkout the API Reference for more details
Added Groups property to StatusDataSearch. This allows searching for status data for devices in the supplied groups. This does not return interpolated results
Added from/to date search to UserSearch object. Checkout the API Reference for more details
API Reference, objects now show properties of from inherited classes. For example GoDevice extends Device and will show properties of GoDevice and Device in the documentation
New condition types added – .Net will require dll update
March
Add KnownId for DiagnosticDeviceTotalIdleFuelId – .Net will require dll update
February
Get all zones now populating points correctly (see forum post)
Fixed TimeZoneInfo isDailightSavingsSupported always false using .Net API wrapper
Units of measure have been converted to use Known Id’s (see forum post)
Adding, setting and removing of some entities has been disabled via the API. Exception Event, Trip, Status Data, Fault Data, Log Record with exceptions for adding odometer and engine hours adjustments and dismissing faults
Clearer documentation of date and long values in API Reference
Data Feed section added to Guides portion of SDK (see document)