open62541pp 0.16.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"
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/8
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()>;
103
104/**
105 * High-level client class.
106 *
107 * A client is usually created in two steps:
108 * 1. Create and modify a client configuration (ClientConfig)
109 * 2. Create a Client with a ClientConfig (move ownership to the Client instance)
110 *
111 * Once a client is connected to an `endpointUrl`, it is not possible to switch to another server.
112 * A new client has to be created for that.
113 *
114 * Use the handle() method to get access the underlying UA_Server instance and use the full power
115 * of open62541.
116 *
117 * Don't overwrite the UA_ClientConfig::clientContext pointer! The context pointer is used to store
118 * a pointer to the Client instance (for asWrapper(UA_Client*)) and to get access to the underlying
119 * client context.
120 */
121class Client {
122public:
123 /// Create client with default configuration.
125
126 /// Create client with given configuration (move ownership to client).
128
129#ifdef UA_ENABLE_ENCRYPTION
130 /// @copydoc ClientConfig::ClientConfig(
131 /// const ByteString&, const ByteString&, Span<const ByteString>, Span<const ByteString>
132 /// )
133 [[deprecated("use ClientConfig constructor and construct Client with ClientConfig")]]
135 const ByteString& certificate,
136 const ByteString& privateKey,
137 Span<const ByteString> trustList,
138 Span<const ByteString> revocationList = {}
139 );
140#endif
141
143
144 Client(const Client&) = delete;
145 Client(Client&& other) noexcept;
146 Client& operator=(const Client&) = delete;
147 Client& operator=(Client&& other) noexcept;
148
149 ClientConfig& config() noexcept;
150 const ClientConfig& config() const noexcept;
151
152 /**
153 * Gets a list of all registered servers at the given server.
154 * @param serverUrl Server URL (for example `opc.tcp://localhost:4840`)
155 * @note Client must be disconnected.
156 */
157 std::vector<ApplicationDescription> findServers(std::string_view serverUrl);
158
159 /**
160 * Gets a list of endpoints of a server.
161 * @copydetails findServers
162 */
163 std::vector<EndpointDescription> getEndpoints(std::string_view serverUrl);
164
165 [[deprecated("use ClientConfig::setLogger via config() or pass config to Client")]]
166 void setLogger(LogFunction logger) {
167 config().setLogger(std::move(logger));
168 }
169
170 [[deprecated("use ClientConfig::setTimeout via config() or pass config to Client")]]
171 void setTimeout(uint32_t milliseconds) noexcept {
172 config().setTimeout(milliseconds);
173 }
174
175 template <typename Token>
176 [[deprecated("use ClientConfig::setUserIdentityToken via config() or pass config to Client")]]
177 void setUserIdentityToken(const Token& token) {
179 }
180
181 [[deprecated("use ClientConfig::setSecurityMode via config() or pass config to Client")]]
183 config().setSecurityMode(mode);
184 }
185
186 /// Set custom data types.
187 /// All data types provided are automatically considered for decoding of received messages.
189
190 /// Set a state callback that will be called after the client is connected.
192 /// Set a state callback that will be called after the client is disconnected.
194 /// Set a state callback that will be called after the session is activated.
196 /// Set a state callback that will be called after the session is closed.
198 /// Set an inactivity callback.
199 /// Every UA_ClientConfig::connectivityCheckInterval (in ms), an async read request is performed
200 /// on the server. The callback is called when the client receives no response for this request.
202
203 /**
204 * Connect to the selected server.
205 * The session authentification method is defined by the UserIdentityToken and is set with
206 * Client::setUserIdentityToken.
207 * @param endpointUrl Endpoint URL (for example `opc.tcp://localhost:4840/open62541/server/`)
208 */
209 void connect(std::string_view endpointUrl);
210
211 /**
212 * Asynchronously connect to the selected server.
213 * Set a state callback, e.g. onConnected, to be notified when the connection status changes.
214 * @copydetails connect
215 */
216 void connectAsync(std::string_view endpointUrl);
217
218 /**
219 * Connect to the selected server with the given username and password.
220 * @param endpointUrl Endpoint URL (for example `opc.tcp://localhost:4840/open62541/server/`)
221 * @param login Login credentials with username and password
222 */
223 [[deprecated("use Client::setUserIdentityToken(UserNameIdentityToken) instead")]]
224 void connect(std::string_view endpointUrl, const Login& login);
225
226 /**
227 * Disconnect and close the connection to the server.
228 */
230
231 /**
232 * Asynchronously disconnect and close the connection to the server.
233 * Set a state callback, e.g. onDisconnected, to be notified when the connection status changes.
234 */
236
237 /// Check if client is connected (secure channel open).
238 bool isConnected() noexcept;
239
240 /// Get all defined namespaces.
241 std::vector<std::string> getNamespaceArray();
242
243#ifdef UA_ENABLE_SUBSCRIPTIONS
244 /// Create a subscription to monitor data changes and events.
246 /// Get all active subscriptions
247 std::vector<Subscription<Client>> getSubscriptions();
248#endif
249
250 /**
251 * Run a single iteration of the client's main loop.
252 * Listen on the network and process arriving asynchronous responses in the background.
253 * Internal housekeeping, renewal of SecureChannels and subscription management is done as well.
254 * @param timeoutMilliseconds Timeout in milliseconds
255 */
256 void runIterate(uint16_t timeoutMilliseconds = 1000);
257 /// Run the client's main loop by. This method will block until Client::stop is called.
258 void run();
259 /// Stop the client's main loop.
260 void stop();
261 /// Check if the client's main loop is running.
262 bool isRunning() const noexcept;
263
264 [[deprecated("use Node constructor")]] Node<Client> getNode(NodeId id);
265 [[deprecated("use Node constructor")]] Node<Client> getRootNode();
266 [[deprecated("use Node constructor")]] Node<Client> getObjectsNode();
267 [[deprecated("use Node constructor")]] Node<Client> getTypesNode();
268 [[deprecated("use Node constructor")]] Node<Client> getViewsNode();
269
270 UA_Client* handle() noexcept;
271 const UA_Client* handle() const noexcept;
272
273private:
274 detail::ClientContext& context() noexcept;
275 const detail::ClientContext& context() const noexcept;
276
277 friend detail::ClientContext& detail::getContext(Client& client) noexcept;
278
279 struct Deleter {
280 void operator()(UA_Client* client) noexcept;
281 };
282
283 std::unique_ptr<detail::ClientContext> context_;
284 std::unique_ptr<UA_Client, Deleter> client_;
285};
286
287/// Convert native UA_Client pointer to its wrapper instance.
288/// The native client must be owned by a Client instance.
289Client* asWrapper(UA_Client* client) noexcept;
290
291inline bool operator==(const Client& lhs, const Client& rhs) noexcept {
292 return (lhs.handle() == rhs.handle());
293}
294
295inline bool operator!=(const Client& lhs, const Client& rhs) noexcept {
296 return !(lhs == rhs);
297}
298
299} // namespace opcua
UA_AnonymousIdentityToken wrapper class.
UA_ApplicationDescription wrapper class.
UA_ByteString wrapper class.
Definition types.hpp:490
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:121
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:182
Client(Client &&other) noexcept
UA_Client * handle() noexcept
Node< Client > getViewsNode()
void setUserIdentityToken(const Token &token)
Definition client.hpp:177
std::vector< Subscription< Client > > getSubscriptions()
Get all active subscriptions.
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.
std::vector< std::string > getNamespaceArray()
Get all defined namespaces.
Client(ClientConfig &&config)
Create client with given configuration (move ownership to client).
void setTimeout(uint32_t milliseconds) noexcept
Definition client.hpp:171
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()
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.
void setLogger(LogFunction logger)
Definition client.hpp:166
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 stop()
Stop the client's main loop.
Node< Client > getRootNode()
bool isRunning() const noexcept
Check if the client's main loop is running.
UA_EndpointDescription wrapper class.
UA_IssuedIdentityToken wrapper class.
UA_NodeId wrapper class.
Definition types.hpp:590
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:26
High-level subscription class.
UA_UserNameIdentityToken wrapper class.
Template base class to wrap native objects.
Definition wrapper.hpp:32
constexpr const UA_ClientConfig & native() const noexcept
Definition wrapper.hpp:75
UA_X509IdentityToken wrapper class.
std::function< void()> StateCallback
Definition client.hpp:101
Client * asWrapper(UA_Client *client) noexcept
Convert native UA_Client pointer to its wrapper instance.
std::function< void(LogLevel, LogCategory, std::string_view msg)> LogFunction
Log function.
std::function< void()> InactivityCallback
Definition client.hpp:102
bool operator!=(const Client &lhs, const Client &rhs) noexcept
Definition client.hpp:295
bool operator==(const Client &lhs, const Client &rhs) noexcept
Definition client.hpp:291
MessageSecurityMode
Message security mode.
Definition common.hpp:315
Login credentials.
Subscription parameters with default values from open62541.