Accessing HDB via Websocket

By radmin — In Blog, SCADA — February 19, 2018

* This blog follows from – Leveraging the Cloud for WinCC OA. Please check it out for an introduction to using the Cloud capabilities for WinCC OA.

** The tutorial in this blog is only meant as an introduction to using Websockets in WinCC OA and does not cover all function types. Please refer to documentation for additional details or reach out to SAM IT Industrial Automation team for further assistance by calling +1-919-800-0044 or e-mail us at [email protected]

Starting from WinCC OA version 3.15, the provided http server supports Websockets. WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. Websockets do not contain overhead data like that in HTTP and hence, require significantly less bandwidth. Moreover, once a connection is established, the server can send live updates and notifications to the client (in this case an Internet browser) without waiting for a client request. Similarly, the client can send requests to the server which will be queued until they can be served.

Let us look at some advantages to using websockets over the OLE DB Provider as mentioned in this post:

  • It can not only access archived values in HDB, but also real time data and alerts.
  • Data can be read as well as edited.
  • It can run simply using a CTRL Manager.
  • No limitations to accessing data from distributed systems.
  • No compatibility issues for Linux/Windows, neither for different versions (32-bit/64-bit).
  • Only requirement is that the client browser should support Websocket protocol.

Now I will describe how to get started with Websockets. To use Websocket, first create a control file and follow the steps below:

Step 1 – Using httpConnect() with the Websocket flag

Import the “CtrlHTTP” library and define httpServer() and httpConnect() functions within main body as follows:

#uses “CtrlHTTP”
void main()
{
httpServer(false, 8080);
//Activates an HTTP Server listening on port 8080. False means Authentication is not used.

httpConnect("websocket", "/websocketurl", "_websocket_");
//Here “_websocket_” is the flag. This flag defines the “/websocketurl” url as a websocket.
//The first argument “websocket” registers a function called websocket() as web resource.
}

We will define the Websocket function next.

Step 2 – Define the function websocket()

When a web browser sends a request to the WinCC OA http server, the server starts the callback process within a thread and passes a mapping. Mappings are simply associative arrays, or dictionaries. Hence define the function as follows:

void websocket(mapping map)
{
mixed any;
//Here, any is a variable that we will use next to read data from the Websocket Request.
}

Step 3 – Add the httpReadWebSocket() function

This httpReadWebSocket() function is a waiting Control function which waits for a Websocket message from the client. It returns 0 if a message(or many messages) has been sent and is ready to read. If the socket is closed on the client side, this function returns 1.

So now, let’s define the logic to read a request:

while ( httpReadWebSocket(map["idx"], any) == 0 )
//Here, map[“idx”] references the Internal File Descriptor of the Websocket connection.
//The second argument any, gets written by the message that is received.
{
DebugTN("Received Message", any);
//Read and display the message to Log Viewer
}

*Here, note that the received message is stored in a mixed data type ‘any’. This is because websockets support only text or binary messages, and they can be passed in an anytype/mixed variable.

Step 4 – Building Logic to respond to requests

If you are using javascript to send requests to the WinCC OA http server, it is advisable to send the messages in a JSON format converted to string. To convert this JSON data to a string, you can use the function JSON.stringify(JSON_Object). The reason for using JSON format is that data parsing becomes very easy. Like you would expect, WinCC OA has a script “json.ctl” in its library that we can leverage to parse and understand the received message.

As an example, let’s say you define a request in the following format using javascript, and send it to the http server as shown below:

websocket_object = new WebSocket("ws://" + window.location.host + "/websocketurl");
//Here websocketurl is the URL used to initiate a Websocket connection in localhost.
var req_msg = {
type: “dpGetPeriod”,
dpe: “System1:Site.Site1.Total_Energy”,
T1: “2018.02.17 10:30:05.000000000”,
T1: “2018.02.18 11:30:05.000000000
};
websocket_object.send(JSON.stringify(req_msg))
//Here, websocket_object is a js variable of the type Websocket, that communicates with the
//Server.

After the message is read on the server side, this message can be converted to json format and can be parsed as follows:

mixed any;
anytype json_data;
while ( httpReadWebSocket(map["idx"], any) == 0 )
{
DebugTN("Received Message", any);

json_data = json_strToVal(any);
if (json_data[“type”] == “dpGetPeriod”) {
custom_function(map[“idx”], json_data);
}
}

Here, you can create a custom_function() to execute the actual dpGetPeriod() function as well as add any extra logic, however you like.

Step 5 – Send Response using httpWriteWebSocket()

Based on the variables mentioned above, your write function should be like follows:

int custom_function(int idx, const mapping &json_data)
{
mapping response_data;

//Code containing backend logic

response_data[“type”] = json_data[“type”];
response_data[“dpe”] = json_data[“dpe”];
response_data[“values”] = values_from_logic;
response_data[“times”] = times_from_logic;
//Variables values_from_logic and times_from_logic are derived from the
//actual code you have to implement using dpGetPeriod()

return httpWriteWebSocket(idx, jsonEncode(response_data));
}

After sending the response, the variable response_data can now be parsed accordingly on the client side web browser using Javascript or any other relevant tool.

That’s it! This small tutorial should help you get started on how to use Websockets in WinCC OA. Sending and receiving messages on the client side can be easily done using Javascript, and have not been mentioned much here. You can also use Python to send and receive Websocket messages. Whatever methods you use, once you are able to get the underlying data, you can connect to a Dashboard directly and display real time values, or you can push them to a database for data analytics.

For completion, here’s the complete Pseudo code:

#uses “CtrlHTTP”
#uses “json.ctl”
void main()
{
httpServer(false, 8080);

httpConnect("websocket", "/websocketurl", "_websocket_");
}

void websocket(mapping map)
{
mixed any;
anytype json_data;

while ( httpReadWebSocket(map["idx"], any) == 0 )
{
DebugTN("Received Message", any);

json_data = json_strToVal(any);
if (json_data[“type”] == “dpGetPeriod”) {
custom_function(map[“idx”], json_data);
}
}
}

int custom_function(int idx, const mapping &json_data)
{
mapping response_data;

//Code containing backend logic

response_data[“type”] = json_data[“type”];
response_data[“dpe”] = json_data[“dpe”];
response_data[“values”] = values_from_logic;
response_data[“times”] = times_from_logic;
//Variables values_from_logic and times_from_logic are derived from the
//actual code you have to implement using dpGetPeriod()

return httpWriteWebSocket(idx, jsonEncode(response_data));
}

Should you need help implementing any of these for your environment, feel free to reach out to the Industrial Automation experts at SAM IT Solutions, we are just a phone call away. Call +1-919-800-0044 or e-mail us at [email protected]

Control Infotech, our Industrial Automation partner applies substation automation domain expertise in the realm of utility grid-tie solar generation plants. Complete solutions from Grid-tie engineering, protection & Control panel build, relay programming and PV plant asset monitoring are among the solutions they offer. The SCADA system is technologically the most advanced. It offers user friendly features on a non-proprietary commercially available platform. Customers benefit from a stable and powerful monitoring and control platform that can be seamlessly expanded and deployed on a Cloud platform.

Suyash Kanungo, BTech, MS
Computer Engineer
SAM IT Solutions

Leave a reply

Need Support Now?
Click CLICK HERE to enter a ticket through our support portal for existing clients or call us directly at 919.800.0044 for 24/7 support