Querying portia - Data fetching with JavaScript (Node.js)

Defining some requirements

For the examples we are presenting we first need to define some constants to be used...


In [1]:
'use strict'

// HTTP protocol library
const http = require("http");

// Portia service URL
const url = "io.portia.supe.solutions";

// The user token
const myToken = "bdb6e780b43011e7af0b67cba486057b";

// Header object with token authentication
const customHeaders = {
    "Authorization": "Bearer " + myToken
};


Out[1]:
'use strict'

Making HTTP requests using JavaScript (Node.js) - Checking credentials

  • ### Unsucessfull request

In [8]:
'use strict'

// Makes the request
let firstRequest = http.get({
    host: url,
    path: "/api/v1/accesstoken/check" // Portia service path for token authorization checking
}, function(response) {
    
    // Treats response data as utf8
    response.setEncoding('utf8');
    
    // Sets callbacks
    let body = "";
    response.on("data", function(dt) {
        body += dt;
    });
    response.on("end", function() {
        
        // Shows response
        if(response.statusCode == 200) {
            console.log("Success accessing Portia Service - Status Code: " + response.statusCode + "\n" + body);
        } else {
            console.log("Couldn't access Portia service - Status Code: " + response.statusCode);
        }
        
    });
    
}).on("error", function(err) {
    // Error handler
    console.error('Error with the request: ', err.message);
});


Out[8]:
'use strict'
Couldn't access Portia service - Status Code: 401
  • ### Sucessfull request

In [9]:
'use strict'

// Makes the request
let secondRequest = http.get({
    host: url,
    path: "/api/v1/accesstoken/check", // Portia service path for token authorization checking
    headers: customHeaders             // Setting the header with a token for successful authorization
}, function(response) {
    
    // Treats response data as utf8
    response.setEncoding('utf8');
    
    // Sets callbacks
    let body = "";
    response.on("data", function(dt) {
        body += dt;
    });
    response.on("end", function() {
        
        // Shows response
        if(response.statusCode == 200) {
            console.log("Success accessing Portia Service - Status Code: " + response.statusCode + "\n" + body);
        } else {
            console.log("Couldn't access Portia service - Status Code: " + response.statusCode);
        }
        
    });
    
}).on("error", function(err) {
    // Error handler
    console.error('Error with the request: ', err.message);
});


Out[9]:
'use strict'
Success accessing Portia Service - Status Code: 200
{"user":"teste","isLoggedIn":true}

Obtaining data from a specific time frame

Now that we have learned how to authenticate with the service, let's see how to get the data


In [10]:
'use strict'

// Example for getting the last 5 minutes of data
let fiveMinutes = 1000 * 60 * 5;
let toTimestamp = Date.now();
let fromTimestamp = toTimestamp - fiveMinutes;

// Portia service path for specific time frame
let timePath = "/api/v1/device/HytTDwUp-j8yrsh8e/port/2/sensor/1";

// Adding the calculated timestamps as GET parameters
let timePathParams = "?from_timestamp=" + fromTimestamp + "&?to_timestamp=" + toTimestamp; // If no parameters, the service default response is for the last 24 hours

// Makes the request
let thirdRequest = http.get({
    host: url,
    path: timePath + timePathParams,
    headers: customHeaders  // Setting the header with a token for successful authorization
}, function(response) {
    
    // Treats response data as utf8
    response.setEncoding('utf8');
    
    // Sets callbacks
    let body = "";
    response.on("data", function(dt) {
        body += dt;
    });
    response.on("end", function() {
        
        // Shows response
        if(response.statusCode == 200) {
            // Parses dimensions
            let dimensions = JSON.parse(body);
            console.log("Success! For each received dimension:");
            for(let dimension of dimensions) {
                console.log("Accessing dimension package:");
                console.log("\tDimension Code: " + dimension.dimension_code);
                console.log("\tUnity Code: " + dimension.dimension_unity_code);
                console.log("\tThing Code: " + dimension.dimension_thing_code);
                console.log("\tDimension Value: " + dimension.dimension_value);
                console.log("\tServer Timestamp: " + dimension.server_timestamp);
            }

        } else {
            console.log("Couldn't access Portia service - Status Code: " + response.statusCode);
        }
        
    });
    
}).on("error", function(err) {
    // Error handler
    console.error('Error with the request: ', err.message);
});


Out[10]:
'use strict'
Success! For each received dimension:
Accessing dimension package:
	Dimension Code: 1
	Unity Code: 1
	Thing Code: 1
	Dimension Value: 27.7
	Server Timestamp: 1508862403386
Accessing dimension package:
	Dimension Code: 1
	Unity Code: 1
	Thing Code: 1
	Dimension Value: 27.8
	Server Timestamp: 1508862344813
Accessing dimension package:
	Dimension Code: 1
	Unity Code: 1
	Thing Code: 1
	Dimension Value: 27.8
	Server Timestamp: 1508862297630
Accessing dimension package:
	Dimension Code: 1
	Unity Code: 1
	Thing Code: 1
	Dimension Value: 27.8
	Server Timestamp: 1508862223091
Accessing dimension package:
	Dimension Code: 1
	Unity Code: 1
	Thing Code: 1
	Dimension Value: 27.8
	Server Timestamp: 1508862163394

Obtaining the latest data

For the next example, we are requesting only the last data sent by the equipments

  • ### Last dimension

In [11]:
'use strict'

// Portia service path for getting the latest data
let lastPath = "/api/v1/device/HytTDwUp-j8yrsh8e/port/2/sensor/1/last";

// Makes the request
let fourthRequest = http.get({
    host: url,
    path: lastPath,
    headers: customHeaders  // Setting the header with a token for successful authorization
}, function(response) {
    
    // Treats response data as utf8
    response.setEncoding('utf8');
    
    // Sets callbacks
    let body = "";
    response.on("data", function(dt) {
        body += dt;
    });
    response.on("end", function() {
        
        // Shows response
        if(response.statusCode == 200) {
            // Parses dimensions
            let dimension = JSON.parse(body)[0];
            console.log("Success! Accessing dimension package:");
            console.log("\tDimension Code: " + dimension.dimension_code);
            console.log("\tUnity Code: " + dimension.dimension_unity_code);
            console.log("\tThing Code: " + dimension.dimension_thing_code);
            console.log("\tDimension Value: " + dimension.dimension_value);
            console.log("\tServer Timestamp: " + dimension.server_timestamp);

        } else {
            console.log("Couldn't access Portia service - Status Code: " + response.statusCode);
        }
        
    });
    
}).on("error", function(err) {
    // Error handler
    console.error('Error with the request: ', err.message);
});


Out[11]:
'use strict'
Success! Accessing dimension package:
	Dimension Code: 1
	Unity Code: 1
	Thing Code: 1
	Dimension Value: 27.7
	Server Timestamp: 1508862403386
  • ### Last three dimensions

In [2]:
'use strict'

// Portia service path for getting the latest data
let lastPath2 = "/api/v1/device/HytTDwUp-j8yrsh8e/port/2/sensor/1/last";

// Adding GET parameter for specifying that we want the last 3 dimension packages
let lastPath2Params = "?limit=3";

// Makes the request
let fifthRequest = http.get({
    host: url,
    path: lastPath2 + lastPath2Params,
    headers: customHeaders  // Setting the header with a token for successful authorization
}, function(response) {
    
    // Treats response data as utf8
    response.setEncoding('utf8');
    
    // Sets callbacks
    let body = "";
    response.on("data", function(dt) {
        body += dt;
    });
    response.on("end", function() {
        
        // Shows response
        if(response.statusCode == 200) {
            // Parses dimensions
            let dimensions = JSON.parse(body);
            console.log("Success! For each received dimension:");
            for(let dimension of dimensions) {
                console.log("Accessing dimension package:");
                console.log("\tDimension Code: " + dimension.dimension_code);
                console.log("\tUnity Code: " + dimension.dimension_unity_code);
                console.log("\tThing Code: " + dimension.dimension_thing_code);
                console.log("\tDimension Value: " + dimension.dimension_value);
                console.log("\tServer Timestamp: " + dimension.server_timestamp);
            }

        } else {
            console.log("Couldn't access Portia service - Status Code: " + response.statusCode);
        }
        
    });
    
}).on("error", function(err) {
    // Error handler
    console.error('Error with the request: ', err.message);
});


Out[2]:
'use strict'
Success! For each received dimension:
Accessing dimension package:
	Dimension Code: 1
	Unity Code: 1
	Thing Code: 1
	Dimension Value: 27.7
	Server Timestamp: 1508862470835
Accessing dimension package:
	Dimension Code: 1
	Unity Code: 1
	Thing Code: 1
	Dimension Value: 27.7
	Server Timestamp: 1508862403386
Accessing dimension package:
	Dimension Code: 1
	Unity Code: 1
	Thing Code: 1
	Dimension Value: 27.8
	Server Timestamp: 1508862344813