0% found this document useful (0 votes)
6 views

VNode Manual RestApiClient v1-8

The vNode REST API Client Reference Manual provides comprehensive guidance on connecting vNode to RESTful API servers, supporting various data retrieval and publishing methods. It includes detailed instructions on creating module instances, configuring channels, requests, headers, and bodies, as well as user-defined scripts for enhanced functionality. Additionally, the manual offers examples and an appendix for JSON and XML object formats.

Uploaded by

engacosta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

VNode Manual RestApiClient v1-8

The vNode REST API Client Reference Manual provides comprehensive guidance on connecting vNode to RESTful API servers, supporting various data retrieval and publishing methods. It includes detailed instructions on creating module instances, configuring channels, requests, headers, and bodies, as well as user-defined scripts for enhanced functionality. Additionally, the manual offers examples and an appendix for JSON and XML object formats.

Uploaded by

engacosta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

I

Reference Manual
vNode REST API Client
V1.8

www.vnodeautomation.com
I

Index
Introduction ................................................................................................................................................3
Creating module instances ................................................................................................................ 4
Configuration ............................................................................................................................................ 6
Channel ................................................................................................................................................... 6
Request ................................................................................................................................................... 7
Headers ................................................................................................................................................... 9
Body .........................................................................................................................................................10
Tag Configuration .............................................................................................................................. 11
User defined scripts............................................................................................................................... 13
Moment.................................................................................................................................................. 13
Buffer....................................................................................................................................................... 13
sprintf ......................................................................................................................................................14
$.logger .................................................................................................................................................. 15
$.local ...................................................................................................................................................... 17
$.output.................................................................................................................................................. 18
Examples .................................................................................................................................................... 19
Reading real time data from JSON Placeholder .............................................................. 20
Reading real time data from OpenWeatherMap ............................................................. 23
Reading historical data from OpenWeatherMap ............................................................ 26
Appendix.................................................................................................................................................... 30
JSON object format ......................................................................................................................... 30
XML object format ........................................................................................................................... 30

www.vnodeautomation.com
I

Introduction

The RestApiClient allows users to quickly and easily connect vNode to most RESTful API
servers.

Main functionalities supported:


• Data retrieval from RESTful servers to the vNode platform.
• Data publishing from vNode to RESTful API servers.
• Supports GET, POST, PUT, PATCH and DELETE methods.
• Secure encrypted connections using HTTPS.
• Basic and token bearer authentication.
• Custom dynamic path and header construction using JavaScript code.
• Out-of-the-box Binary, Text, JSON, and XML serialization supported.
• Custom parsers for transforming any response into valid vNode data.
• Simple interface and code examples included in this manual for speedy data collection.

www.vnodeautomation.com
I

Creating module instances

The first step when using RestApiClient after vNode installation is to instantiate a
RestApiClient module:

• Open vNode and navigate to the “Config” view.


• Click on “Modules”, then create a new module. This instance can have any name (except
names with reserved characters like ‘.’, ‘/’, etc.), although it’s recommended to name the
instance similarly to the name of the module being instantiated. In this case, the name
will be RestApiClient.

Figure 1. Creating new module instances

www.vnodeautomation.com
I

By setting the module type to RestApiClient, the created instance will be a RestApiClient
instance. After saving, RestApiClient should appear in the module list in bold because there
are unsaved changes.

Figure 1: Setting the instance type

Additionally, each instance can be configured with the following options:


• Required: When set to enabled and when this module is receiving data from other
vNode nodes, all links will be paused whilst the module is offline to avoid data loss. If
disabled, this module will have no effect on links when offline.

• Start: This section controls how the module behaves when the vNode service is started
(which also includes service restarts).
o Enabled: If true, the module will automatically start when the vNode service
starts. Otherwise, the module must be started manually.
o Start delay: When automatic start is enabled, this setting is used to control how
much delay there should be between starting the vNode service and starting
the module. This value is displayed in milliseconds.

• Monitor: This section is used to monitor the status of each module, as well as to enable
automatic restart if it goes offline.
o Automatic restart: If true, whenever the module goes offline (except when
manually stopped by the user), the module will automatically restart.
o Restart delay: Determines the delay before restarting the module after it has
gone offline.

www.vnodeautomation.com
I

In addition to configuring this instance, each module has a Logger and API
section which needs to be configured separately. The default settings will be
sufficient for this, but users will need to actively open the Logger and API
configuration settings and save the default values to fully apply the settings.

Configuration

Channel

The first step when configuring the RestApiClient is to create a connection to a REST endpoint.
This is represented by a channel. Channels have the following configuration:

Figure 2: Channel configuration

• Enable data collection: Enables data collection for this channel. If set to false, no
requests on this channel will be executed

• Connection: This section contains options related to the HTTP/HTTPS connection.


o Protocol: Select between unsecure HTTP protocol or secure HTTPS protocol.
o Host: Hostname or IP address of the target REST server without http:// or https://.
o Port: TCP port where the target REST server will be listening. By default, HTTP
uses port 80 and HTTPS uses port 443.
o Options: This section contains additional options that are used when the
protocol is HTTPS.

www.vnodeautomation.com
I

• Reject untrusted certificates: When set to true, connections to the target HTTPS server
will be silently dropped if the server supplies a certificate that is not signed by a trusted
certificate authority. This can occur when using self-signed certificates. In this case, this
option must be set to false.

• Timing: This section contains options related to timeouts and retries that affect all
the requests in the channel.
o Request timeout: Specifies how much time can pass after a request is sent to
the server before it times out and is retried (in milliseconds). The default value it
10000 milliseconds.
o Retries: Selects how many times a request will be retried before being aborted. The
default value is 3 retries, which means that the request will be sent 4 times to the
server (initial request plus 3 retries).
o Transmission delay: Specifies the delay between one request and the next one
on this channel (in milliseconds). The minimum value is 0, which means that the
next request will be sent out as soon as possible after the current one finishes.

Request

A Request represents the REST request that is sent to the server. Requests have the
following options:

Figure 3: Request configuration

www.vnodeautomation.com
I

• Enable data collection: Enables or disables this request. If disabled, the request will
never be sent to the server and any tags with this request as their source will remain
with a BAD – UNINITIALIZED quality.

• Method: Selects between the different HTTP REST methods. Some methods (such as GET)
do not have a body (and as such, the body section is hidden), while others such as POST or
PUT require a body.

• Rate: Sets the rate at which the request will be executed. This value only guarantees
that the request will execute after this rate has passed. However, it may also be delayed
if the transmission delay is too high, or if there are multiple slow requests on this
channel.

• Parameters: List of parameters that will be available to all scripts in this request. More
information about parameters can be found at $.parameter.

• Path: This section is used to obtain the path of the REST request. It can be one of two
types:
o Plain text: The path is created using a static string. This is the simplest way of
creating the request path. However, paths that require dynamic values (such as
a date, or values that depend on tags) cannot be created this way.
o Custom script: Creates a path by executing a custom JavaScript script. This
confers greater flexibility compared to plain text, since using this method means
that the path can be created dynamically based on parameters. The path can be
set by assigning the desired value to the $.output variable. More information can
be found in the $.output section.

• Headers: This section is used to define which headers are sent with the request. More
information about the headers can be found in the headers section.

• Body: This section only appears when the request needs a body (such as a POST, PUT,
and PATCH requests) and is used to generate the body of the request. More
information can be found in the body section.

• Response format: Establishes the expected response format.


o Encoding: Determines the encoding of the response. Valid values are UTF8,
Binary, Base64, and Hexadecimal.
o Serialization: Determines the serialization of the incoming response. Valid values
are Binary, Text, JSON and XML.

www.vnodeautomation.com
I

• Response parser: Determines how the response is parsed into a vNode compatible
format, which is then saved into tags.
o Type: Selects the type of serializer used to parse the body. Currently, only Custom
serializers are supported.
o Script: User defined JavaScript code that will be used to parse the body of the
response. The response received from the REST API server can be found in the
$.input property (containing response body, response status code, and header).
More information about scripts can be found in the user defined scripts section.

Headers

When executing a Request, headers are sent along with the request. Each request has a
number of headers that are set automatically by the module and a variable number of
custom headers created by the user. The below screenshot shows the configuration options
for these headers & two custom headers.

Figure 4: Request header configuration

• Fixed headers: These headers are set automatically by the module. However, a custom
header with the same name as these headers can be created to override this value.

• Accept-Encoding: Configures the Accept-Encoding header for the request, which is


used to indicate which encoding the client can support to the server. Valid values are
Gzip, Deflate, and None.

• Authorization: Configures the Authorization header for the request, which some servers
use to determine whether the client is authorized to execute the REST request. The
authorization header can be one of three types:
o None: The authorization header is not added automatically. However, it can still
be added as a custom header if custom authorization is desired.

www.vnodeautomation.com
I

o Basic: Employs HTTP basic authentication using a username and password.


o Bearer: Uses a static bearer token to authenticate with the server

• Custom headers: These headers are created by users and can either be used to override
a fixed header (for example, if the server uses a custom authorization method) or to add
headers that the REST server requires for servicing a request. The above figure displays
two custom headers of the Accept and Content-Type.
o Type: Custom headers can be created in two ways, either by using a static text,
or by executing code to dynamically create the header. These correspond
respectively to the raw text and custom script options.
o Value: Sets the value of the custom header to the specified string. This option is
only available for raw text types.
o Script: The Script that will be used to dynamically generate the custom header.
The header is set by assigning it to the script’s $.output property. More
information can be found in $.output and information surrounding custom
scripts can be found in user defined scripts. This option is only available for
custom script types.

Body

This section is used to create the body that is sent with the request. These options will only
appear when the REST method is either POST, PUT, or PATCH. The configuration used to
create a body is as follows:

Figure 5: Request body configuration

• Body format: This section determines the format and encoding of the body.
o Serialization: Determines how the body is serialized before being sent to the
destination. Valid options are Binary, Text, JSON, and XML.
o Encoding: Sets the encoding of the body after it is serialized. Valid options are
UTF8, Binary, Base64, and Hexadecimal.

www.vnodeautomation.com
I

• Body serializer: Determines how the body of the request will be created.
o Type: Selects the type of serializer used to create the body. Currently, only
Custom serializers are supported.
o Script: User defined JavaScript code that will be used to generate the body. The
output of the script must be set in the $.output field. More information can be
found in the $.output section and information about scripts can be found at user
defined scripts.

Tag Configuration

RestApiClient can be used as a source module and as such, can generate tag events from
REST requests. In order for these tag events to be valid, tags with the RestApiClient as their
source must be created. See below screenshot for example configuration:

Figure 6: Tag source configuration

• Enabled: When disabled, tags won’t be updated with the values received from the
device. Instead, they will essentially act as memory tags. When set to enabled, the tag
value will be continuously updated with the values received from the field device, or in
this case, the REST server. The default value is set to disabled.

• Module type: Defines the driver type used to retrieve values from the field. In this
example, RestApiClient must be selected from the drop-down menu. If RestApiClient
does not appear in the drop-down menu, this means that this driver has not been
installed on this machine yet and must be installed.

www.vnodeautomation.com
I

• Module name: Selects which instance of the RestApiClient module will provide the data
for this tag.

• Config:
o Enabled: Enables data collection for this tag. If disabled, no events can occur in
this tag.
o Request: Selects which request will provide data to this tag. The request must
already exist in the selected RestApiClient instance. The format for this property
is Channel/Request.
o Alias: The alias can be used to associate this vNode tag with the data retrieved
from the REST server. This property can be left blank, which means that the full
tag path must be used to assign the values received from the REST server. If a tag
alias is used, tags can be referred to in the request parser using this alias, instead
of the full tag path.

www.vnodeautomation.com
I

User defined scripts

User defined scripts can be used in the following cases:


• To create a path using JavaScript functions (such as Date) and/or parameters from tags.
• To create a custom header dynamically based on JavaScript functions and/or
parameters.
• To create the body of the request, when needed (POST, PATCH and PUT methods).
• To parse the response obtained from the server into tag data objects, ready to write or
update the tags.

These scripts use the JavaScript language and have access to the standard JavaScript
functions and objects (such as parseInt or the Date object), as well as the following
additional libraries and functions added by the vNode platform.

Moment

Moment is a JavaScript library that simplifies date parsing and formatting, as well as
manipulating dates (such as adding a specific duration to a date). The RestApiClient version
also includes Moment Timezone, which is used to parse dates in specific time zones and to
manipulate the time zone of a moment object.
Moment can be accessed by directly invoking the moment() constructor, while Moment
Timezone is accessed using moment.tz()
Documentation about Moment can be found in Moment.js and Moment Timezone.

Buffer
Buffer is a Node.js class that is used to create and manipulate binary arrays. This class can
be used when generating or parsing a binary body. Documentation about the Buffer class
can be found at Node.js Buffer API.

www.vnodeautomation.com
I

sprintf

sprintf is a function used to format any string given a format pattern containing placeholders
and several variables that will substitute the placeholders. The format is similar to that of the
C's printf function, since placeholders are declared using the special character %, followed by
a letter denoting the type of the variable that will substitute the placeholder. The following
examples are valid placeholders for different data types:

• Integer: %d or %i
• String: %s
• Binary: %b
• JSON: %j
• ASCII character in decimal: %c
• Scientific notation: %e
• Floating point: %f
• Fixed point: %g
• Octal: %o
• Unsigned integer: %u
• Hexadecimal lowercase: %x
• Hexadecimal uppercase: %X
• Node buffer: %r

If the integer and the unsigned integer format type receive a decimal number, they will
truncate the decimal part.

All formats that admit decimal numbers, such as floating point or scientific notation, can
be configured to specify the required number of decimals to display by using the
format %.xY, where x is the number of decimals, and Y is the format used (f, for floating
point; e, for exponential, etc). For example, to show a floating-point number with 2
decimals, the following format must be used: %.2f. See below for examples of the different
format options in the following script:

www.vnodeautomation.com
I

$.sprintf(“Numbers are: %d and %i”, 10, 15.7)


//Numbers are: 10 and 15

$.sprintf(“String is: %s”, “Hello world!”);


//String is: Hello world!

$.sprintf(“The binary representation of 5 is: %b”, 5);


// The binary representation of 5 is: 101

$.sprintf(“The ASCII character with decimal value 48 is %c”, 48);


// The ASCII character with decimal value 48 is 0

$.sprintf(“1000 in scientific notation is: %e”, 1000);


1000 in scientific notation is: 1e3

$.sprintf(“1234 in scientific notation and 2 decimals is: %.2e”, 1234);


//1234 in scientific notation and 2 decimals is: 1.23e3

$.sprintf(“12.34 in floating point notation is: %f”, 12.34)


//12.34 in floating point notation is: 12.34

$.sprintf(“12.3456 in fixed point notation is: %.3g”, 12.3456);


//12.3456 in fixed point notation is: 12.3

$.sprintf(“12 in octal is: %o”, 12);


//12 in octal is: 14

$.sprintf(“-10 in unsigned integer format is: %u”, -10)


//-10 in unsigned integer format is: 4294967286

$.sprintf(“30 in hexadecimal is: %x”, 30);


//10 in hexadecimal is: 1e

$.sprintf(“30 in uppercase hexadecimal is: %X”, 30);


//30 in uppercase hexadecimal is: 1E

var buf = new Buffer([“Hello world!”]);


$.sprintf(“The buffer is: %r”, buf);
//The buffer is: <48 65 6c 6c 6f 20 77 6f 72 6c 64 21>;

www.vnodeautomation.com
I

$.logger

The $.logger object is used to log messages to the module log, which can be used for both
debugging and informative purposes. The log file can be found at
vNode/log/RestApiClientInstaceName/. It is shared by both the module’s internal execution
and any messages written by the users. The logger has five different logging levels:
• $.logger.error()
• $.logger.warn()
• $.logger.info()
• $.logger.debug()
• $.logger.trace()

Each of the logging functions have two arguments:


o (String) message: Format string using sprintf formatting.
o (Any) arguments: Arguments that will replace the placeholders in the format
string.

$.parameter

Parameters in requests can be used by accessing the $.parameter object. All of these parameters are tag
events and as such, have a value, a quality, and a timestamp. Parameters use the following configuration:

Figure 7: Request parameter configuration

As an example, the parameters value is used by accessing $.parameter.Start.value.


• The parameters value corresponds to the tag value. The type depends on the tag type,
which can be a number, a string, a Boolean, or null.
• The parameters quality is a number in the range of 0-255.
• The parameters timestamp is a number that represents the number of milliseconds
elapsed since January 1970 (Unix Epoch).

www.vnodeautomation.com
I

Additionally, since $.parameter is a JavaScript object, it can be iterated to


programmatically obtain all parameters using the for…in syntax. An iteration example can
be seen in the following snippet:

for (var p in $.parameter){

$.logger.info("Parameter %s is %j", p, $.parameter[p]);

$.local

$.local is an empty object that can be used to store any user variables that persist
between request executions, as well as any variables that are shared between different
scripts belonging to the same request. For example, when creating a local variable named
"count", the following syntax is used:

//Only define the variable if it's undefined

if($.local.count === undefined) $.local.count = 0;

$.input

This variable contains the input given to the custom script, if applicable. The input type
depends on the function of the custom script, and may be null if the script has no input. The
current scripts with access to $.input are:

• Response parser: The input is an object containing three keys:


o Status code: Contains the status code that the server responded with. The most
common status code is 200 – OK.
o Headers: Contains the headers sent with the response by the server. The keys for
these objects are the header name and the values are the header value.
o Body: Contains the body of the request. The body type varies depending on the
serializer used. If the serialization is binary, the type will be a Buffer. If the
serialization is text, it will be plain text and finally, if the serialization is JSON or
XML the result will be a JavaScript object obtained by deserializing each
respective format. More information about the resulting objects can be found in
the appendix.

www.vnodeautomation.com
I

$.output

This variable is used to set the script output. The output type depends on the function of
the custom script. If an incorrect type is used, an exception will be logged and the request
will be aborted. The following are valid output types for each use:

• Custom path: When creating a path using a script, the output must be a valid string.

• Custom header: When a script is used to create a custom header, the output must be
a valid string.

• Custom body serializer: When a custom body is created, the output depends on the
type of serializer used to serialize the body. If the serializer is JSON or XML, the output
must be an object (which is then converted automatically to a JSON or XML string).
When the serialization is text, the output must be a string, and if the serialization is
binary, the output must be a Buffer.

• Custom response parser: When a custom response parser is used to parse the data
received from the server, the output must be an array of tag data objects that contain,
at the very minimum, a tag property and a value property, and optionally, a quality and
a timestamp (using the UNIX Epoch with milliseconds format).

Tag data objects

Whenever data is received from a request to vNode, the data must be parsed into a format
that is compatible with vNode tags, which is an array of tag data objects. The format of a tag
data object differs slightly when the data is saved to a source tag, as opposed to when it is
written to a tag. The tag data formats are as follows:

• TAG_ADDRESS: This value is used to associate the given tag event with a tag in the vNode
tag model. Values can either be a tag path or an alias (providing that an alias is defined in
the tag configuration).

• TAG_VALUE: This is the value that will be saved to the specified tag. It can be a number,
a string, or a Boolean value. If the destination tag has a different type, the value will be
casted to the correct type (if possible).

www.vnodeautomation.com
I

• TAG_QUALITY: This property is optional when the tag is a RestApiClient source tag and will
be ignored if the tag has a different source (since this will make it a tag write). If defined,
this field specifies the quality of this tag event. The property type is a number between 0
and 255. Qualities with values in the 0-64 interval are considered bad, 64-127 are uncertain
and values between 192 and 255 are good. If this value is omitted when acting as the source,
it will automatically be set to 192 (GOOD_NON_SPECIFIC).

• TAG_TIMESTAMP: This property is optional when the tag is a RestApiClient source tag
and ignored if the tag has a different source (since this will make it a tag write). If defined,
this field sets the timestamp of this tag event. The property type is a number and the
value must be the number of milliseconds elapsed since 1970 (UNIX Epoch with
milliseconds). For easy date parsing, Date and/or moment is recommended. If this value
is omitted when acting as a source, the timestamp will automatically be set to the current
time (using the Date.now()function).

tag: TAG_ADDRESS,

value: TAG_VALUE,

quality: TAG_QUALITY,

ts: TAG_TIMESTAMP

www.vnodeautomation.com
I

Examples

Reading real time data from JSON Placeholder

JSON Placeholder is a public REST API server that can be used to test REST clients. It
provides a large amount of static data that can be retrieved using different REST methods
and paths. This example provides a simple request that retrieves some data using a GET
method.

• Step 1: The following channel configuration is used:

Figure 8: JSON Placeholder channel configuration

www.vnodeautomation.com
I

• Step 2: The following request is used by means of a GET to retrieve posts:

Figure 9: JSON Placeholder request configuration

• Step 3: The following script is used to parse the response and the following tag naming
scheme is used: USERID_ID_title and USERID_ID_body.

var data = $.input.body;

//Gets the time when the request finishes to be used as timestamp

var now = Date.now();

for(var i = 0; i<data.length; ++i){

//Creates the ID for each post, concatenating the userId and the id of the post

var id = sprintf("%s_%s", data[i].userId, data[i].id);

//Retrieves the title of the post

$.output.push({tag: id+"_title", value: data[i].title, quality: 192, ts: now});

//Retrieves the body of the post

$.output.push({tag: id+"_body", value: data[i].body, quality: 192, ts: now});

www.vnodeautomation.com
I

Step 4: Since the module is acting as a source, the following tag configuration must be
used. The tag path can be anything, as long as the alias follows the same naming
scheme as established in the previous step. An example source tag can be seen in the
below screenshot:

Figure 10: JSON Placeholder example source tag

www.vnodeautomation.com
I

Reading real time data from OpenWeatherMap

OpenWeatherMap has a REST API that can be used to retrieve climate data for regions
around the globe. This example deals with retrieving real time climate data for a specific
city, in this case Madrid.

• Step 1: The following channel configuration is used:

Figure 11: OpenWeatherMap channel configuration

www.vnodeautomation.com
I

• Step 2: The following request is used by means of a GET method to retrieve climate data
for Madrid (the APPID should be replaced by the unique API key associated with the
OpenWeatherMap account):

Figure 12: OpenWeatherMap real time data request configuration

• Step 3: The following script is used to parse the response using the City_variable as
a naming scheme for the tags:

var data = $.input.body;

//Directly extract the data from the JSON response

$.output.push({tag: "Madrid_temperature", value: data.main.temp});

$.output.push({tag: "Madrid_pressure", value: data.main.pressure});

$.output.push({tag: "Madrid_humidity", value: data.main.humidity});

$.output.push({tag: "Madrid_wind_speed", value: data.wind.speed});

$.output.push({tag: "Madrid_wind_degree", value: data.wind.deg});

www.vnodeautomation.com
I

• Step 4: In order for this data to be saved correctly to tags, the tags must have
RestApiClient as the source module and use the same naming scheme as established
in the previous step. An example of a source tag can be seen in the following
screenshot:

Figure 13: OpenWeatherMap real time data tag example

www.vnodeautomation.com
I

Reading historical data from OpenWeatherMap

Continuing on from the previous example, this example demonstrates how historical data
is read from OpenWeatherMaps.

• Step 1: The same channel configuration as the previous example is used:

Figure 14: OpenWeatherMap channel configuration

www.vnodeautomation.com
I

• Step 2: This request is also like the previous example. The only difference is that it uses
a custom path (since the historical data requested depends on the current date, which
is a dynamic value). See below screenshot for example configuration:

Figure 15: OpenWeatherMap historical data request configuration

• Step 3: The following custom script is used to generate the request path:

//Get the timestamp as the number of seconds since 1970

var ts = Math.round(moment().startOf("d")/1000);

//Create the object that will generate the output using querystring

var requestParams = {

lat: 40.41,

lon: -3.70,

dt: ts,

// appid : "APP_ID",

appid: "c8298d241b1ba07af67d476964756a65"

$.output =
"http://api.openweathermap.org/data/2.5/onecall/timemachine?"+querystring.stringify(
requestParams);

www.vnodeautomation.com
I

• Step 4: The below script is used to parse the response, using the City_variable as a
naming scheme for the tags:

var data = $.input.body.hourly;

for(var i = 0; i<data.length; ++i){

var ts = data[i].dt*1000;

$.output.push({tag: "Madrid_temperature", value: data[i].temp, ts: ts});

$.output.push({tag: "Madrid_pressure", value: data[i].pressure, ts: ts});

$.output.push({tag: "Madrid_humidity", value: data[i].humidity, ts: ts});

$.output.push({tag: "Madrid_wind_speed", value: data[i].wind_speed, ts: ts});

$.output.push({tag: "Madrid_wind_degree", value: data[i].wind_deg, ts: ts});

www.vnodeautomation.com
I

• Step 5: In order for the data to be saved to tags, these tags must have RestApiClient as
the source module and must also have an alias that follows the naming scheme
mentioned in the previous step. An example source configuration can be seen in the
following screenshot:

Figure 16: OpenWeatherMap historical data tag example

www.vnodeautomation.com
I

Appendix

JSON object format

When using JSON, the JSON string will automatically be parsed to an object with the same
structure as the string, since JSON was designed to be a textual representation of a
JavaScript object. A JSON text and its JS equivalent can be seen in the below snippets:

"data": {

"info": {

"Tag Path": "/RestApiClient/Tag1"

"ts": 1550569887810,

"good": true

},

"values ": [5, 23, 12]

data: {

info: {

"Tag Path": "/RestApiClient/Tag1"

ts: 1550569887810,

good: true

},

values: [5, 23, 12]

As an example, the timestamp can be retrieved by accessing data.info.ts, while the value
array can be retrieved by using data.values (which can then be iterated in order to extract
each value).

XML object format

When using XML, the XML string will automatically be parsed to a JavaScript object using
several rules and special characters to generate the object. Parsing depends on the tags
and their structure, but in general, the following rules apply:

www.vnodeautomation.com
I

<main>
<datapoint ts="1550569887810">
<tag path="/RestApiClient/Tag1"/>
<good>true</good>
<values>
<sample value="5"/>
<sample value="23"/>
<sample value="12"/>
</values>
</datapoint>
</main>

• Each tag (except the root) is parsed as an array of one or more elements. As such, an
index must be used when traversing the nested tags. For example, the <good> tag can
be retrieved by using main.datapoint[0].good.

• Attributes of a tag can be accessed by using the $ character after navigating to the
specific tag. For example, the path attribute of the <tag> tag can be accessed by using
main.datapoint[0].tag[0].$.path

• The text value of a tag can be accessed directly if the tag has no attributes. If the tag
does have attributes, it can be accessed using the special character _. In this case, the
text value for the <good> tag can be accessed directly, since the <good> tag has no
attributes. This is done by using main.datapoint[0].good[0]

• When a tag contains several tags with the same name, these tags will be parsed as an
array contained in the parent tag. This can be seen with the <sample> tags contained
in the <values> tag. For example, to access the second sample (with value 23), the
following example must be used: main.datapoint[0].values[0].sample[2].$.value

www.vnodeautomation.com
I

Using these rules, the following JavaScript object is generated after parsing the XML

{
main: {
datapoint: [
{
$: {
ts: "1550569887810"
},
tag: [
{
$: {
path: "/RestApiClient/Tag1"
}
}
],
good: [
"true"
],
values: [
{
sample: [
{
$: {
"value": "5"
}
},
{
$: {
"value": "23"
}
},
{
$: {
"value": "12"
}
}
]
}
]
}
]
}
}

www.vnodeautomation.com

You might also like