Learn open62541 --- [37] Simple communication with KEPServerEX

KEPServerEX is a well-known OPC Server software. This article mainly describes how to use the Client function of open62541 to communicate with KEPServerEX simply.


A KEPServerEX installation and use

I rarely use KEPServerEX. I am a beginner to KEPServerEX. I also look for information on the Internet. You can refer to the following two articles:

  • Please refer to this for installation
  • Please refer to this

After KEPServerEX runs, it will automatically create a Server whose address and port number are opc.tcp://127.0.0.1:49320. Use UaExpert to observe the following on this machine.
Insert picture description here
There are 4 endpoints in total.


Two add users

The Client of this article uses a user name and password to connect to KEPServerEX. For related content, please refer to this article .

We add a user in KEPServerEX, right-click the green ex icon in the figure below, select Settings
Insert picture description here
and then User Manager, click the add user button, add a user name called hello, and the password is 123
Insert picture description here


Three connection

From the previous section, we can see that the communication needs to be encrypted. OpenSSL is used here for operation. For related content, please refer to this article . You need to generate a certificate and private key for the Client.

This article uses VS2015, the open62541 version is V1.1.1, the client code is as follows, the function is to read the UTC time of the Server system, it is relatively simple, the selected endpoint is Basic256-Sign & Encrypt

/* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
* See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */

#define _CRT_SECURE_NO_WARNINGS

#include <stdlib.h>

#pragma comment(lib,"libssl.lib")
#pragma comment(lib,"libcrypto.lib")
#pragma warning(disable: 4996)      

#include "common.h"


#define MIN_ARGS 4

int main(int argc, char* argv[]) {
    
    
	if (argc < MIN_ARGS) {
    
    
		UA_LOG_FATAL(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
			"Arguments are missing. The required arguments are "
			"<opc.tcp://host:port> "
			"<client-certificate.der> <client-private-key.der> "
			"[<trustlist1.der>, ...]");
		return EXIT_FAILURE;
	}

	const char *endpointUrl = argv[1];

	/* 加载client的证书和私匙 */
	UA_ByteString certificate = loadFile(argv[2]);
	UA_ByteString privateKey = loadFile(argv[3]);

	/* 加载trustList. revocationList目前还不支持 */
	size_t trustListSize = 0;
	if (argc > MIN_ARGS)
		trustListSize = (size_t)argc - MIN_ARGS;
	UA_STACKARRAY(UA_ByteString, trustList, trustListSize);
	for (size_t trustListCount = 0; trustListCount < trustListSize; trustListCount++)
		trustList[trustListCount] = loadFile(argv[trustListCount + 4]);

	UA_ByteString *revocationList = NULL;
	size_t revocationListSize = 0;

	UA_Client *client = UA_Client_new();
	UA_ClientConfig *cc = UA_Client_getConfig(client);
	cc->securityMode = UA_MESSAGESECURITYMODE_SIGNANDENCRYPT;
	cc->securityPolicyUri = UA_STRING_ALLOC("http://opcfoundation.org/UA/SecurityPolicy#Basic256");
	UA_ClientConfig_setDefaultEncryption(cc, certificate, privateKey,
		trustList, trustListSize,
		revocationList, revocationListSize);

	// 给安全策略None添加证书信息,去除运行时不匹配的警告
	UA_SecurityPolicy_None(cc->securityPolicies, certificate, &cc->logger);

	// 填坑的地方,非常重要,URI需要保证和证书里的URI一致
	cc->clientDescription.applicationUri = UA_STRING_ALLOC("urn:open62541.client.application");

	UA_ByteString_clear(&certificate);
	UA_ByteString_clear(&privateKey);
	for (size_t deleteCount = 0; deleteCount < trustListSize; deleteCount++) {
    
    
		UA_ByteString_clear(&trustList[deleteCount]);
	}

	/* Secure client connect */
	cc->securityMode = UA_MESSAGESECURITYMODE_SIGNANDENCRYPT; /* require encryption */
	UA_StatusCode retval = UA_Client_connect_username(client, endpointUrl, "hello", "123");
	if (retval != UA_STATUSCODE_GOOD) {
    
    
		UA_Client_delete(client);
		return EXIT_FAILURE;
	}

	UA_Variant value;
	UA_Variant_init(&value);

	/* NodeId of the variable holding the current time */
	const UA_NodeId nodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER_SERVERSTATUS_CURRENTTIME);
	retval = UA_Client_readValueAttribute(client, nodeId, &value);

	if (retval == UA_STATUSCODE_GOOD &&
		UA_Variant_hasScalarType(&value, &UA_TYPES[UA_TYPES_DATETIME])) {
    
    
		UA_DateTime raw_date = *(UA_DateTime *)value.data;
		UA_DateTimeStruct dts = UA_DateTime_toStruct(raw_date);
		UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "date is: %u-%u-%u %u:%u:%u.%03u\n",
			dts.day, dts.month, dts.year, dts.hour, dts.min, dts.sec, dts.milliSec);
	}

	/* Clean up */
	UA_Variant_clear(&value);
	UA_Client_delete(client);
	return retval == UA_STATUSCODE_GOOD ? EXIT_SUCCESS : EXIT_FAILURE;
}

Run the command:

encryp_openssl.exe opc.tcp://127.0.0.1:49320 client_cert.der client_key.der "KEPServerEX_UA Server [A05ECEC2133854A7B9C4CC65EF7F263F9D6E0270].der"

After the compilation is successful, an error will occur during the first run and will be rejected by KEPServerEX. Because the self-signed certificate is used, it is not an officially issued certificate, so KEPServerEX will not trust this certificate by default.

How to make KEPServerEX trust the client's certificate? First, right-click the green ex icon in the figure below and select OPC UA Configuration.
Insert picture description here
This will open the KEPServerEX configuration manager, and then select Trusted Clients. You can see that the client's certificate has been displayed here, but it is in a rejected state, as follows,
Insert picture description here
Select this certificate, and then click Trust below,
Insert picture description here
so that KEPServerEX will trust the client's security certificate.

Run the client's execution command again to get the server's system UTC time correctly.
Insert picture description here


Four how to obtain the certificate of KEPServerEX

After reading the previous section, I will definitely ask: How to obtain the KEPServerEX certificate? I used UaExpert to obtain it, that is, I use UaExpert to connect first. The first time I connect, I will be prompted whether to trust or not.
Insert picture description here
Click Trust Server Certificate and Continue, so that UaExpert can obtain the server's security certificate. For
Insert picture description here
the storage location of the certificate, please refer to this article. article

PS: When using UaExpert to connect, it may be rejected. You can refer to the operation in the previous section and set it to trust.


Five summary

This article mainly describes how to use the Client function of open62541 to perform simple communication with KEPServerEX. This is a foundation. With this foundation, various operations can be performed later.

If there is something wrong with the writing, I hope to leave a message to correct it, thank you for reading.

Guess you like

Origin blog.csdn.net/whahu1989/article/details/108740339