如何在open62541中向服务器添加UA_String数组 [英] How to add an array of UA_String to the server in open62541
问题描述
我正在尝试使用open62541设置OPC服务器.这些示例正在运行,我能够将自己的变量添加到服务器.
I am trying to set up an OPC server using open62541. The examples are working and I was able to add my own variables to the server.
对于这个项目,我想添加一个服务器变量,它是UA_String的数组.有一些诸如double之类的原始类型的示例,但没有针对字符串的示例.
For this project I would like to add a server variable which is an array of UA_String. There are examples for primitive types like doubles, but none for strings.
如何将字符串数组添加到服务器变量?那这些字符串的内存管理又如何呢?
How to add an array of strings to the server variables? And what about the memory management of those strings?
推荐答案
下面是一个最小的示例,该示例显示了如何向服务器添加变量节点.变量节点具有一个包含2个条目的数组:
Here is a minimal example which shows how to add a variable node to the server. The variable node has an array with 2 entries:
#include <open62541/plugin/log_stdout.h>
#include <open62541/server.h>
#include <open62541/server_config_default.h>
#include <signal.h>
#include <stdlib.h>
static volatile UA_Boolean running = true;
static void stopHandler(int sig) {
UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "received ctrl-c");
running = false;
}
int main(void) {
signal(SIGINT, stopHandler);
signal(SIGTERM, stopHandler);
// Server initialization
UA_Server *server = UA_Server_new();
UA_ServerConfig_setDefault(UA_Server_getConfig(server));
// Attributes for variable node
UA_VariableAttributes vattr = UA_VariableAttributes_default;
// Here is the string array. Current size is 2
const size_t array_size = 2;
UA_String *values = (UA_String *) UA_Array_new(array_size, &UA_TYPES[UA_TYPES_STRING]);
values[0] = UA_String_fromChars("Foo");
values[1] = UA_String_fromChars("Bar");
UA_Variant_setArray(&vattr.value, values, array_size, &UA_TYPES[UA_TYPES_STRING]);
vattr.valueRank = UA_VALUERANK_ANY;
// We want a 1-dimensional array with 2 values
UA_UInt32 myArrayDimensions[1] = {array_size};
vattr.value.arrayDimensions = myArrayDimensions;
vattr.value.arrayDimensionsSize = 1;
vattr.displayName = UA_LOCALIZEDTEXT("locale","myarray");
UA_StatusCode retval = UA_Server_addVariableNode(server,
UA_NODEID_STRING(1, "myarray"), // new node id
UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), // parent node
UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), // reference type
UA_QUALIFIEDNAME(1, "myarray"), // node browse name
UA_NODEID_NUMERIC(0, UA_NS0ID_BASEDATAVARIABLETYPE),
vattr, NULL, NULL);
if (retval != UA_STATUSCODE_GOOD) {
// handle error
printf("Error adding node");
}
// clean up
UA_Array_delete(values, array_size, &UA_TYPES[UA_TYPES_STRING]);
retval = UA_Server_run(server, &running);
UA_Server_delete(server);
return retval == UA_STATUSCODE_GOOD ? EXIT_SUCCESS : EXIT_FAILURE;
}
这篇关于如何在open62541中向服务器添加UA_String数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!