Getting started: OAS REST API and native iOS

Step 1

To read and write data between a native iOS app and OAS, you can use the OAS REST API. As a first step, register the HTTP listener with the OAS Service Control Manager under the section labeled “HTML HMI Registration”.

Define the exclusive Node Name and Port Number  that is to be supported. The Node Name should be the registered domain name, IP address, or network node name that all clients will connect to from their browsers. If you are unsure of which node name to use, localhost will work in most cases.

NOTE: Before clicking “Register”, be sure to stop all services. If services are running, the Service Control app will prompt you to stop them.

Step 2

Start up all services, and be sure to include the Framework 4.5 Service as this houses the listener specific to the REST API.

Step 3

Test your API Service from your iOS device.

You will now ensure that your iPhone or iPad can communicate with OAS via the REST API. In this example, the OAS host is located at 192.168.0.101 on the local network, but you will have to replace this with the OAS host node on your network. The base URL you will use to connect to the REST API is http://{{node}}:{{port}}/OASREST/v2. Each operation performed against the REST API will use the specific operation name prepended with the base {{url}}. The first operation to complete is authentication. All sessions with the REST API must be authenticated. You can adjust the {{url}} in the following snippet and test authentication. In Xcode, create a new single-view iOS application, and choose Swift as the language. Add the following code to MainViewController.swift:

Authenticate Session (Swift):

If this code is executed without error, the response will include a clientid and token. These will be included in the header for all other operations.

Here are some Python examples of basic HTTP requests you might wish to make via the REST API after having completed authentication. For additional information, see our REST API documentation.

Create a Tag (Python 3):

Successful tag creation results in the following response from the OAS server:

Read a Tag (Python 3):

Reading a tag is accomplished with a GET request, using a simple query including the path to the Tag.

A possible response from the OAS server:

Update a Tag (Python 3):

Updating a tag is accomplished with a PUT request, using a payload including the path to the Tag, and the parameter(s) to be updated.

Update confirmation from the OAS server:

Step 4

Write tag data from Raspberry Pi to OAS.
Now that you’ve established connectivity with the REST API, you can complete a Python script to write data from your device. Here is an example script which detects when a button is pushed, and forwards that data into OAS as a discrete tag value. An LED on the breadboard (see figure) indicates the current value, and the OAS server is polled at a frequency of 1 Hz to reflect the current state.

For further help with the REST API, navigate to http://restapi.openautomationsoftware.com to open the REST API online documentation.

Writing data from Raspberry Pi using OAS REST API

Step 1

To write data into OAS from a Raspberry Pi, you will use the OAS REST API. As a first step, register the HTTP listener with the OAS Service Control Manager under the section labeled “HTML HMI Registration”.

Define the exclusive Node Name and Port Number  that is to be supported. The Node Name should be the registered domain name, IP address, or network node name that all clients will connect to from their browsers. If you are unsure of which node name to use, localhost will work in most cases.

NOTE: Before clicking “Register”, be sure to stop all services. If services are running, the Service Control app will prompt you to stop them.

Step 2

Start up all services, and be sure to include the Framework 4.5 Service as this houses the listener specific to the REST API.

Step 3

Test your API Service from your Raspberry Pi.

You will now ensure that the Raspberry Pi can communicate with OAS via the REST API. In this example, the OAS host is located at 192.168.0.101 on the local network, but you will have to replace this with the OAS host node on your network. The base URL you will use to connect to the REST API is http://{{node}}:{{port}}/OASREST/v2. Each operation performed against the REST API will use the specific operation name prepended with the base {{url}}. The first operation to complete is authentication. All sessions with the REST API must be authenticated. You can adjust the {{url}} in the following snippet and test authentication.

Authenticate Session (Python 3):

If this code is executed without error, the response will include a clientid and token. These will be included in the header for all other operations.

Here are some Python examples of basic HTTP requests you might wish to make via the REST API after having completed authentication. For additional information, see our REST API documentation.

Create a Tag (Python 3):

Successful tag creation results in the following response from the OAS server:

Read a Tag (Python 3):

Reading a tag is accomplished with a GET request, using a simple query including the path to the Tag.

A possible response from the OAS server:

Update a Tag (Python 3):

Updating a tag is accomplished with a PUT request, using a payload including the path to the Tag, and the parameter(s) to be updated.

Update confirmation from the OAS server:

Step 4

Write tag data from Raspberry Pi to OAS.
Now that you’ve established connectivity with the REST API, you can complete a Python script to write data from your device. Here is an example script which detects when a button is pushed, and forwards that data into OAS as a discrete tag value. An LED on the breadboard indicates the current value, and the OAS server is polled at a frequency of 1 Hz to reflect the current state.

For further help with the REST API, navigate to http://restapi.openautomationsoftware.com to open the REST API online documentation.

Read Database Data

Use the OPCSystems.dll assembly to call GetDatabaseData to return a DataTable of values from a database table or view.

  • The GetDatabaseData function returns a DataTable of values from the local or remote service by obtaining database values where the service is running.
  • Returns blank DataTable if service is not reachable.
  • DBProvider is the database provider type to use.
  • DBServer is the database server to connect to. Not applicable for MS Access and Oracle.
  • TableOrView is the table name or view name to query the data from.
  • MSSQLWindowsAuthentication – when connecting with SQL Server use Windows Authentication. When false specify the DBUser and DBPassword for SQL user login.
  • DBUser is the user name for security authentication. Not applicable if using SQL Server and MSSQLWindowsAuthentication is set to true.
  • DBPassword is the password for security authentication. Not applicable if using SQL Server and MSSQLWindowsAuthentication is set to true.
  • FieldNames is a string array containing the field names to query from the table for view.
  • DataTypes is an array of field data types for the fields.
  • UseDates will enable using the StartDate and EndDate.
  • StartDate as the start date and time of history to retrieve.
  • EndDate as the end date and time of history to retrieve.
  • QueryString is the WHERE condition to append to the query. When blank it is not used.
  • NetworkNode is the name of the network node of the OPC Systems Service to connect to. Leave blank for localhost connection.
  • ErrorString will be set to Success when function is successful and an error message when in error.
  • RemoteSCADAHostingName is the name of the Live Data Cloud OPC Systems Service to connect to.
CONTENTS

VB

C#

Getting Started – REST API

Step 1

To use the OAS REST API you must first register the HTTP listener. This is done with the OAS Service Control Manager under the section labeled “HTML HMI Registration”.

Define the exclusive Node Name and Port Number  that is to be supported. The Node Name should be the registered domain name, IP address, or network node name that all clients will connect to from their browsers. If you are unsure of which node name to use, localhost will work in most cases.

NOTE: Before clicking “Register”, be sure to stop all services. If services are running, the Service Control app will prompt you to stop them.

Step 2

Start up all services, and be sure to include the Framework 4.5 Service as this houses the listener specific to the REST API.

Step 3

Test your API service.
Navigate to http://restapi.openautomationsoftware.com to open the REST API online documentation.

This documentation illustrates all of the operations available to any REST API client and can be tested using the Postman application client.  In the upper right corner of the documentation, you will see a button to Run in Postman, which will install the API documentation into the Postman client for direct execution against any OAS server.  Additionally, the documentation can be configured to display code samples in multiple languages including cURL, jQuery, and NodeJS. Feel free to browse the documentation at any time and to refer back to it while developing your applications.

Clicking Run in Postman will pop up a dialog box to import the REST API into an existing installation of Postman, or you can choose to install the app for the first time. Postman is available for Windows and Mac desktops as well as in a Chrome extension.

Once installed and the API has been downloaded into the app, you will see the following interface, with all operations on the left, organized identically to the online documentation:

The first operation to execute is the Authenticate call, which will generate a REST API session and returns a clientid and token to be used in all subsequent calls to the OAS server.

In the list of operations, expand and select Authenticate and you will see the following on the right side of the app:

This shows that the Authenticate operation is executed as an HTTP POST against the /authenticate URL appended to the base {{url}}. This base URL is defined in your Environment here. Select Manage Environments to add new fields:

Click ADD to create a new Environment which will hold environment variables:

Add a name for your environment, then add a key of url with a value of http://localhost:58725/OASREST/v2 and click ADD to create the new environment. Then return to the Authenticate operation.

Now under the Environments dropdown, select your new Environment. You should see the {{url}} turn orange, indicating that the environment variable is being used.

You can now click SEND to execute the post against your server. If successful, you should see a response body similar to the one below, containing the clientid and token fields.

You can then use these fields in the header of all other operations using the Postman app to test your server.

HTTP API Operations

/gettoken

Used to get an identity token from the server, which will then be used on every subsequent request to read or write data.

message

response

Unless an error occurs, the gettoken response will always contain a token in the response with a status of “OK“. The token should then be included in every subsequent call to the API, identifying the user context for each request.

If the credentials are not valid, a token will still be created, but depending on the OPCSystems Service configuration, that token may not allow the user to gain access to read or write data.

/getdata

Used to get the most recent tag data from the server for real time data display.

message

The message should contain an array of “tags“, each representing a server tag. Each tag should contain an array of “props“, each representing a distinct property that you would like to retrieve from the server for that tag. For example, if you want to get the value for “Pump.Value“, the tag name would be “Pump“, and it would contain a single property with a name of “Value“.

If you wanted to retrieve both “Pump.Value” and “Pump.Description“, you would send a single tag with two elements in the props collection for “Value” and “Description“, respectively.

response

The response follows the same structure as the request, with additional data populated in the property structure. A “datatype” is returned to assist with client-side data formatting, a boolean “quality” field is returned to indicate whether the data quality from the source is good or bad, and the raw value is populated in the “val” field. The value will always be populated as a string no matter which datatype the source is. Use the datatype to do any native client conversions.

/setdata

Used to set a tag value on the server, and ultimately on the data source itself. The message is similar to that used in the /getdata operation, with the addition of the “val” field on the property indicating the new value to set on the server.

message

response

/gettrenddata

Used to retrieve real time and historical alarm data points for rendering graphs and charts on a client.

message

The “requesttype” field determines the type and amount of data returned. For an full load of datapoints, pass an empty string. For only new data received since the last request, pass “NewData”. For historical data, first issue a request with using “HistoryRequest”, and pass in “HistoryData” for subsequent requests for data values.

Only use the “starthistorydate” and “endhistorydate” fields when requesting historical data. Omit these fields for all other requests. Also, these values are based on the Javascript Date format and represent the number of ticks since January 1, 1970, and other client ticks may need conversion.

The “chartinstanceguid” field is used to synchronize between client and server requests. When an initial data set is requested, pass in an empty string, and the server will assign a chartinstanceguid value in the response. For all subsequent messages within the context of that trend data, use the same chartinstanceguid and “NewData” in the requesttype field to reduce the amount of data transferred to the client on each request.

The “samplerate” and “timeframe” fields are used to determine the frequency of samples in seconds, and the timeframe for the full data set.

The “tagnames” array lists each individual tag that will be polled for trend data. These names are simple strings representing the each tag (e.g. “Random.Value”), and the order in which the data will be returned from the server.

The “historytagnames” field is a parallel array to the “tagnames” list. Include a blank entry for each entry in the tagnames array, unless the historical data for any tag is in a separate datalogging group. In that case, use the format datalogginggroupname.fieldname for each entry.

The “historystatprocessing” field is also a parallel array associated with the “tagnames” list. These entries indicate the method used to calculate the historical datapoints returned for each tag. In most cases, use “avg” for an average value of the data samples. You can also use “min” and “max” to get the minimum and maximum values for that data sample timeframe, or “lastsample” to use the most recent sample in that timeframe.

By default, when data is returned, only the raw data values are included in the result, without any timestamp information. When using the averaging method, this makes plotting very straightforward since the timestamp can be inferred from the start time, end time, and number of samples.

It also greatly reduces the amount of data transferred from the server by having the client perform the calculations for display. However, if you wish to include the actual timestamp with each sample, set the “returnalldatawithtimes” value to true.

response

The “chartinstanceguid” field is returned to help you coordinate data sets if you are displaying multiple sets with different parameters. The “firsttime” and “lasttime” fields are tick values indicating the timestamp of the first datapoint and last datapoint in the result, respectively, and combined with the “numberofvalues” can be used to generate timestamps for each datapoint.

If the “returnalldatawithtime” field was utilized in the request, then the “timesforreturnalldata” field in the response will contain actual timestamps for each individual datapoint.

The “penvalues” field will contain the raw datapoints. These are arranged in an array for each individual tag requested in the request message’s “tagnames” field. The penvalues are returned in the same order as tags requested.

/getalarmdata

Used to retrieve real time and historical alarm data, optionally filtered by group, type, and status.

message

Similar the the gettrenddata request, there is a concept of an instance guid, referenced by the “alarminstanceguid” field. On an initial request using the “requesttype” of “RefreshAllData“, use a blank alarminstanceguid. The response will contain a guid assigned by the server to be used in all subsequent requests to synchronize data and modes between client and server.

The “requesttype” field is used to switch between modes. “RefreshAllData” will pull all current real time alarm data available in a single dataset. This is used to refresh data or get a full update after displaying historical data. Subsequent requests for real time alarms should use “NewData” as it will reduce bandwidth and only provide updated alarms since the last request.

To display historical alarms, send an initial message with a requesttype of “HistoryRequest” along the “starthistorydate” and “endhistorydate” fields containing ticks to define the timeframe for historical data. Then subsequent requests should be issued with the “HistoryData” requesttype to receive the dataset.

The “networknodes” is an array of network node strings used for determining the source of the data. Leave empty to assume “localhost” relative to the OPCSystems Service being contacted.

The “alarmfilter” field is used to determine the criteria for which alarms to include in the resulting dataset.

response

The response for any request for alarms will contain the matching alarminstanceguid, along with an array of “alarmvalues“. Each alarm value itself is an array containing the values for the individual alarms. Use the AlarmID field when referencing any individual alarm for performing an Ack or Delete operation.

/updatealarm

Used to update an alarm, marking it as acknowledged or marking it for deletion.

message

Passing in a “requesttype” of “Ack” will mark the alarm identified with “alarmid” as acknowledged, and passing in “Delete” will mark the alarm for deletion.

response

HTTP API JSON Data Structures

HTTP API JSON Data Structures

Any client that can make HTTP calls using JSON data structures can call the API to perform any of the following functions. All urls are relative to the base OPCSystems Service address with a port designated for the HTTP calls. Urls follow the pattern:

<protocol>://<server>:<port>/OPCREST<operation>

Example:

http://your.server.com:58725/OPCREST/gettoken

The API and client library utilizes the JSONP pattern to allow for greater flexibility in deployment without the need for the OPCSystems Service and the web application to be on the same domain. As such, all calls to the API are HTTP GET commands with UrlEncoded data sent as parameters. The required parameters for all API calls are as follows:

callback : <string>

The JSONP callback name. If not implementing the JSONP pattern in the client itself, this can be any string and will be the function name returned by the server containing the response data.

message : <string>

A UrlEncoded string that is the JSON structure required for the particular request. So if you wanted to pass in the necessary structure for executing a call to gettoken, you would pass the following JSON into the message parameter:

{%22un%22:%22someuser%22,%22pw%22:%22somepassword%22}

So, a full example of a call to an OAS server to execute the gettoken operation would look like the following:

http://your.server.com:58725/OPCREST/gettoken?callback=mycallback&message={%22un%22:%22someuser%22,%22pw%22:%22somepassword%22}

Also following the JSONP pattern, the response will take on the form of a JavaScript function with a single parameter containing the JSON response data. For example, if the request parameter for callback was passed a value of “mycallback”, the response would take the following form:

mycallback(<JSON data>);

So using the full example above, you would get something similar to the following as a response:

mycallback({"message":"94ae2a8e-8c20-4578-88a8-bc8089dedb63","status":"OK"});

JSON – jQuery HTML Interface

Real-time Data jQuery Interface

Refer to the Web HMI – Programming Reference for reference and examples of accessing real-time data in a web client?

Real-time and Historical Trend jQuery Interface

Refer to the Web Trend – Programming Reference – Web Trend for reference and examples of accessing real-time and historical trend data in a web client?

Real-time and Historical Alarm jQuery Interface

Refer to the Web Alarm – Programming Reference –  Web Alarm for reference and examples of accessing real-time and historical alarm data in a web client?

 

Frequently Asked Questions – Programmatic Interface

Frequently Asked Questions – Programmatic Interface

How can I programmatically browse OPC Servers?
Yes, using the free to use OPCSystems component. Refer to the WinForm Example Code under the program group Open Automation Software-Example in the Form FormConfigureOPC. This example is also listed in this help file in Programmatic Interface - .NET Programmatic Configuration - Programmatic Access OPC Browsing.