Using scriptr.io with MODE

As previously mentioned, webhooks are convenient means to integrate sophisticated logic into your IoT application. You can implement this logic using your favorite language and platform, then expose it as an HTTP service to MODE. You will also need to cater for your service’s scalability, availability and quality; as well as tackle the required underlying software infrastructure (such as messaging, persistence, integration, etc.).

Since the real value of your IoT application relies in the business logic you implement and not in the latter concerns, it is important for you to spend your time and effort on elaborating the former. One way of doing this is by leveraging the services offered by scriptr.io to implement this logic.

scriptr.io is a secure cloud-based scripting engine for implementing IoT applications in JavaScript. It provides developers with many services (orchestration, persistence, messaging, scheduled execution, etc.) and connectors (Nest, wit.ai, fitbit, etc.) to accelerate their development pace. Once registered to scriptr.io you can start implementing your script with their Web IDE and expose them as APIs (read more about it in their online documentation).

In this tutorial, we will explain how to implement scripts using scriptr.io and integrate them into the MODE cloud via webhooks.

Setting up scriptr.io

Creating your account on scriptr.io is pretty straightforward: 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 workspace - which is the Web IDE they provide - to implement your scripts.

Screenshot - script.io Workspace

Creating a New Script

  1. Click on the New Script button of the workspace.
  2. Type MyFirstDevice (or whatever name you choose) in the Set Script Name place holder, then hit “enter” or click on the code editor.
  3. In the code editor area, simply type return "My first device"; 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/MyFirstDevice, which will be called later on by the MODE cloud.

Testing the Script from scriptr.io’s Workspace

  1. Click on the Run button at the right top corner of the workspace.
  2. Execution logs are displayed in the Console window at the bottom of the workspace, and they should contain something like the following:
>> curl -X POST  -F apsws.time=1434632687831 -H 'Authorization: bearer <AUTH_TOKEN>' 'https://api.scriptrapps.io/MyFirstDevice'
{
  "metadata": {
    "requestId": "b9433975-a9a7-4bbc-8576-1f6d8c0155a9",
      "status": "success",
      "statusCode": "200"
  },
  "result": "My first device"
}

Notice that executing your code requires you to pass an authentication token (<AUTH_TOKEN> in the above example). You will need to provide this token when communicating between MODE and scriptr.io . On a side note, 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 at the top right corner of the code editor. Requests sent to anonymous scripts will need to pass an anonymous token instead of the aforementioned access token.

A Note on scriptr.io’s Authentication and Anonymous Tokens

  • You can retrieve and manage your scriptr.io access and anonymous tokens by clicking on your username at the top left corner of the screen, then click on Account.
  • To learn more about scriptr.io’s tokens, see their online documentation.

Testing the Script from Your Shell

You can also double check that you can hit your script by executing the following command in your shell environment (make sure to replace <AUTH_TOKEN> with the actual value of your own scriptr.io token)

$ curl "https://api.scriptrapps.io/MyFirstDevice?auth_token=<AUTH_TOKEN>&apsws.time=123456789"

Notice that we passed the authentication token as a parameter of the request (<AUTH_TOKEN>) 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": "My first device"
}

Setting up a Device

Now that you are a bit more familiar with scriptr.io, let’s go on to create your device on the MODE cloud.

If Follow the instructions provided in:

  1. Create a Project
  2. Define a Device Class
  3. Instantiate a Device
  4. Add Device to Home

You can get the device ID from the device details screen. We will use it later, when writing the webhooks handler code on scriptr.io.

Screenshot - Device Details

Setting up Webhooks

Use the MODE Deveoper Console to add a Webhooks Smart Module to your MODE project, as described here.

For the newly added Smart Module, you need to specify an Event Webhook by pasting the URL to your scriptr.io script, as follows:

https://api.scriptrapps.io/MyFirstDevice?auth_token=<AUTH_TOKEN>&apsws.time=123456789

Again, make sure to replace <AUTH_TOKEN> with your actual scriptr.io auth token (or your anonymous token, if you checked the Allow Anonymous Requests checkbox in the scriptr.io editor).

Obtaining a Project API Key

You will also need a project API key to access MODE when implementing the actual code of the webhooks handler in scriptr.io. To provision an API key, go to Settings of your MODE project. In the API Keys section, click the New button to add a new key:

Screenshot - Creating API Key

Then click the entry for your newly created API key to reveal the actual token assigned to this key:

Screenshot - Creating API Key

Implement the Webhooks Handler on scriptr.io

As mentioned in the first section of this document, you can implement the webhooks handler’s logic using scriptr.io. In the following example, we will write a simple handler that echo messages between Device and scriptr.io through the MODE cloud.

Copy and paste the following code into your scriptr.io workspace, replacing the content of the “MyFirstDevice” script you created at the beginning of this document.

// The http module is a native scriptr.io module that allows you to issue http requests to any REST API
// You can read more on how to use the http module here: https://www.scriptr.io/documentation#documentation-2-modulesModules

var http = require("http");

// this method builds a request towards your device on the MODE cloud platform
var Device = function(deviceId, token, host) {
  this.deviceId = deviceId;
  this.token = token;
  this.host = host;
}

Device.prototype.sendCommand = function(action, params) {
  var command = {
    "action": action,
    "parameters": params
  };

  var postData = JSON.stringify(command);

  // Invoke the request method of the http module to issue a request towards the MODE cloud API
  return http.request({
     // this is the url of the targeted MODE cloud API
    "url": "https://" + this.host + "/devices/" + this.deviceId.toString() + "/command",
    method : 'PUT',
    headers : {
      "Content-Type": 'application/json',
      "Authorization": 'ModeCloud ' + this.token
    },
    "bodyString": postData
  });
}

var deviceId = <Device ID>;
var hostname = 'api.tinkermode.com';
var token = '<MODE API Key>';

var device = new Device(deviceId, token, hostname);
var json = request.body ? request.body : {};

return device.sendCommand("scriptr.io", json);

In the above code, you need again to replace <Device Id> and <MODE API Key> with their corresponding values you obtained in the previous steps.

Click the Save button or press Ctrl+S on your keyboard after updating your code.

Now you are ready to test your webhooks handler!

Test the Webhooks Handler

To test the webhooks handler, we are going to trigger an event from the Device Simulator. Upon receiving the event, MODE will invoke the code on scriptr.io by calling the event webhook. And finally, the handler script will issue a command to the device.

So let’s go back to the device details screen on the MODE Developer Console and launch the Device Simulator. In the OUTGOING: EVENTS panel, enter the event type and data as follows:

Screenshot - Sending Event

Click TRIGGER EVENT. If the setup is correct, you should see a new command logged in the INCOMING: COMMANDS panel of the simulator. Click Details to reveal the details of the command, like the following:

Screenshot - Command Details

Conclusion

Congratulations! If you went this far, this means that communication between the MODE cloud and scriptr.io succeeded in both directions. The device event sent to the MODE cloud was delivered to scriptr.io. Then scriptr.io echoed it in a command, via MODE cloud, back to the originating device.