commit 624a1d8eb8a11c9d60e6040492761807088620be Author: Steffen Pohle Date: Wed Oct 14 00:27:22 2026 +0200 first commit diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..80573de --- /dev/null +++ b/Makefile @@ -0,0 +1,21 @@ +CXX = g++ +CXXFLAGS = -std=c++17 -O2 -Wall -Wextra + + +PKG_CFLAGS := $(shell pkg-config --cflags open62541) +# PKG_LIBS := $(shell pkg-config --libs open62541) +# PKG_LIBS := -lopen62541 -lpthread -lm -ldl -lmbedtls -lmbedtls -lmbedx509 -lmbedcrypto +PKG_LIBS := -lopen62541 + +all: opcua_client opcua_browser + +opcua_client: opcua_client.cpp OPCUAClient.cpp + $(CXX) -o opcua_client opcua_client.cpp OPCUAClient.cpp $(CXXFLAGS) $(PKG_CFLAGS) $(PKG_LIBS) + +opcua_browser: opcua_browser.cpp OPCUAClient.cpp + $(CXX) -o opcua_browser opcua_browser.cpp OPCUAClient.cpp $(CXXFLAGS) $(PKG_CFLAGS) $(PKG_LIBS) + +clean: + rm -f opcua_client opcua_browser + +.PHONY: all clean diff --git a/OPCUAClient.cpp b/OPCUAClient.cpp new file mode 100644 index 0000000..032565b --- /dev/null +++ b/OPCUAClient.cpp @@ -0,0 +1,142 @@ +#include "OPCUAClient.h" + +OPCUAClient::OPCUAClient() : client(nullptr), isConnected(false) { + client = UA_Client_new(); + UA_ClientConfig_setDefault(UA_Client_getConfig(client)); +} + +OPCUAClient::~OPCUAClient() { + Close(); + if (client) { + UA_Client_delete(client); + } +} + +bool OPCUAClient::Connect(const std::string& endpointUrl) { + if (isConnected) return true; + + UA_StatusCode retval = UA_Client_connect(client, endpointUrl.c_str()); + if (retval != UA_STATUSCODE_GOOD) { + std::cerr << "Connection failed with status: " << UA_StatusCode_name(retval) << std::endl; + return false; + } + + isConnected = true; + return true; +} + +std::vector OPCUAClient::GenList(uint16_t namespaceIndex, uint32_t numericNodeId) { + std::vector nodeList; + if (!isConnected) { + std::cerr << "Not connected!" << std::endl; + return nodeList; + } + + UA_BrowseRequest bReq; + UA_BrowseRequest_init(&bReq); + bReq.requestedMaxReferencesPerNode = 0; + bReq.nodesToBrowse = (UA_BrowseDescription*)UA_malloc(sizeof(UA_BrowseDescription)); + bReq.nodesToBrowseSize = 1; + + // The '&' was removed here to fix the compiler error + UA_BrowseDescription_init(bReq.nodesToBrowse); + bReq.nodesToBrowse->nodeId = UA_NODEID_NUMERIC(namespaceIndex, numericNodeId); + bReq.nodesToBrowse->resultMask = UA_BROWSERESULTMASK_ALL; + + UA_BrowseResponse bResp = UA_Client_Service_browse(client, bReq); + + if (bResp.responseHeader.serviceResult == UA_STATUSCODE_GOOD) { + for (size_t i = 0; i < bResp.resultsSize; ++i) { + for (size_t j = 0; j < bResp.results[i].referencesSize; ++j) { + UA_ReferenceDescription* ref = &bResp.results[i].references[j]; + + OpcNodeInfo info; + info.name = std::string((char*)ref->browseName.name.data, ref->browseName.name.length); + info.nsIndex = ref->nodeId.nodeId.namespaceIndex; + info.nodeClass = ref->nodeClass; + + if (ref->nodeId.nodeId.identifierType == UA_NODEIDTYPE_NUMERIC) { + info.numericId = ref->nodeId.nodeId.identifier.numeric; + info.isStringId = false; + } else if (ref->nodeId.nodeId.identifierType == UA_NODEIDTYPE_STRING) { + info.stringId = std::string((char*)ref->nodeId.nodeId.identifier.string.data, ref->nodeId.nodeId.identifier.string.length); + info.isStringId = true; + } else { + continue; // Skip other ID types in this example + } + + nodeList.push_back(info); + } + } + } + + UA_BrowseRequest_clear(&bReq); + UA_BrowseResponse_clear(&bResp); + return nodeList; +} + +// Internal helper for converting UA_Variant to std::string +static std::string VariantToString(UA_Variant* value) { + if (!UA_Variant_isScalar(value)) { + return "(Array/non-scalar)"; + } + if (value->type == &UA_TYPES[UA_TYPES_STRING]) { + UA_String* uaStr = (UA_String*)value->data; + return std::string((char*)uaStr->data, uaStr->length); + } else if (value->type == &UA_TYPES[UA_TYPES_INT32]) { + return std::to_string(*(UA_Int32*)value->data); + } else if (value->type == &UA_TYPES[UA_TYPES_DOUBLE]) { + return std::to_string(*(UA_Double*)value->data); + } else if (value->type == &UA_TYPES[UA_TYPES_BOOLEAN]) { + return *(UA_Boolean*)value->data ? "True" : "False"; + } + return "(Data type not implemented)"; +} + +std::string OPCUAClient::ReadString(uint16_t namespaceIndex, const std::string& stringNodeId) { + if (!isConnected) return "Error: not connected"; + + UA_Variant value; + UA_Variant_init(&value); + + UA_NodeId nodeId = UA_NODEID_STRING_ALLOC(namespaceIndex, stringNodeId.c_str()); + UA_StatusCode retval = UA_Client_readValueAttribute(client, nodeId, &value); + UA_NodeId_clear(&nodeId); + + std::string result = ""; + if (retval == UA_STATUSCODE_GOOD) { + result = VariantToString(&value); + } else { + result = "Error (" + std::string(UA_StatusCode_name(retval)) + ")"; + } + + UA_Variant_clear(&value); + return result; +} + +std::string OPCUAClient::ReadNumeric(uint16_t namespaceIndex, uint32_t numericNodeId) { + if (!isConnected) return "Error: not connected"; + + UA_Variant value; + UA_Variant_init(&value); + + UA_NodeId nodeId = UA_NODEID_NUMERIC(namespaceIndex, numericNodeId); + UA_StatusCode retval = UA_Client_readValueAttribute(client, nodeId, &value); + + std::string result = ""; + if (retval == UA_STATUSCODE_GOOD) { + result = VariantToString(&value); + } else { + result = "Error (" + std::string(UA_StatusCode_name(retval)) + ")"; + } + + UA_Variant_clear(&value); + return result; +} + +void OPCUAClient::Close() { + if (isConnected && client) { + UA_Client_disconnect(client); + isConnected = false; + } +} \ No newline at end of file diff --git a/OPCUAClient.h b/OPCUAClient.h new file mode 100644 index 0000000..eec2dec --- /dev/null +++ b/OPCUAClient.h @@ -0,0 +1,45 @@ +#ifndef OPCUA_CLIENT_H +#define OPCUA_CLIENT_H + +#include +#include +#include +#include +#include + +// Structure for storing node information for the browser +struct OpcNodeInfo { + std::string name; + uint16_t nsIndex; + uint32_t numericId; + std::string stringId; + bool isStringId; + uint32_t nodeClass; // e.g. UA_NODECLASS_VARIABLE or UA_NODECLASS_OBJECT +}; + +class OPCUAClient { +public: + OPCUAClient(); + ~OPCUAClient(); + + // Establishes a connection to the server + bool Connect(const std::string& endpointUrl); + + // Lists the child nodes of a specific node (default: Objects folder) + std::vector GenList(uint16_t namespaceIndex = 0, uint32_t numericNodeId = 85); + + // Reads the value of a string-based node + std::string ReadString(uint16_t namespaceIndex, const std::string& stringNodeId); + + // Reads the value of a numeric node (new for the browser) + std::string ReadNumeric(uint16_t namespaceIndex, uint32_t numericNodeId); + + // Closes the connection + void Close(); + +private: + UA_Client* client; + bool isConnected; +}; + +#endif // OPCUA_CLIENT_H \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..d8c40bd --- /dev/null +++ b/README.md @@ -0,0 +1,68 @@ +# OPC UA test clients + +This project contains a few small C++ test clients for experimenting with an OPC UA server using the `open62541` library. + +## Included clients + +- `opcua_client.cpp` + - Simple example client. + - Connects to an OPC UA endpoint. + - Lists the nodes in the `Objects` folder. + - Reads a sample value from a string-based node. + +- `opcua_browser.cpp` + - Interactive console browser for the OPC UA address space. + - Starts from the `Objects` folder. + - Lets you browse child nodes and navigate back through the history. + - Prints variable values while browsing. + +- `OPCUAClient.h` / `OPCUAClient.cpp` + - Shared helper class that wraps the Open62541 client API. + - Provides connect, browse, read, and disconnect functions. + +## Requirements + +- C++17 compiler +- `open62541` development package +- `pkg-config` + +On Linux, the library is usually available via the system package manager, for example: + +```bash +sudo apt install libopen62541-dev +``` + +## Build + +From the project directory, run: + +```bash +make +``` + +This creates the following binaries: + +- `opcua_client` +- `opcua_browser` + +## Run + +### Simple client + +```bash +./opcua_client opc.tcp://192.168.1.100:4840 +``` + +The example uses a sample node ID in namespace 1 (`my_variable`), so adjust the code if your server exposes different node names. + +### Browser + +```bash +./opcua_browser opc.tcp://192.168.1.100:4840 +``` + +The browser opens the `Objects` folder and lets you select child nodes from the console. + +## Notes + +This is intended as a small learning and testing project. The code is deliberately compact and meant to be easy to adapt to your own OPC UA server. diff --git a/opcua_browser.cpp b/opcua_browser.cpp new file mode 100644 index 0000000..e91fad6 --- /dev/null +++ b/opcua_browser.cpp @@ -0,0 +1,117 @@ +#include "OPCUAClient.h" +#include +#include +#include +#include + +// Helper structure for navigation history (back button) +struct HistoryStep { + uint16_t nsIndex; + uint32_t numericId; + std::string name; +}; + +int main(int argc, char* argv[]) { + OPCUAClient opcClient; + + if (argc != 2) { + std::cerr << "Usage: " << argv[0] << " " << std::endl; + return 1; + } + + std::string endpoint = argv[1]; + + std::cout << "=== OPC UA Console Browser ===" << std::endl; + std::cout << "Connecting to " << endpoint << "..." << std::endl; + + if (!opcClient.Connect(endpoint)) { + std::cerr << "Connection failed!" << std::endl; + return -1; + } + + // Starting point: Objects folder (NS 0, ID 85) + uint16_t currentNs = 0; + uint32_t currentId = 85; + std::string currentName = "Root/Objects"; + + std::stack history; + + while (true) { + std::cout << "\n--------------------------------------------------" << std::endl; + std::cout << "Current path: " << currentName << " (NS:" << currentNs << ", ID:" << currentId << ")" << std::endl; + std::cout << "--------------------------------------------------" << std::endl; + + // List child nodes + auto nodes = opcClient.GenList(currentNs, currentId); + + if (nodes.empty()) { + std::cout << "[No child nodes found or access denied]" << std::endl; + } else { + for (size_t i = 0; i < nodes.size(); ++i) { + std::string typeStr = (nodes[i].nodeClass == UA_NODECLASS_VARIABLE) ? "[VAR]" : "[FOLDER]"; + std::cout << std::right << std::setw(5) << i + 1 << ") " << std::setw(9) << typeStr << " " << std::left << std::setw(32) << nodes[i].name << std::setw(8) << " (NS:" << nodes[i].nsIndex << ", ID:"; + if (nodes[i].isStringId) { + std::cout << "s=" << nodes[i].stringId; + } else { + std::cout << "i=" << nodes[i].numericId; + } + std::cout << ")"; + + // If it is a variable, show the value immediately + if (nodes[i].nodeClass == UA_NODECLASS_VARIABLE && !nodes[i].isStringId) { + std::cout << " -> Value: " << opcClient.ReadNumeric(nodes[i].nsIndex, nodes[i].numericId); + } else if (nodes[i].nodeClass == UA_NODECLASS_VARIABLE && nodes[i].isStringId) { + std::cout << " -> Value: " << opcClient.ReadString(nodes[i].nsIndex, nodes[i].stringId); + } + std::cout << std::endl; + } + } + + // Navigation options + std::cout << "\nOptions: [number] = select/open | 0 = back | -1 = exit" << std::endl; + std::cout << "Input: "; + int choice; + if (!(std::cin >> choice)) { + std::cin.clear(); + std::cin.ignore(10000, '\n'); + continue; + } + + if (choice == -1) { + break; + } else if (choice == 0) { + if (!history.empty()) { + auto prev = history.top(); + history.pop(); + currentNs = prev.nsIndex; + currentId = prev.numericId; + currentName = prev.name; + } else { + std::cout << "Already at the top level!" << std::endl; + } + } else if (choice > 0 && choice <= static_cast(nodes.size())) { + auto selectedNode = nodes[choice - 1]; + + if (selectedNode.nodeClass == UA_NODECLASS_VARIABLE) { + std::cout << "\n>>> Variable '" << selectedNode.name << "' selected. <<<" << std::endl; + // The value has already been printed in the list + } else { + // Go into the folder (only for numeric IDs to keep the example simple) + if (!selectedNode.isStringId) { + history.push({currentNs, currentId, currentName}); + currentNs = selectedNode.nsIndex; + currentId = selectedNode.numericId; + currentName = currentName + "/" + selectedNode.name; + } else { + std::cout << "Navigation into string-based folder IDs is skipped in this demo." << std::endl; + } + } + } else { + std::cout << "Invalid selection!" << std::endl; + } + } + + opcClient.Close(); + std::cout << "Browser closed." << std::endl; + return 0; +} diff --git a/opcua_client.cpp b/opcua_client.cpp new file mode 100644 index 0000000..e823374 --- /dev/null +++ b/opcua_client.cpp @@ -0,0 +1,52 @@ +#include "OPCUAClient.h" +#include +#include + +int main(int argc, char* argv[]) { + OPCUAClient opcClient; + + if (argc < 3 || argc > 4) { + std::cerr + << "Usage: " << argv[0] + << " [Interval-in-seconds]\n\n" + << "Example:\n" + << argv[0] + << " opc.tcp://192.168.1.100:4840 ns=2;i=2 1\n"; + return 1; + } + + const std::string endpoint = argv[1]; + const std::string nodeText = argv[2]; + const unsigned int interval = + (argc == 4) ? std::strtoul(argv[3], nullptr, 10) : 0; + + // 1. Connect + std::cout << "Connecting to server..." << std::endl; + if (!opcClient.Connect(endpoint)) { + return -1; + } + + // 2. Read Node Value + uint16_t nsIndex = std::stoi(nodeText.substr(nodeText.find("ns=") + 3, nodeText.find(";") - (nodeText.find("ns=") + 3))); + std::size_t sPos = nodeText.find("s="); + std::string stringNodeId; + uint32_t numericNodeId; + std::string value; + + if (sPos != std::string::npos) stringNodeId = nodeText.substr(sPos + 2); + else numericNodeId = std::stoi(nodeText.substr(nodeText.find("i=") + 2)); + + do { + if (sPos != std::string::npos) value = opcClient.ReadString(nsIndex, stringNodeId); + else value = opcClient.ReadNumeric(nsIndex, numericNodeId); + + std::cout << "Value: " << value << std::endl; + if (interval > 0) usleep(interval * 1000000); + } while (interval > 0); + + // 4. Close + std::cout << "\nClosing connection." << std::endl; + opcClient.Close(); + + return 0; +} \ No newline at end of file