How To Read and Write Live Data with the OAS REST API

Open Automation SoftwareREST API

The OAS REST API exposes functionality for reading and writing real-time and historical Tag Data, Trend Data, and Alarms. The API can also be used for managing OAS Server configurations.

Under the Networking tab, locate the field for REST API/WebHMI Port Number. The default is 58725 but can be changed. If you are accessing the server from a remote client, you will also need to make sure your machine and/or company firewalls allow TCP traffic on the selected port.

OAS REST API Online Documentation

You can view the full documentation for the OAS REST API at https://restapi.openautomationsoftware.com. It details 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. 



For more information about using the OAS REST API with Postman, see our Getting Started – REST API tutorial or watch the video below:

To start you will need to authenticate a session with the REST API, generating a clientid and credential token to use in all subsequent calls. The credentials posted in this operation must be configured in OAS Security settings on the server. To learn more about configuring security, see out Getting Started – Security tutorial in the knowledge base. To use the server’s default credentials, pass an empty string for both username and password fields, but only if the server is configured with the Default user group allowing access to operations.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
    <title>REST Client</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            url: "http://localhost:58725/OASREST/v2/authenticate",
            type: "POST",
            contentType: "application/json; charset=utf-8", 
            crossDomain: true,
            dataType: "json",
            data: '{"username": "", "password": ""}',
            success: function(r) {
                // display the response status code and text
                $('#displaythis').append("Status: "+ r.status +"<br>");
                $('#displaythis').append("Client ID: "+ r.data.clientid +"<br>");
                $('#displaythis').append("Token: "+ r.data.token +"<br>");
            }
        });
    })
    </script>
</head>
    <body>        
        <div id='displaythis'></div>
    </body>
</html>

How To Authenticate and Use the OAS REST API

AuthenticateOpen Automation SoftwareREST API

The OAS REST API exposes functionality for reading and writing real-time and historical Tag Data, Trend Data, and Alarms. The API can also be used for managing OAS Server configurations.

Configure the Port

To use the OAS REST API you must make sure that the OAS HTTP service is listening on the correct port. Open the OAS Configuration application and select Configure > Options, then select the Network Node and click Select.





Under the Networking tab, locate the field for REST API/WebHMI Port Number. The default is 58725 but can be changed. If you are accessing the server from a remote client, you will also need to make sure your machine and/or company firewalls allow TCP traffic on the selected port.



OAS REST API Online Documentation

You can view the full documentation for the OAS REST API at https://restapi.openautomationsoftware.com. It details 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. 



For more information about using the OAS REST API with Postman, see our Getting Started – REST API tutorial or watch the video below:

Authenticate a Session with the REST API

To start you will need to authenticate a session with the REST API, generating a clientid and credential token to use in all subsequent calls. The credentials posted in this operation must be configured in OAS Security settings on the server. To learn more about configuring security, see out Getting Started – Security tutorial in the knowledge base. To use the server’s default credentials, pass an empty string for both username and password fields, but only if the server is configured with the Default user group allowing access to operations.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
    <title>REST Client</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            url: "http://localhost:58725/OASREST/v2/authenticate",
            type: "POST",
            contentType: "application/json; charset=utf-8", 
            crossDomain: true,
            dataType: "json",
            data: '{"username": "", "password": ""}',
            success: function(r) {
                // display the response status code and text
                $('#displaythis').append("Status: "+ r.status +"<br>");
                $('#displaythis').append("Client ID: "+ r.data.clientid +"<br>");
                $('#displaythis').append("Token: "+ r.data.token +"<br>");
            }
        });
    })
    </script>
</head>
    <body>        
        <div id='displaythis'></div>
    </body>
</html>

IIoT Example Service Code

The OAS Example Service code example is a great way to learn how to programmatically add tags, update tag properties, and read and write live data to an OAS Engine.

You can view the .NET Programmatic Interface video for demonstration of the OAS Example Service Code and explanation of use of the most common methods.

Download the OAS Example Service code.

Right click on the zip file that you have downloaded and choose Properties to select Unblock checkbox if Security warning is shown.

There are 4 Visual Studio projects all use the same methods to provide a working example.

  • C# .NET Core Console App
  • VB .NET Core Console App
  • C# Windows Service
  • VB Windows Service

These projects use the OASConfig.dll and OASData.dll assemblies that are included in the OAS platform installation directory, the default is C:\Program Files\Open Automation Software\OAS.

These projects are a good starting point if you need to setup unattended execution of processing and transferring data.  They can be easily modified to include your own routines.

Note: It is recommend to run Visual Studio in Administrative mode for full access to project files.  Either modify the properties of the shortcut under Advanced button or right click on the VS shortcut to Run as administrator.

Key Methods

Constructor

private OASData.Data oasd = new OASData.Data();
private OASConfig.Config oassys = new OASConfig.Config();

Create Tags

string DemoErrorString = "";
string DemoResultString = oassys.SetTagProperties(DemoPropertyValues, "localhost", ref DemoErrorString);
  • PropertyValues is an array of arrays
  • NetworkNode is optional and can be an IP Address network node, or registered domain name
  • ErrorString will set the string passed by reference with Success if successful, or an error string if the tags were not created or updated.

First element is an array containing the property names.  These property names will match the Tag CSV Export header.

object[] DemoDesiredColumns = new object[5];
DemoDesiredColumns[0] = "Tag"; // Required
DemoDesiredColumns[1] = "Value - Data Type";
DemoDesiredColumns[2] = "Value - Source";
DemoDesiredColumns[3] = "Value - Simulation Type";
DemoDesiredColumns[4] = "Value - Simulation Rate";
DemoPropertyValues[0] = DemoDesiredColumns; // First record is the header

Additional elements contain the values for each Tag.

object[] DemoTagValues1 = new object[5];
DemoTagValues1[0] = "OAS Demo Service.Source Tags.Ramp";
DemoTagValues1[1] = "Double";
DemoTagValues1[2] = "Simulation";
DemoTagValues1[3] = "Ramp";
DemoTagValues1[4] = 0.25;
DemoPropertyValues[1] = DemoTagValues1;

Write Tags Asynchronously

oasd.WriteTags(OASTags, OASValues);
  • Tags is a string array of tag names and variables.
  • Values is an object array containing the values to write to each tag.
  • TimeStamps array can optionally be provided to set the time of the value if the Data Source of the Tag is Value.

If the Data Source is defined to a device or application writes to .Value will be written to the source defined.

Examples: Modbus, Siemens, AB, OPC UA, MQTT

Read Tags Asynchronously

Call AddTags to add a list of tags for subscription.

oasd.AddTags(ReadTags);
  • Tags is a string array of tag names and variables.

Values will be returned in the ValuesChangedAll event anytime value changes in a tag variable.

oasd.ValuesChangedAll += OASDValuesChangedAll;
private void OASDValuesChangedAll(string[] Tags, object[] Values, bool[] Qualities, DateTime[] TimeStamps)

Call RemoveTags to remove any of the tag variables from subscription.

Write Tags Synchronously

SyncWriteTags is a blocking call that waits for the call to return from the service.

Errors = oasd.SyncWriteTags(Tags, Values);
  • Tags is a string array of tag names and variables.
  • Values is an object array containing the values to write to each tag.
  • Errors is an Integer array that returns
  • 0 when successful
  • 1 when OAS Engine is not reachable
  • 2 when the Tags array size is not equal to the Values array

Write Tags Synchronously with Confirmation

SyncWriteTagsWithConfirmation is a blocking call that waits for the values of the tag variables written call to return from the service.

Errors = oasd. SyncWriteTagsWithConfirmation(Tags, Values, 10000, 0.0001);
  • Tags is a string array of tag names and variables.
  • Values is an object array containing the values to write to each tag.
  • Include optional timeout with default of 10,000 milliseconds and deadband for floating point values with default of 0.0001.
  • Errors is an Integer array that returns
  • 0 when successful
  • 1 when OAS Engine is not reachable
  • 2 when the Values array is null
  • 3 when the Tags array size is not equal to the Values array

Read Tags Synchronously

SyncReadTags is a blocking call that obtains the current value of the list of tag variables.

Values = oasd.SyncReadTags(Tags, ref Errors, 10000);
  • The returned value is an object array with the values for each tag variable.
  • Tags is a string array of tag names and variables to read.
  • Errors is an integer array returning:
  • 0 if the tag variable quality is good
  • 1 if the quality is bad
  • 2 if the value could not be returned within the timeout specified
  • Timeout is specified in milliseconds to wait for the call to return.

Networking

Tag names can include an IP Address, network node name, or registered domain name if the application is deployed remote from the OAS Engine.

Basis Networking Example:

\\192.168.0.1\TagName.Value

If Live Data Cloud networking is implemented for self-hosting with a dynamic IP Address the LDC syntax is applicable.

Live Data Cloud Networking Example:

\\www.opcweb.com\RemoteSCADAHosting.MyLDCNode.TagName.Value

Register Service

Linux

Windows

  • Windows: Use InstallUtil to register service
  • Using Visual Studio Command Prompt as Administrator
  • InstallUtil OASDemoService.exe

To change the name of the service set the properties of ServiceInstaller1 in ProjectInstaller.

  • Description
  • DisplayName
  • ServiceName

See our OASConfig documentation and OASData documentation for more details.

Automatic Configuration with Dynamic User Interface

Open Automation Software offers OEMs full programmatic setup for their end users.  This method greatly reduces the potential for human error in the setup process.  Deployment of custom applications can be implemented from predefined scripts using SharePoint, Excel or a number of other methods.  Time is saved both in deployment and in troubleshooting because of the decreased likelihood for error and the speed that you can deploy new and update existing projects.

The video below demonstrates how to use the Automated HMI Example that is included in the installation of Open Automation Software.  The application automatically sets up data source configurations, trending, data logging and alarm limits.  The HMI clients will adapt themselves automatically based upon what data source is defined.

.NET Programmatic Server Configuration

.NET Users can programmatically define all OAS configurations including tags and data logging as demonstrated in this video above. The OASConfig .NET Standard 2.0 assembly for .NET 5, .NET Core 2.o or greater, .NET Framework 4.61 or greater, Xamarin.iOS 10.14 or greater, Xamarin.Android 8.0 or greater, and UWP 1.0.0.16299 or greater or the OPCSystems assembly for .NET Framework 4.6 or less. The components are free to use and can be included in Windows Services, Web Services, ASP.NET or .NET MVC Web Applications, WinForm Applications, WPF Applications, and .NET Core Console applications. The assemblies can be used to communicate and setup local and remote services. Learn More…

REST API

The OAS Platform REST API allows developers to read and write real time Tag data, read real time and historical Alarms and Trends, and even create or update Tag configurations. It utilizes JSON data over HTTP(s) and can be used by any virtually any development platform or language. Learn More…

What’s the difference between the REST API and Web HMI?

REST API

The OAS Platform REST API, like all APIs is a programmatic interface. It allows developers to read and write real time Tag data, read real time and historical Alarms and Trends, and even create or update Tag configurations. Because it utilizes JSON data over HTTP(s), it can be used by any virtually any development platform or language. It is also a perfect alternative to the .NET Data Connector for applications not running .NET code. Developers need to handle client to server communication to the API within their code. This includes web technologies such as Javascript, but if browser visualization is required, Web HMI may be the preferred product to utilize.

REST API Language Support

  • Any language that can support sending JSON over HTTP/S (.NET, PHP, Python, JS, NodeJS, Java, and more)
  • Fully documented and interactive API found here

Typical Applications

  • Automated solutions without the need for a user interface or data visualization
  • Programmatic configuration of the OAS Platform when using the .NET Data Connector is not possible (e.g. your platform is not .NET)
  • Native mobile applications

Skills Required

  • Knowledge of HTTP processes and methods
  • Familiarity with JSON object structures

Learn more about the OAS REST API >>

Web HMI

The Web HMI product is specifically geared towards web applications that need to visualize real time and historical data. It consists of a set of Javascript libraries intended to be included in your web pages which handle server communication and screen updates. While the Web HMI product does include programmatic methods for reading and writing Tag data, development is strictly done within HTML and intended to be run in a browser.

Web HMI Language and Platform Support

  • Any web application platform – built on standards (HTML, CSS, Javascript)
  • Any web development platform
  • Purely a Javascript solution for browser-to-OAS communications

Typical Applications

  • Real time and historical data visualization
  • System management and control user interfaces
  • Browser-based desktop and mobile applications

Skills Required

  • Web application development skills
  • Familiarity with JSON object structures
  • Javascript skills for direct access to the Web HMI script library functions

Learn more about OAS Web HMI >>

Can the REST API push data to another destination?

REST APIs by their very nature are HTTP services. This means that they are based on a request/response model. They are not event-driven and not capable of pushing data to a destination. You can poll against the REST API for updated values, but the data is only as current as the polling rate. So if the polling rate is longer than the refresh rate on the server value, you may miss updates.

If you would like to move data based on events, you must write your own solutions using one of our other developer tools, such as the .NET Data Connector or the Universal Driver Interface.

Is the REST API secure?

YES! There are two levels of security when using the REST API. The first is the authentication required for all operations. You first perform an authentication call using a credential configured within the OAS Server. Then, you can encrypt all communications over the wire by using an SSL certificate and restrict the REST API to using only SSL communications.

After authentication, how long can I use the token and clientid?

The security token and client id granted to the caller after authentication represent a REST API session. As long as the server remains active (not rebooted), and the credentials are continually used, the session will not expire. If there is no activity on the session after 30 minutes, the session will expire and a 401 Unauthorized response will be returned for all operations. This idle timeout can be configured on the server using the OAS Configuration app. Go to Configure > Options, select your OAS server (usually localhost when configuring the current machine) and then go to the Networking tab. Here you can set the REST API Session Timeout in minutes.

When would I use the REST API?

The OAS Platform allows for connectivity and integration with many systems and devices. It also exposes tools for direct data integration and automation using .NET for Windows developers, and libraries for integration with web technologies. If you are developing custom software that runs on other platforms that do not host the .NET Framework, and if you prefer to develop more robust applications with or without user interfaces, the REST API is a perfect solution. It exposes functions for reading and writing real time and historical data, as well as operations for customizing the OAS tag configurations themselves.

How do I test the REST API?

The OAS REST API was developed as a standard REST API, and we have exposed our demo server for you to experiment with it using your own tools. We have also published the full REST API documentation online and have integrated it with the popular Postman tool. This free tool allows you to test operations without writing code, and then generate sample code to get you started. In fact, in our online documentation, just click “Run in Postman” and it will download the full API with examples to your Postman instance. Within Postman, you can then point to your own OAS server to test the REST API with your own data. Read more about Getting Started with REST API.