IoT applications involve the collaboration and orchestration of many – different – devices, many of which produce a large amount of data stemming from the sensors they ship with. In most cases, these data have a vital importance for the organization that is running the IoT application:

  • Data can be used to build dashboards to monitor the behavior of the concerned devices or to monitor the environment where the devices are operating, allowing for the identification of potential glitches and reacting accordingly,
  • Running analyses on the available historical data can lead to the identification of event patterns and to the production of predictive models used in decision making, process improvement, etc.

Since scriptr.io aims at facilitating and accelerating the implementation of scalable Enterprise IoT applications, it naturally provides you with means to seamlessly connect to analytics services. We notably provide a connector to Initial State, which can be leveraged from within scripts to allow sending device events into event buckets, to further use them to create dashboards and statistics.

About Initital State

Initial State is an IoT data analytics and data management service that turns sensor and event data into information that matters, by making it easy to visualize, interact and take action with data from internet connected devices. More particularly, Initial State provides you with user-friendly, configurable and embeddable dashboards, to monitor and analyse your IoT data.

A sample application

In this paragraph we demonstrate how easy it is to generate a dashboard for a precision-farming application, using scriptr.io and Initial State. In our example, we assume that we have deployed a device that detects the temperature and water flow near crops. The values of the temperature and water flow are sent to a script deployed on scriptr.io through Web Sockets. Don’t worry if you do not have a device for now: we provide you with a simple simulator you can run in your browser, at the end of this tutorial.

Exposing an API to the devices

As a first step, we thus implement a very simple script on scriptr.io that is exposed as an API to the aforementioned devices. The API temporarily stores the values of the temperature and water it received until it is instructed that the transmission is done. It then simply uses the Initial State connector to push these values as events to the Initial State’s API.
Note that before trying the code below, you first have to deploy the Initial State Connector into your scriptr.io account

// Import the initialstateclient module and create an instance of the InitialState class
// to invoke Initial State's APIs
var initialstateModule = require('modules/initialstate/initialstateclient.js');
var initialState = new initialstateModule.InitialState();

try {
  
  // Create a bucket (Initial State makes sure it is only created once)
  var bucket = {bucketKey:"precision_farming", bucketName: "Precison Farming Measures"};
  initialState.createBucket(bucket); 
  
  // Our script store the events it receives (flow and temperature) as long as it is not informed
  // of the end of the transmission (request.parameters.done)
  var done = request.parameters.done;
  if (!done) {

    // Retrieve the values of the water flow and temperature from the parameters 
    // of the incoming request
    var flow = request.parameters.flow;
    var temp = request.parameters.temp;
    
    // Store the received values as events in the script's local storage
    var dateTime = new Date();
    var flowEvent = {key: "flow", "value": flow, iso8601: dateTime.toISOString() };
    var tempEvent = {key: "temp", "value": temp, iso8601: dateTime.toISOString() };
     if (!storage.local.waterflowMeasures) {
    	storage.local.waterflowMeasures = {}; // Lazy initialization of a field in the store 
     }

    storage.local.waterflowMeasures["flow_" +  dateTime] = flowEvent;
    storage.local.waterflowMeasures["temp_" +  dateTime] = tempEvent;
    return "Stored 2 events ";
  }else {   
   
    // The script is now informed that the transmission of events is done, it needs to send 
    // all the events to an Initial State bucket
    
    // Retrieve the events from the store and put them into an array
    var eventArray = [];
    for (var eventKey in storage.local.waterflowMeasures) {
      eventArray.push(storage.local.waterflowMeasures[eventKey]);
    }

    // Invoke the sendEvents method of the Initial State connector to send the events 
    var response = initialState.sendEvents({bucketKey: "precision_farming", events: eventArray});
    
    storage.local.waterflowMeasures = null;
    return "Sent all events to bucket: " + response;
  } 
}catch (exception) {
  return exception;
}

The dashboard

Switch to your Initial State account and sign in. On your left, you are presented with the list of your event buckets. You should see the “Precision Farming Measure” bucket.
initialstate-dashboard
Select the latter then choose one of the available options to see the corresponding data (in our example, we selected “waves”). That’s it, you now have a full fledged dashboard to monitor the water flow and temperature events.
initialstate-dashboard-2

The client application

To go ahead and test this example, you can use the below JavaScript code that can be ran in a browser. This code simulates the behavior of a device that sends water flow and temperature values to the API we created above, using a Web Socket connection.

var ws = new WebSocket("wss://api.scriptrapps.io/YOUR_SCRIPTR_AUTH_TOKEN");
var MAX = 100;


ws.onopen = function() {
  
  console.log("Connection opened");
  var done = false;
  var count = 1;
  var interval = setInterval(

    function() {

      var flow = Math.random() * 2 + 1;
      var temp = Math.random() * 3 + 19;
      flow = flow.toFixed(2);
      temp = temp.toFixed(2);
      var flowMsg = {
        method: "initialstate/sample/precisionFarming",
        params: {"flow":flow, "temp":temp}
      };

      ws.send(JSON.stringify(flowMsg));
      if (count++ >= MAX) {
        
        clearInterval(interval); 
        flowMsg = {
          method: "initialstate/sample/precisionFarming",
          params: {"done":"true"}
        };
        
        ws.send(JSON.stringify(flowMsg));
      }
    }, 20);
};

ws.onmessage = function(event) { 
  console.log(event.data);
};

ws.onerror = function(event) {
  console.log(event.data);
};

ws.onclose = function() {
  console.log("Connection closed");
}

Links

Initial State Connector