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