VNode Manual RestApi Client v1.8
VNode Manual RestApi Client v1.8
Reference Manual
vNode REST API Client
v 1.8
www.vnodeautomation.com
I
2
Index
Introduction ................................................................................................................................ 3
Configuration ............................................................................................................................ 4
User defined scrips................................................................................................................ 15
Examples .................................................................................................................................... 21
Appendix ................................................................................................................................... 29
www.vnodeautomation.com
I
3
Introduction
The REST API Client allows users to quickly and easily connect vNode to most RESTful
API servers.
www.vnodeautomation.com
I
4
Configuration
Channel
The first step when configuring the REST API CLIENT is to create a connection to a REST
endpoint. This is represented by a channel. Channels have the following 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. The valid range is 1 to 65536.
o Options: This section contains additional options that are used when the protocol
is HTTPS.
▪ CA: Allows using a custom certificate as a trusted Certificate Authority in order
to validate the certificates returned by the server. This can be useful when the
www.vnodeautomation.com
I
5
server is using certificates signed with a non-trusted CA (or when using self-
signed certificates).
▪ 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:
www.vnodeautomation.com
I
6
• 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.
• Triggers: Each request can have one or more triggers that dictate when it will be
executed. Each trigger is checked continuously and whenever one becomes active, the
request will be executed.
www.vnodeautomation.com
I
7
o Periodic: This type of trigger becomes active after a specified period has passed. It is
configured as per the below example:
▪ Scan rate: Specifies the period between each time the trigger is activated, displayed
in milliseconds. The default and minimum value is 1000 milliseconds.
▪ Type: Determines how this period is calculated. Valid values are:
o Fixed time: The trigger will activate as soon as the specified scan rate has passed
since the previous execution ended. For example, if a trigger is set to execute
every 30 seconds, and the first execution occurred at 12:30:17, the next execution
will be at 12:30:47.
• Reschedule timer: If enabled, the transaction activation time will be
rescheduled whenever another trigger is activated.
• Example: If a transaction with several triggers (including a 60 second periodic
trigger, which executed at 11:30:10 is executed at 11:30:25.
o Reschedule enabled: The periodic trigger will be executed at 11:31:25,
rescheduling the timer to execute 60 seconds after the current execution.
o Reschedule disabled: The periodic trigger will be executed at 11:31:10, which
is 60 seconds after the previous periodic execution.
www.vnodeautomation.com
I
8
o Fixed interval: The trigger will execute at specific intervals based on the
scan rate. As per the previous example, if the scan rate is 30 seconds, the
trigger will execute at 12:30:00, 12:30:30, regardless of when the module
started.
o Cron: This field will require you to provide or select a cron expression to
define the desired schedule. Readers can find further information at
crontab.guru. For example, 0 3 * * * would schedule the task to run at 3 AM
every day. It is also possible to select a predefined cron expression:
• Every 15 minutes
• Hourly
• Daily
• Weekly
• Monthly
www.vnodeautomation.com
I
9
o While true: The action triggers once when the condition becomes true, and then
repeats periodically, according to the specified period.
o While false: Same as above, except it triggers while the condition is false.
• Trigger on update: If true, the action will trigger whenever there is a new tag update that
still satisfies the condition. Otherwise, it will only trigger the first time the condition
becomes true. This option is only used when the condition type is set to If true or If false.
• Reset trigger: If enabled, the tag acting as the trigger will be reset after the transaction
is executed. If disabled, the trigger must be manually cleared. Only used for If True and
If False conditions.
• Reset value: Specifies the value that will be used to reset the tag that is acting as the
trigger. Only used when Reset trigger is set to true or for If true and If false conditions.
• 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.
www.vnodeautomation.com
I
10
• 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.
• 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.
www.vnodeautomation.com
I
11
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.
• 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.
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
www.vnodeautomation.com
I
12
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:
• 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.
• Body serializer: Determines how the body of the request will be created.
www.vnodeautomation.com
I
13
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
REST API Client 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 REST API Client
as their source must be created. See below screenshot for example 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.
• Module name: Selects which instance of the REST API Client module will provide the data
for this tag.
www.vnodeautomation.com
I
14
• 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 REST API Client 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
15
• 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 REST API Client 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()
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.
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 sprintf 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
www.vnodeautomation.com
I
16
• 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
17
$.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()
www.vnodeautomation.com
I
18
$.parameter
Parameters in requests can be used by accessing the $.parameter object. All these
parameters are tag events and as such, have a value, a quality, and a timestamp. Parameters
use the following configuration:
• 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).
$.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:
www.vnodeautomation.com
I
19
$.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:
$.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).
www.vnodeautomation.com
I
20
• 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).
• TAG_QUALITY: This property is optional when the tag is a REST API Client 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 REST API Client 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
21
Examples
www.vnodeautomation.com
I
22
• 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.
//Creates the ID for each post, concatenating the userId and the id of the post
www.vnodeautomation.com
I
23
• 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:
www.vnodeautomation.com
I
24
• 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):
www.vnodeautomation.com
I
25
• Step 3: The following script is used to parse the response using the City_variable as a
naming scheme for the tags:
• 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:
www.vnodeautomation.com
I
26
• 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:
www.vnodeautomation.com
I
27
• Step 3: The following custom script is used to generate the request path:
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: "c8298d241b1ba07af67d476964756a6566"
$.output =
"http://api.openweathermap.org/data/2.5/onecall/timemachine?"+querystring.stringify(
requestParams);
• Step 4: The below script is used to parse the response, using the CITY_variable as a
naming scheme for the tags:
var ts = sample.dt*1000;
• 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:
www.vnodeautomation.com
I
28
www.vnodeautomation.com
I
29
Appendix
"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).
www.vnodeautomation.com
I
30
<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
Using these rules, the following JavaScript object is generated after parsing the XML:
www.vnodeautomation.com
I
31
{
main: {
datapoint: [
{
$: {
ts: "1550569887810"
},
tag: [
{
$: {
path: "/RestApiClient/Tag1"
}
}
],
good: [
"true"
],
values: [
{
sample: [
{
$: {
"value": "5"
}
},
{
$: {
"value": "23"
}
},
{
$: {
"value": "12"
}
}
]
}
]
}
]
}
}
www.vnodeautomation.com