cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
Showing results for 
Search instead for 
Did you mean: 

Community Tip - You can change your system assigned username to something more personal in your community settings. X

Node.js Rest API example- how to display data from the local network in Vuforia Studio project?

RolandRaytchev
21-Topaz I

Node.js Rest API example- how to display data from the local network in Vuforia Studio project?

Here we have the same start state as described in “How to read sensors via Rest API call in and display it Vuforia Studio experience project?”… but with one significant difference. The sensors URLs are not visible for the Thingworx service. The problem is that the sensors values should be requested via Rest API calls in a local intranet. This means that the end devices are connected to a local router but they  have also internet access. So, they could see the Experience Server and could download the experience. The sensor URL and rest API call should be some thing like:

var url="http://172.16.40.43.5900/api/v0/dev_id=6&size_id=123";

So, it means the IP address of the device, where the value should be requested via Rest API call is not visible from outside the local wlan and the Rest API call could be done only inside the local network.

So here e.g. we can use a node.js program which will request the sensors and will send the values to thingworks. So the main loop is an interval callback function “requestFunction” which is called here in example every 5 seconds. It will read the sensors data via Rest API fetch call (here from a test server)

var http = require('http')
var https = require('https')
const fetch = require('node-fetch')
var request = require("request")

var userId = 1 //could be from 1 to  10
var todosId = 1 //could be 1 -200
function requestFunction() {
    userId = Math.floor((Math.random() * 10) + 1)
    todosId = Math.floor((Math.random() * 200) + 1)

    fetch('http://127.0.0.1:8081/userId/' + userId)
        .then(response => response.json())
        .then(json => {
            console.log(JSON.stringify(json))
 
            setPropValue("profession", json["profession"])
            setPropValue("userName", json["name"])
            setPropValue("userId", json["id"])
            setPropValue("userPassword", json["password"])
        })
    fetch('http://127.0.0.1:8081/api/todos?id=' + todosId)

        .then(response => response.json())
        .then(json => {
            console.log(JSON.stringify(json))
            setPropValue("message", json["title"])
        
        })
}
// ==============================================
setInterval(requestFunction, 5000) //every 5 sec

The syntax of the Rest API  call where we will set/ change the value of the thing property we can  check from the  REST API Reference Guide

https://developer.thingworx.com/en/resources/guides/rest-api-how-guide

Property values access:

https://developer.thingworx.com/en/resources/guides/rest-api-how-guide/property-values-rest-api-how

 

 When we review the code above we can see that there is function “setPropValue” which should set a value to a particular property. Here the twx server:port is mxxxxx7o.studio-trial.thingworx.io:8443. The Thingname is fixed “REST_API_EDGE”

function setPropValue(propName, propValue) {

    var options = {
        method: 'PUT',
        url: 'https://mxxxxx7o.studio-trial.thingworx.io:8443/Thingworx/Things/REST_API_EDGE/Properties/PROPNAME',
        headers: {
            // use here the user appKey who created the Thing /here REST_API_EDGE
            appKey: 'fxxx7x4a-19x4-4xx3-bxxxa-9978a8xxxx17x', //appkey for the user
            'Content-Type': 'application/json'
        },
        body: { PROPNAME: 'XXXXXXX' },
        json: true
    };
    //this will make a string from the option json and will replace the 
 // place holder “PROPNAME” by function argument propName 
     var str_temp = JSON.stringify(options).replace(/PROPNAME/g, propName)
   //this will replace place placeholder XXXXXXX by function argument propVaule
 // and will convert the string back to json
    options = JSON.parse(str_temp.replace(/XXXXXXX/g, propValue))
    console.log("option in setPropValue:")
    console.warn(options)
    request(options, function(error, response, body) {
       //print the return code – success is 200
        console.log("response.statusCode=" + response.statusCode)
        if (error) {
            console.log("error in request");
            throw new Error(error);
        }
        console.log("response")
        
    });
}
// =================================================

111117.jpg

Mostly the generated code should be postprocessed. When we start the script we can verify that the property values will change every 5 seconds.

111118.jpgThebest way now /also the supported way is to get data in Vuforia studio is via the External DATA panel

111119.jpg

Afterwards  we can test in the Preview and later on the end device:

1111191.jpg

0 REPLIES 0
Top Tags