天天看點

OPC UA 開發:open62541使用心得(一)VS2017 64位環境

    由于目前已知的OPC UA的SDK基本都是收費的,隻找到這個open62541是免費開源的。是以決定使用open62541做開發。

一 簡介:

open62541(http://open62541.org) 是一個開源的免費實作OPC UA(OPC統一架構),用C99和C ++ 98語言的通用子集編寫。該庫可與所有主要編譯器一起使用,并提供實作專用OPC UA用戶端和伺服器的必要工具,或将基于OPC UA的通信內建到現有應用程式中。open62541庫與平台無關。所有特定于平台的功能都是通過可交換的插件實作的。為主要作業系統提供了插件實作。

open62541根據Mozilla Public License v2.0獲得許可。是以open62541庫可用于非開源項目。隻有對open62541庫本身的更改才需要在同一許可下釋出。插件以及伺服器和用戶端示例都屬于公共域(CC0許可證)。它們可以在任何許可下重複使用,并且不必釋出更改。

二 資源:

1、官方網站:https://open62541.org/

2、GitHub:https://github.com/open62541/open62541

3、文檔:https://blog.csdn.net/mikasoi/article/details/84799078

4、參考:https://www.cnblogs.com/eatfishcat/p/9929524.html

5、測試工具:https://blog.csdn.net/han_better/article/details/81666740

三 過程:

1、先從官網下載下傳庫檔案,我下載下傳的是Win64位的,解壓後如下:

OPC UA 開發:open62541使用心得(一)VS2017 64位環境

        其中bin檔案夾下面有2個可執行檔案,分别是Server和Client的Demo。

        我隻使用了這裡的“.c”和“.h”2個檔案。

2、建立工程:

        打開VS2017,建立名為“open62541Test”的C++空項目。

        open62541.c和open62541.h這2個檔案到“open62541Test\open62541Test\”檔案夾下。

        打開C:\Windows\System32目錄,複制其中的ws2_32.dll檔案到“open62541Test\open62541Test\”檔案夾下。

        将上面三個檔案分别添加到工程中相應位置:

OPC UA 開發:open62541使用心得(一)VS2017 64位環境

        在源檔案中建立一個Test.cpp檔案:

OPC UA 開發:open62541使用心得(一)VS2017 64位環境

        按照之前連結上的文檔,添加client的測試代碼:

#include <stdio.h>	
#include "open62541.h"
#pragma comment(lib,"ws2_32.lib")    //加載ws2_32.dll的語句,必須要有,否則報錯

int main(void) {
	UA_Client *client = UA_Client_new(UA_ClientConfig_default);
	UA_StatusCode retval = UA_Client_connect(client, "opc.tcp://127.0.0.1:49320");
 //opc.tcp://localhost:4840   此處填寫伺服器的Access我使用的KepServer預設設定
	if (retval != UA_STATUSCODE_GOOD)
	{
		UA_Client_delete(client);
		return (int)retval;
	}

	/* Read the value attribute of the node. UA_Client_readValueAttribute is a
	 * wrapper for the raw read service available as UA_Client_Service_read. */
	UA_Variant value; /* Variants can hold scalar values and arrays of any type */
	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_deleteMembers(&value);
	UA_Client_delete(client); /* Disconnects the client internally */
	return UA_STATUSCODE_GOOD;
}
           

    配置Debug平台為X64。

3、測試:

        按照前面連結上的說明進行KepServer配置。

OPC UA 開發:open62541使用心得(一)VS2017 64位環境

        然後在上面代碼中“if”的前面打個斷點,運作到這裡就會看到是否成功建立了client。同時也可以在KepServer中看到用戶端數量變為“1”,說明連接配接成功。

OPC UA 開發:open62541使用心得(一)VS2017 64位環境

繼續閱讀