About this tutorial
The scriptr.io team has implemented a connector to simplify and streamline the way developers access Carvoyant’s APIs from scriptr.io. Using a few native objects, developers can directly access cars’ data from within their scripts and thus, create sophisticated IoT applications and processes around connected vehicles.
In this tutorial, you will learn how to sign-up to scriptr.io (if not already done) and write your first script to get familiar with the web IDE. Once this is done, we will see how to check-out the carvoyant connector from Github into your scriptr.io workspace then we will start implementing a sample application, based on the carvoyant connector.
Table of contents
- Signing-up to scriptr.io
- Writing scripts
- Importing the Carvoyant connector to your scriptr.io workspace
- Configure the connector
- Obtain an authentication token for a carvoyant driver
- Getting familiar with the carvoyant connector
Signing-up to scriptr.io
There are many simple ways to create an account on scriptr.io: you can either sign-in using your GitHub, Facebook or Twitter credentials, or fill in the sign-up form. Once signed-in, you will be redirected to scriptr.io’s workspace – the Web IDE – to implement your scripts.
Writing scripts
Scripts are the foundation of your applications. Write them to implement any back-end logic for your IoT application, leveraging the many native objects and modules to accelerate development.
Create your first script
Click on the New Script button of the workspace. Type “MyFirstScript” (or any other name) in the Set Script Name place holder, then hit “enter” or click on the code editor area. In the latter, simply type return "Hello world";
for now, and click on the Save button to save your work.
Since all scripts that you implement in scriptr.io are potential APIs, the one you have just created is now publicly accessible on the following endpoint: https://api.scriptrapps.io/MyFirstScript
,
Test your first script
You can test your scripts either from scriptr.io’s Workspace or from the command line. We will describe both ways in the below.
Testing from the workspace
Click on the Run button at the right top corner of the workspace. Execution results are displayed in the Console window at the bottom of the workspace, and it should contain something like the following:
>> curl -X POST -F apsws.time=1434632687831 -H 'Authorization: bearer ' 'https://api.scriptrapps.io/MyFirstScript' { "metadata": { "requestId": "b9433975-a9a7-4bbc-8576-1f6d8c0155a9", "status": "success", "statusCode": "200" }, "result": "Hello world" }
Notice that executing your code requires you to pass an authentication token ( in the above example). You can also choose to grant wider access to your script by turning it into an anonymous script. For that, you will need to check the Allow anonymous requests checkbox on the right top corner of the code editor. Requests sent to anonymous scripts will need to pass an anonymous token instead of the aforementioned access token.
You can retrieve and manage your scriptr.io access and anonymous tokens by clicking on your username on the top left corner of the screen, then click on Account. Read more
Testing the Script from the command line.
You can also double check that you can hit your script by executing the following command in your shell environment (make sure to replace with the actual value of your own scriptr.io token)
$ curl "https://api.scriptrapps.io/MyFirstScript?auth_token=YOUR_TOKEN;apsws.time=123456789"
Notice that in the above, we passed the authentication token as a parameter of the request () instead of sending it using the HTTP Authorization header. scriptr.io accepts both alternatives.
If everything is correct, you should obtain the following result from scriptr.io, once again.
{ "metadata": { "requestId": "4027aad4-5996-4eae-b38e-57929d249104", "status": "success", "statusCode": "200" }, "result": "Hello world }
Import the Carvoyant connector to your scriptr.io workspace
In order to import the carvoyant connector to your workspace, you need to connect to Github as scriptrdotio. From the workspace, click on your username (top left corner of the screen) then click on settings. This opens a form where you can configure your connection to the scriptrdotio Github account.
As shown in the above screenshot, enter “scriptrdotio” as the owner name, enter an access token that you generate for your account on Github as the value of the Access Token field. Set “libraries” as the value of Repository name and “master” as the value of the Branch field. Keep the Path field empty, then click on Save then close
You should see the whole list of scriptr.io libraries added to the Synchronize area on the left side of the screen. In order to check-out the “carvoyant” library into your workspace, right-click on carvoyant then on Update (see below screenshot).
Make sure that the carvoyant library is now in your workspace by clicking on the My scripts tab. The scripts should appear in the carvoyant folder.
The carvoyant connector needs the oauth2 library in order to handle authentication against carvoyant. Therefore, click on the Synchronize tab once again to display the available libraries, right click on oauth2 and once again, click on Update, in order to check-out the oauth2 library into your scriptr.io workspace.
Now make sure to modify the Github settings in order to point to your own Github account. Head to the scriptr.io’s Github settings and replace the owner name with your own Github username, and replace the repository name with the name of one of your repositories. This will allow you to commit the carvoyant code into your own repository.
Configure the connector
You first need to configure the oauth2/config file (make sure that you already have created a developer account at carvoyant)
- Copy/paste the values of your Client (Consumer) Key to the client_id variable
- Copy/paste the Client (Consumer) Secret to the client_secret variable
- Make sure that the value of the response_type variable is set to “token”
- Set the value of the apiUrl to the correct carvoyant endpoint (sandbox or production)
- Set the value of the app variable to a name of your choice
- Keep the apiVer variable empty (empty string “”)
Obtain an authentication token for a carvoyant driver
In order to run tests on your application, you need to create a carvoyant driver (end user) account. Once you are done, follow the steps hereafter in order to obtain an OAuth token for the driver. The token is automatically stored into, and further retrieved from, your scriptr.io storage.
Step 1
Invoke the /oauth2/getRequestCodeUrl script, passing the username parameter. The username is the carvoyant driver’s username. The result returned by the aforementioned script should resemble the following:
>> curl -X POST -F username=edison -F apsws.time=1434722158021 -H 'Authorization: bearer ' 'https://api.scriptrapps.io/oauth2/getRequestCodeUrl' { "metadata": { "requestId": "45753a7f-a2b6-4378-a8e1-3bbddced9694", "status": "success", "statusCode": "200" }, "result": "https://sandbox-auth.carvoyant.com/OAuth/authorize?client_id=atkchwp98j3whpg6cjgwt98h&response_type=token&state=02a0e4&redirect_uri=https%3A%2F%2Fapi.scriptrapps.io%2Foauth2%2FgetAccessToken%3Fauth_token%3SKzM1RnYwAzc4Mg%3D%3D%26state%3R02a1e4"" }
Step 2
Issue a request to the obtained URL. This redirects your end user to the carvoyant login page, where he has to enter his credentials then authorize the application on the requested scope. Once this is done, carvoyant automatically calls back the carvoyant/getAccessToken script, providing it with an access and a refresh token that it stores in your scriptr.io’s global storage. The tokens are also returned by the script.
Getting familiar with the carvoyant connector
Most of the time, you will only use instances of two specific classes of the carvoyant connector:
- The “User” class, which wraps the APIs that manipulate carvoyant users’ data
- The “Vehicle” class, which wraps the APIs that manipulate carvoyant vehicles’ data
Actually, the User class is mainly what you need when dealing with vehicles of a particular user, since you can obtain an instance of the Vehicle class from the former.
E-mail me the nearest gas station when fuel is low
Let us start by creating a simple script that loops through the list of a carvoyant user’s vehicles, read the fuel level of each vehicle on the list and, if the fuel level is lower than a certain minimum threshold, send a email to the vehicle’s user with the list of nearest gaz stations.
// require the 'http' module, which allows you to invoke third party APIs var http = require("http"); // require the 'user' module, where the User class is defined var userModule = require("modules/carvoyant/user.js"); // create an instance of User from the username of a carvoyant driver (for whom you obtained an auth token) var user = new userModule.User({username:"edison"}); // get the list of vehicles owned by this user and known to carvoyant var vehicles = user.listVehicles(); // loop through the list of vehicles var alertedCars = []; try { for (var i = 0; i < vehicles.length; i++) { // retrieve the current Vehicle instance var vehicle = user.getVehicle(vehicles[i].vehicleId); // get the current vehicle's fuel level var fuelLevel = vehicle.getFuelLevel(); // compare the fuel level to the min threshold if (fuelLevel < 100) { // get the user's email address form his account info var accountsList = user.listAccounts(); var email = accountsList.accounts[0].email; // we assume the user has one account // invoke the NREL APIs (https://developer.nrel.gov) to get the list // of fuel stations near the vehicle's latest location (replace the api key with yours) var vehicleInfo = vehicle.getInfo(); if (vehicleInfo.lastWaypoint) { // check if there is a known last location // prepare the request var queryObject = { "url": "https://api.data.gov/nrel/alt-fuel-stations/v1.json", "params": { "limit":1, "api_key": "EXS3dziSzzrDg9yM7D1Emnyt7MXPBk1Wk85thvHD", "latitude": vehicleInfo.lastWaypoint.latitude, "longitude": vehicleInfo.lastWaypoint.longitude } }; // invoke the third party API var fuelStationsApiResponse = http.request(queryObject); var fuelStations = (JSON.parse(fuelStationsApiResponse.body))["fuel_stations"]; // send the list of fuel stations by email to the user, using the built-in 'sendMail' object var emailConfig = { "to": email, "fromName": "Carvoyant&scriptr.io", "subject": "Fuel alert", "body": (JSON.stringify(fuelStations)).replace(/,/g, ' ') }; sendMail(emailConfig.to, emailConfig.fromName, emailConfig.subject, emailConfig.body); // push a information string into the alertedCars array alertedCars.push("sent alert to vehicle " + vehicleInfo.vehicleId); } } } return alertedCars; }catch(exception) { return exception; }
We hope this first introduction will allow you to get started with scriptr.io and the carvoyant connector.
Remember to check the list of available objects and methods in the tests sample script and to check our documentation. You can also contact our support (support@scriptr.io) and post any question to our forum (coming soon).