open62541pp 0.17.0
C++ wrapper of open62541
Loading...
Searching...
No Matches
client.hpp
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 <utility> // move
9#include <vector>
10
11#include "open62541pp/config.hpp"
15#include "open62541pp/span.hpp"
16#include "open62541pp/subscription.hpp" // TODO: remove with Client::createSubscription
17#include "open62541pp/types.hpp"
20
22#include "open62541pp/plugin/log_default.hpp" // LogFunction
23
24namespace opcua {
25struct Login;
26template <typename Connection>
27class Node;
28
29/* ---------------------------------------- ClientConfig ---------------------------------------- */
30
31/**
32 * Client configuration.
33 * @see UA_ClientConfig
34 */
35class ClientConfig : public Wrapper<UA_ClientConfig> {
36public:
37 /**
38 * Create client config with default configuration (no encryption).
39 * Security policies:
40 * - [None](http://opcfoundation.org/UA/SecurityPolicy#None)
41 */
43
44#ifdef UA_ENABLE_ENCRYPTION
45 /**
46 * Create client config with encryption enabled (PKI).
47 * Security policies:
48 * - [None](http://opcfoundation.org/UA/SecurityPolicy#None)
49 * - [Basic128Rsa15](http://opcfoundation.org/UA/SecurityPolicy#Basic128Rsa15)
50 * - [Basic256](http://opcfoundation.org/UA/SecurityPolicy#Basic256)
51 * - [Basic256Sha256](http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256)
52 * - [Aes128_Sha256_RsaOaep](http://opcfoundation.org/UA/SecurityPolicy#Aes128_Sha256_RsaOaep)
53 *
54 * @param certificate X.509 v3 certificate in `DER` encoded format
55 * @param privateKey Private key in `PEM` encoded format
56 * @param trustList List of trusted certificates in `DER` encoded format
57 * @param revocationList Certificate revocation lists (CRL) in `DER` encoded format
58 *
59 * @see https://reference.opcfoundation.org/Core/Part2/v105/docs/9
60 * @see https://reference.opcfoundation.org/Core/Part6/v105/docs/6.2
61 */
63 const ByteString& certificate,
64 const ByteString& privateKey,
65 Span<const ByteString> trustList,
66 Span<const ByteString> revocationList = {}
67 );
68#endif
69
71
73
74 ClientConfig(const ClientConfig&) = delete;
75 ClientConfig(ClientConfig&& other) noexcept;
78
79 /// Set custom log function.
80 /// Does nothing if the passed function is empty or a nullptr.
82
83 /// Set response timeout in milliseconds.
84 void setTimeout(uint32_t milliseconds) noexcept;
85
86 /// Set anonymous identity token.
88 /// Set username/password identity token.
90 /// Set X.509 identity token.
92 /// Set issued identity token.
94
95 /// Set message security mode.
97};
98
99/* ------------------------------------------- Client ------------------------------------------- */
100
101using StateCallback = std::function<void()>;
102using InactivityCallback = std::function<void()>;
103using SubscriptionInactivityCallback = std::function<void(IntegerId subscriptionId)>;
104
105/**
106 * High-level client class.
107 *
108 * A client is usually created in two steps:
109 * 1. Create and modify a client configuration (ClientConfig)
110 * 2. Create a Client with a ClientConfig (move ownership to the Client instance)
111 *
112 * Once a client is connected to an `endpointUrl`, it is not possible to switch to another server.
113 * A new client has to be created for that.
114 *
115 * Use the handle() method to get access the underlying UA_Server instance and use the full power
116 * of open62541.
117 *
118 * Don't overwrite the UA_ClientConfig::clientContext pointer! The context pointer is used to store
119 * a pointer to the Client instance (for asWrapper(UA_Client*)) and to get access to the underlying
120 * client context.
121 */
122class Client {
123public:
124 /// Create client with default configuration.
126
127 /// Create client with given configuration (move ownership to client).
129
130#ifdef UA_ENABLE_ENCRYPTION
131 /// @copydoc ClientConfig::ClientConfig(
132 /// const ByteString&, const ByteString&, Span<const ByteString>, Span<const ByteString>
133 /// )
134 [[deprecated("use ClientConfig constructor and construct Client with ClientConfig")]]
136 const ByteString& certificate,
137 const ByteString& privateKey,
138 Span<const ByteString> trustList,
139 Span<const ByteString> revocationList = {}
140 );
141#endif
142
144
145 Client(const Client&) = delete;
146 Client(Client&& other) noexcept;
147 Client& operator=(const Client&) = delete;
148 Client& operator=(Client&& other) noexcept;
149
150 ClientConfig& config() noexcept;
151 const ClientConfig& config() const noexcept;
152
153 /**
154 * Gets a list of all registered servers at the given server.
155 * @param serverUrl Server URL (for example `opc.tcp://localhost:4840`)
156 * @note Client must be disconnected.
157 */
158 std::vector<ApplicationDescription> findServers(std::string_view serverUrl);
159
160 /**
161 * Gets a list of endpoints of a server.
162 * @copydetails findServers
163 */
164 std::vector<EndpointDescription> getEndpoints(std::string_view serverUrl);
165
166 [[deprecated("use ClientConfig::setLogger via config() or pass config to Client")]]
167 void setLogger(LogFunction logger) {
168 config().setLogger(std::move(logger));
169 }
170
171 [[deprecated("use ClientConfig::setTimeout via config() or pass config to Client")]]
172 void setTimeout(uint32_t milliseconds) noexcept {
173 config().setTimeout(milliseconds);
174 }
175
176 template <typename Token>
177 [[deprecated("use ClientConfig::setUserIdentityToken via config() or pass config to Client")]]
178 void setUserIdentityToken(const Token& token) {
180 }
181
182 [[deprecated("use ClientConfig::setSecurityMode via config() or pass config to Client")]]
184 config().setSecurityMode(mode);
185 }
186
187 /// Set custom data types.
188 /// All data types provided are automatically considered for decoding of received messages.
190
191 /// Set a state callback that will be called after the client is connected.
193 /// Set a state callback that will be called after the client is disconnected.
195 /// Set a state callback that will be called after the session is activated.
197 /// Set a state callback that will be called after the session is closed.
199 /// Set an inactivity callback.
200 /// Every UA_ClientConfig::connectivityCheckInterval (in ms), an async read request is performed
201 /// on the server. The callback is called when the client receives no response for this request.
203 /// Set a subscription inactivity callback.
204 /// The callback is called when the client does not receive a publish response after the defined
205 /// delay of `(publishingInterval * maxKeepAliveCount) + UA_ClientConfig::timeout)`.
207
208 /**
209 * Connect to the selected server.
210 * The session authentification method is defined by the UserIdentityToken and is set with
211 * Client::setUserIdentityToken.
212 * @param endpointUrl Endpoint URL (for example `opc.tcp://localhost:4840/open62541/server/`)
213 */
214 void connect(std::string_view endpointUrl);
215
216 /**
217 * Asynchronously connect to the selected server.
218 * Set a state callback, e.g. onConnected, to be notified when the connection status changes.
219 * @copydetails connect
220 */
221 void connectAsync(std::string_view endpointUrl);
222
223 /**
224 * Connect to the selected server with the given username and password.
225 * @param endpointUrl Endpoint URL (for example `opc.tcp://localhost:4840/open62541/server/`)
226 * @param login Login credentials with username and password
227 */
228 [[deprecated("use Client::setUserIdentityToken(UserNameIdentityToken) instead")]]
229 void connect(std::string_view endpointUrl, const Login& login);
230
231 /**
232 * Disconnect and close the connection to the server.
233 */
235
236 /**
237 * Asynchronously disconnect and close the connection to the server.
238 * Set a state callback, e.g. onDisconnected, to be notified when the connection status changes.
239 */
241
242 /// Check if client is connected (secure channel open).
243 bool isConnected() noexcept;
244
245 /// Get all defined namespaces.
246 std::vector<std::string> namespaceArray();
247
248 /// @deprecated Use namespaceArray() instead
249 [[deprecated("use namespaceArray() instead")]]
250 std::vector<std::string> getNamespaceArray() {
251 return namespaceArray();
252 }
253
254#ifdef UA_ENABLE_SUBSCRIPTIONS
255 /// Create a subscription to monitor data changes and events.
256 /// @deprecated Use Subscription constructor
257 [[deprecated("use Subscription constructor")]]
259
260 /// Get all active subscriptions
261 std::vector<Subscription<Client>> subscriptions();
262
263 /// @deprecated Use subscriptions() instead
264 [[deprecated("use subscriptions() instead")]]
265 std::vector<Subscription<Client>> getSubscriptions() {
266 return subscriptions();
267 }
268#endif
269
270 /**
271 * Run a single iteration of the client's main loop.
272 * Listen on the network and process arriving asynchronous responses in the background.
273 * Internal housekeeping, renewal of SecureChannels and subscription management is done as well.
274 * @param timeoutMilliseconds Timeout in milliseconds
275 */
276 void runIterate(uint16_t timeoutMilliseconds = 1000);
277 /// Run the client's main loop by. This method will block until Client::stop is called.
278 void run();
279 /// Stop the client's main loop.
280 void stop();
281 /// Check if the client's main loop is running.
282 bool isRunning() const noexcept;
283
284 [[deprecated("use Node constructor")]] Node<Client> getNode(NodeId id);
285 [[deprecated("use Node constructor")]] Node<Client> getRootNode();
286 [[deprecated("use Node constructor")]] Node<Client> getObjectsNode();
287 [[deprecated("use Node constructor")]] Node<Client> getTypesNode();
288 [[deprecated("use Node constructor")]] Node<Client> getViewsNode();
289
290 UA_Client* handle() noexcept;
291 const UA_Client* handle() const noexcept;
292
293private:
294 detail::ClientContext& context() noexcept;
295 const detail::ClientContext& context() const noexcept;
296
297 friend detail::ClientContext& detail::getContext(Client& client) noexcept;
298
299 struct Deleter {
300 void operator()(UA_Client* client) noexcept;
301 };
302
303 std::unique_ptr<detail::ClientContext> context_;
304 std::unique_ptr<UA_Client, Deleter> client_;
305};
306
307/// Convert native UA_Client pointer to its wrapper instance.
308/// The native client must be owned by a Client instance.
309/// @relates Client
310Client* asWrapper(UA_Client* client) noexcept;
311
312/// @relates Client
313inline bool operator==(const Client& lhs, const Client& rhs) noexcept {
314 return (lhs.handle() == rhs.handle());
315}
316
317/// @relates Client
318inline bool operator!=(const Client& lhs, const Client& rhs) noexcept {
319 return !(lhs == rhs);
320}
321
322} // namespace opcua
UA_ByteString wrapper class.
Definition types.hpp:531
Client configuration.
Definition client.hpp:35
ClientConfig(ClientConfig &&other) noexcept
ClientConfig(const ByteString &certificate, const ByteString &privateKey, Span< const ByteString > trustList, Span< const ByteString > revocationList={})
Create client config with encryption enabled (PKI).
ClientConfig & operator=(const ClientConfig &)=delete
void setUserIdentityToken(const X509IdentityToken &token)
Set X.509 identity token.
ClientConfig & operator=(ClientConfig &&other) noexcept
void setUserIdentityToken(const IssuedIdentityToken &token)
Set issued identity token.
void setTimeout(uint32_t milliseconds) noexcept
Set response timeout in milliseconds.
ClientConfig(const ClientConfig &)=delete
ClientConfig(UA_ClientConfig &&native)
void setSecurityMode(MessageSecurityMode mode) noexcept
Set message security mode.
void setLogger(LogFunction func)
Set custom log function.
ClientConfig()
Create client config with default configuration (no encryption).
void setUserIdentityToken(const UserNameIdentityToken &token)
Set username/password identity token.
void setUserIdentityToken(const AnonymousIdentityToken &token)
Set anonymous identity token.
High-level client class.
Definition client.hpp:122
void disconnect()
Disconnect and close the connection to the server.
friend detail::ClientContext & detail::getContext(Client &client) noexcept
void setSecurityMode(MessageSecurityMode mode) noexcept
Definition client.hpp:183
Client(Client &&other) noexcept
UA_Client * handle() noexcept
Node< Client > getViewsNode()
void setUserIdentityToken(const Token &token)
Definition client.hpp:178
std::vector< Subscription< Client > > getSubscriptions()
Definition client.hpp:265
Client & operator=(const Client &)=delete
Client & operator=(Client &&other) noexcept
Client(const Client &)=delete
void connect(std::string_view endpointUrl, const Login &login)
Connect to the selected server with the given username and password.
void onConnected(StateCallback callback)
Set a state callback that will be called after the client is connected.
bool operator!=(const Client &lhs, const Client &rhs) noexcept
Definition client.hpp:318
std::vector< std::string > getNamespaceArray()
Definition client.hpp:250
Client(ClientConfig &&config)
Create client with given configuration (move ownership to client).
bool operator==(const Client &lhs, const Client &rhs) noexcept
Definition client.hpp:313
void setTimeout(uint32_t milliseconds) noexcept
Definition client.hpp:172
std::vector< std::string > namespaceArray()
Get all defined namespaces.
void connect(std::string_view endpointUrl)
Connect to the selected server.
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)
Client * asWrapper(UA_Client *client) noexcept
Convert native UA_Client pointer to its wrapper instance.
Client()
Create client with default configuration.
void onSessionActivated(StateCallback callback)
Set a state callback that will be called after the session is activated.
ClientConfig & config() noexcept
void run()
Run the client's main loop by. This method will block until Client::stop is called.
std::vector< Subscription< Client > > subscriptions()
Get all active subscriptions.
void setLogger(LogFunction logger)
Definition client.hpp:167
void onInactive(InactivityCallback callback)
Set an inactivity callback.
void setCustomDataTypes(Span< const DataType > dataTypes)
Set custom data types.
void disconnectAsync()
Asynchronously disconnect and close the connection to the server.
Client(const ByteString &certificate, const ByteString &privateKey, Span< const ByteString > trustList, Span< const ByteString > revocationList={})
Create client config 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(const SubscriptionParameters &parameters={})
Create a subscription to monitor data changes and events.
void connectAsync(std::string_view endpointUrl)
Asynchronously connect to the selected server.
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.
void onSubscriptionInactive(SubscriptionInactivityCallback callback)
Set a subscription inactivity callback.
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_NodeId wrapper class.
Definition types.hpp:666
High-level node class to access node attribute, browse and populate address space.
Definition server.hpp:30
View to a contiguous sequence of objects, similar to std::span in C++20.
Definition span.hpp:28
High-level subscription class.
Template base class to wrap native objects.
Definition wrapper.hpp:33
constexpr const UA_ClientConfig & native() const noexcept
Definition wrapper.hpp:102
UA_AnonymousIdentityToken wrapper class.
Definition types.hpp:656
UA_ApplicationDescription wrapper class.
Definition types.hpp:154
UA_EndpointDescription wrapper class.
Definition types.hpp:279
UA_IssuedIdentityToken wrapper class.
Definition types.hpp:709
UA_UserNameIdentityToken wrapper class.
Definition types.hpp:668
UA_X509IdentityToken wrapper class.
Definition types.hpp:692
MessageSecurityMode
Message security mode.
Definition types.hpp:223
uint32_t IntegerId
IntegerId.
Definition types.hpp:123
std::function< void()> StateCallback
Definition client.hpp:101
std::function< void(LogLevel, LogCategory, std::string_view msg)> LogFunction
Log function.
std::function< void()> InactivityCallback
Definition client.hpp:102
std::function< void(IntegerId subscriptionId)> SubscriptionInactivityCallback
Definition client.hpp:103
Login credentials.
Subscription parameters with default values from open62541.