open62541++ 0.13.0
C++ wrapper of open62541
Loading...
Searching...
No Matches
Client.h
Go to the documentation of this file.
1#pragma once
2
3#include <cstdint>
4#include <functional>
5#include <memory>
6#include <string>
7#include <string_view>
8#include <vector>
9
10#include "open62541pp/Config.h"
11#include "open62541pp/Logger.h"
12#include "open62541pp/Span.h"
15
16// forward declaration
17namespace opcua {
19class ByteString;
20class Client;
21class DataType;
23struct Login;
24template <typename Connection>
25class Node;
26class NodeId;
27
28namespace detail {
29struct ClientConnection;
30struct ClientContext;
31} // namespace detail
32
33/* -------------------------------------- Helper functions -------------------------------------- */
34
35namespace detail {
36
38UA_ClientConfig& getConfig(Client& client) noexcept;
39
40ClientConnection* getConnection(UA_Client* client) noexcept;
41ClientConnection& getConnection(Client& client) noexcept;
42
43Client* getWrapper(UA_Client* client) noexcept;
44
46ClientContext& getContext(Client& client) noexcept;
47
48} // namespace detail
49
50/* ------------------------------------------- Client ------------------------------------------- */
51
52using StateCallback = std::function<void()>;
53
54/**
55 * High-level client class.
56 *
57 * Exposes the most common functionality. Use the handle() method to get access the underlying
58 * UA_Client instance and use the full power of open6254.
59 */
60class Client {
61public:
62 /**
63 * Create client with default configuration (no encryption).
64 * Security policies:
65 * - [None](http://opcfoundation.org/UA/SecurityPolicy#None)
66 * @param logger Custom log function. If the passed function is empty, the default logger is
67 * used.
68 */
69 explicit Client(Logger logger = nullptr);
70
71#ifdef UA_ENABLE_ENCRYPTION
72 /**
73 * Create client with encryption enabled (PKI).
74 * Security policies:
75 * - [None](http://opcfoundation.org/UA/SecurityPolicy#None)
76 * - [Basic128Rsa15](http://opcfoundation.org/UA/SecurityPolicy#Basic128Rsa15)
77 * - [Basic256](http://opcfoundation.org/UA/SecurityPolicy#Basic256)
78 * - [Basic256Sha256](http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256)
79 * - [Aes128_Sha256_RsaOaep](http://opcfoundation.org/UA/SecurityPolicy#Aes128_Sha256_RsaOaep)
80 *
81 * @param certificate X.509 v3 certificate in `DER` encoded format
82 * @param privateKey Private key in `PEM` encoded format
83 * @param trustList List of trusted certificates in `DER` encoded format
84 * @param revocationList Certificate revocation lists (CRL) in `DER` encoded format
85 *
86 * @see https://reference.opcfoundation.org/Core/Part2/v105/docs/8
87 * @see https://reference.opcfoundation.org/Core/Part6/v105/docs/6.2
88 */
90 const ByteString& certificate,
91 const ByteString& privateKey,
92 Span<const ByteString> trustList,
93 Span<const ByteString> revocationList = {}
94 );
95#endif
96
98
99 Client(const Client&) = delete;
100 Client(Client&&) noexcept = default;
101 Client& operator=(const Client&) = delete;
102 Client& operator=(Client&&) noexcept = default;
103
104 /**
105 * Gets a list of all registered servers at the given server.
106 * @param serverUrl Server URL (for example `opc.tcp://localhost:4840`)
107 * @note Client must be disconnected.
108 */
109 std::vector<ApplicationDescription> findServers(std::string_view serverUrl);
110
111 /**
112 * Gets a list of endpoints of a server.
113 * @copydetails findServers
114 */
115 std::vector<EndpointDescription> getEndpoints(std::string_view serverUrl);
116
117 /// Set custom logging function.
118 /// Does nothing if the passed function is empty or a nullptr.
119 void setLogger(Logger logger);
120
121 /// Set response timeout in milliseconds.
122 void setTimeout(uint32_t milliseconds);
123
124 /// Set message security mode.
126
127 /// Set custom data types.
128 /// All data types provided are automatically considered for decoding of received messages.
129 void setCustomDataTypes(std::vector<DataType> dataTypes);
130
131 /// Set a state callback that will be called after the client is connected.
133 /// Set a state callback that will be called after the client is disconnected.
135 /// Set a state callback that will be called after the session is activated.
137 /// Set a state callback that will be called after the session is closed.
139
140 /**
141 * Connect to the selected server.
142 * @param endpointUrl Endpoint URL (for example `opc.tcp://localhost:4840/open62541/server/`)
143 */
144 void connect(std::string_view endpointUrl);
145
146 /**
147 * Connect to the selected server with the given username and password.
148 * @param endpointUrl Endpoint URL (for example `opc.tcp://localhost:4840/open62541/server/`)
149 * @param login Login credentials with username and password
150 */
151 void connect(std::string_view endpointUrl, const Login& login);
152
153 /// Disconnect and close a connection to the server (async, without blocking).
154 void disconnect() noexcept;
155
156 /// Check if client is connected (secure channel open).
157 bool isConnected() noexcept;
158
159 /// Get all defined namespaces.
160 std::vector<std::string> getNamespaceArray();
161
162#ifdef UA_ENABLE_SUBSCRIPTIONS
163 /// Create a subscription to monitor data changes and events (default subscription parameters).
165 /// Create a subscription to monitor data changes and events.
167 /// Get all active subscriptions
168 std::vector<Subscription<Client>> getSubscriptions();
169#endif
170
171 /**
172 * Run a single iteration of the client's main loop.
173 * Listen on the network and process arriving asynchronous responses in the background.
174 * Internal housekeeping, renewal of SecureChannels and subscription management is done as well.
175 * @param timeoutMilliseconds Timeout in milliseconds
176 */
177 void runIterate(uint16_t timeoutMilliseconds = 1000);
178 /// Run the client's main loop by. This method will block until Client::stop is called.
179 void run();
180 /// Stop the client's main loop.
181 void stop();
182 /// Check if the client's main loop is running.
183 bool isRunning() const noexcept;
184
190
191 UA_Client* handle() noexcept;
192 const UA_Client* handle() const noexcept;
193
194private:
195 friend detail::ClientConnection& detail::getConnection(Client& client) noexcept;
196
197 std::unique_ptr<detail::ClientConnection> connection_;
198};
199
200inline bool operator==(const Client& lhs, const Client& rhs) noexcept {
201 return (lhs.handle() == rhs.handle());
202}
203
204inline bool operator!=(const Client& lhs, const Client& rhs) noexcept {
205 return !(lhs == rhs);
206}
207
208} // namespace opcua
UA_ApplicationDescription wrapper class.
Definition Composed.h:96
UA_ByteString wrapper class.
Definition Builtin.h:172
High-level client class.
Definition Client.h:60
Subscription< Client > createSubscription()
Create a subscription to monitor data changes and events (default subscription parameters).
Client(Logger logger=nullptr)
Create client with default configuration (no encryption).
UA_Client * handle() noexcept
Node< Client > getViewsNode()
std::vector< Subscription< Client > > getSubscriptions()
Get all active subscriptions.
Client(const Client &)=delete
void onConnected(StateCallback callback)
Set a state callback that will be called after the client is connected.
std::vector< std::string > getNamespaceArray()
Get all defined namespaces.
void connect(std::string_view endpointUrl)
Connect to the selected server.
void setCustomDataTypes(std::vector< DataType > dataTypes)
Set custom data types.
std::vector< EndpointDescription > getEndpoints(std::string_view serverUrl)
Gets a list of endpoints of a server.
void onDisconnected(StateCallback callback)
Set a state callback that will be called after the client is disconnected.
Node< Client > getNode(NodeId id)
void onSessionActivated(StateCallback callback)
Set a state callback that will be called after the session is activated.
void run()
Run the client's main loop by. This method will block until Client::stop is called.
void setSecurityMode(MessageSecurityMode mode)
Set message security mode.
void setLogger(Logger logger)
Set custom logging function.
friend detail::ClientConnection & detail::getConnection(Client &client) noexcept
Client(const ByteString &certificate, const ByteString &privateKey, Span< const ByteString > trustList, Span< const ByteString > revocationList={})
Create client with encryption enabled (PKI).
void onSessionClosed(StateCallback callback)
Set a state callback that will be called after the session is closed.
bool isConnected() noexcept
Check if client is connected (secure channel open).
Node< Client > getTypesNode()
Subscription< Client > createSubscription(SubscriptionParameters &parameters)
Create a subscription to monitor data changes and events.
void runIterate(uint16_t timeoutMilliseconds=1000)
Run a single iteration of the client's main loop.
Node< Client > getObjectsNode()
std::vector< ApplicationDescription > findServers(std::string_view serverUrl)
Gets a list of all registered servers at the given server.
Client(Client &&) noexcept=default
void disconnect() noexcept
Disconnect and close a connection to the server (async, without blocking).
void setTimeout(uint32_t milliseconds)
Set response timeout in milliseconds.
void stop()
Stop the client's main loop.
Node< Client > getRootNode()
bool isRunning() const noexcept
Check if the client's main loop is running.
UA_DataType wrapper class.
Definition DataType.h:20
UA_EndpointDescription wrapper class.
Definition Composed.h:207
UA_NodeId wrapper class.
Definition NodeId.h:36
High-level node class to access node attribute, browse and populate address space.
Definition Node.h:42
View to a contiguous sequence of objects, similar to std::span in C++20.
Definition Span.h:27
High-level subscription class.
ClientContext * getContext(UA_Client *client) noexcept
UA_ClientConfig * getConfig(UA_Client *client) noexcept
Client * getWrapper(UA_Client *client) noexcept
ClientConnection * getConnection(UA_Client *client) noexcept
std::function< void(LogLevel, LogCategory, std::string_view msg)> Logger
Log function signature.
Definition Logger.h:44
std::function< void()> StateCallback
Definition Client.h:52
bool operator!=(const Client &lhs, const Client &rhs) noexcept
Definition Client.h:204
@ DataType
The NodeId of the data type definition for the Value attribute.
MessageSecurityMode
Message security mode.
Definition Common.h:315
Login credentials.
Internal storage for Client class.
Subscription parameters with default values from open62541.