open62541pp 0.19.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_view>
7#include <utility> // move
8#include <vector>
9
10#include "open62541pp/config.hpp"
14#include "open62541pp/span.hpp"
15#include "open62541pp/subscription.hpp" // TODO: remove with Client::createSubscription
16#include "open62541pp/types.hpp"
19
21#include "open62541pp/plugin/log_default.hpp" // LogFunction
22
23namespace opcua {
24
25/* ---------------------------------------- ClientConfig ---------------------------------------- */
26
27template <>
29 static UA_ClientConfig copy(const UA_ClientConfig& config);
30 static UA_ClientConfig move(UA_ClientConfig&& config) noexcept;
31 static void clear(UA_ClientConfig& config) noexcept;
32};
33
34/**
35 * Client configuration.
36 * @see UA_ClientConfig
37 */
38class ClientConfig : public Wrapper<UA_ClientConfig> {
39public:
40 /**
41 * Create client config with default configuration (no encryption).
42 * Security policies:
43 * - [None](http://opcfoundation.org/UA/SecurityPolicy#None)
44 */
46
47#ifdef UA_ENABLE_ENCRYPTION
48 /**
49 * Create client config with encryption enabled (PKI).
50 * Security policies:
51 * - [None](http://opcfoundation.org/UA/SecurityPolicy#None)
52 * - [Basic128Rsa15](http://opcfoundation.org/UA/SecurityPolicy#Basic128Rsa15)
53 * - [Basic256](http://opcfoundation.org/UA/SecurityPolicy#Basic256)
54 * - [Basic256Sha256](http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256)
55 * - [Aes128_Sha256_RsaOaep](http://opcfoundation.org/UA/SecurityPolicy#Aes128_Sha256_RsaOaep)
56 *
57 * @param certificate X.509 v3 certificate in `DER` encoded format
58 * @param privateKey Private key in `PEM` encoded format
59 * @param trustList List of trusted certificates in `DER` encoded format
60 * @param revocationList Certificate revocation lists (CRL) in `DER` encoded format
61 *
62 * @see https://reference.opcfoundation.org/Core/Part2/v105/docs/9
63 * @see https://reference.opcfoundation.org/Core/Part6/v105/docs/6.2
64 */
66 const ByteString& certificate,
67 const ByteString& privateKey,
68 Span<const ByteString> trustList,
69 Span<const ByteString> revocationList = {}
70 );
71#endif
72
73 explicit ClientConfig(UA_ClientConfig&& native) noexcept
74 : Wrapper{std::move(native)} {} // NOLINT
75
76 ClientConfig(const ClientConfig&) = delete;
77 ClientConfig(ClientConfig&&) noexcept = default;
78 ClientConfig& operator=(const ClientConfig&) = delete;
79 ClientConfig& operator=(ClientConfig&&) = default;
80
81 ~ClientConfig() noexcept = default;
82
83 /// Set custom log function.
84 /// Does nothing if the passed function is empty or a nullptr.
86
87 /// Set response timeout in milliseconds.
88 void setTimeout(uint32_t milliseconds) noexcept;
89
90 /// Set anonymous identity token.
92 /// Set username/password identity token.
94 /// Set X.509 identity token.
96 /// Set issued identity token.
98
99 /// Set message security mode.
101
102 /// Add custom data types.
103 /// All data types provided are automatically considered for decoding of received messages.
104 void addCustomDataTypes(Span<const DataType> types);
105};
106
107/* ------------------------------------------- Client ------------------------------------------- */
108
109using StateCallback = std::function<void()>;
110using InactivityCallback = std::function<void()>;
111using SubscriptionInactivityCallback = std::function<void(IntegerId subscriptionId)>;
112
113/**
114 * High-level client class.
115 *
116 * A client is usually created in two steps:
117 * 1. Create and modify a client configuration (ClientConfig)
118 * 2. Create a Client with a ClientConfig (move ownership to the Client instance)
119 *
120 * Once a client is connected to an `endpointUrl`, it is not possible to switch to another server.
121 * A new client has to be created for that.
122 *
123 * Use the handle() method to get access the underlying UA_Server instance and use the full power
124 * of open62541.
125 *
126 * Don't overwrite the UA_ClientConfig::clientContext pointer! The context pointer is used to store
127 * a pointer to the Client instance (for asWrapper(UA_Client*)) and to get access to the underlying
128 * client context.
129 */
130class Client {
131public:
132 /// Create client with default configuration.
134
135 /// Create client with given configuration (move ownership to client).
136 explicit Client(ClientConfig&& config);
137
138 /// Create client from native instance (move ownership to client).
140
142
143 Client(const Client&) = delete;
144 Client(Client&& other) noexcept;
145 Client& operator=(const Client&) = delete;
146 Client& operator=(Client&& other) noexcept;
147
148 ClientConfig& config() noexcept;
149 const ClientConfig& config() const noexcept;
150
151 /**
152 * Gets a list of all registered servers at the given server.
153 * @param serverUrl Server URL (for example `opc.tcp://localhost:4840`)
154 * @note Client must be disconnected.
155 */
156 std::vector<ApplicationDescription> findServers(std::string_view serverUrl);
157
158 /**
159 * Gets a list of endpoints of a server.
160 * @copydetails findServers
161 */
162 std::vector<EndpointDescription> getEndpoints(std::string_view serverUrl);
163
164 [[deprecated("use ClientConfig::addCustomDataTypes via config() or pass config to Client")]]
165 void setCustomDataTypes(Span<const DataType> dataTypes) {
166 config().addCustomDataTypes(dataTypes);
167 }
168
169 /// Set a state callback that will be called after the client is connected.
171 /// Set a state callback that will be called after the client is disconnected.
173 /// Set a state callback that will be called after the session is activated.
175 /// Set a state callback that will be called after the session is closed.
177 /// Set an inactivity callback.
178 /// Every UA_ClientConfig::connectivityCheckInterval (in ms), an async read request is performed
179 /// on the server. The callback is called when the client receives no response for this request.
181 /// Set a subscription inactivity callback.
182 /// The callback is called when the client does not receive a publish response after the defined
183 /// delay of `(publishingInterval * maxKeepAliveCount) + UA_ClientConfig::timeout)`.
185
186 /**
187 * Connect to the selected server.
188 * The session authentification method is defined by the UserIdentityToken and is set with
189 * Client::setUserIdentityToken.
190 * @param endpointUrl Endpoint URL (for example `opc.tcp://localhost:4840/open62541/server/`)
191 */
192 void connect(std::string_view endpointUrl);
193
194 /**
195 * Asynchronously connect to the selected server.
196 * Set a state callback, e.g. onConnected, to be notified when the connection status changes.
197 * @copydetails connect
198 */
199 void connectAsync(std::string_view endpointUrl);
200
201 /**
202 * Disconnect and close the connection to the server.
203 */
205
206 /**
207 * Asynchronously disconnect and close the connection to the server.
208 * Set a state callback, e.g. onDisconnected, to be notified when the connection status changes.
209 */
211
212 /// Check if client is connected (secure channel open).
213 bool isConnected() noexcept;
214
215 /// Get all defined namespaces.
216 std::vector<String> namespaceArray();
217
218#ifdef UA_ENABLE_SUBSCRIPTIONS
219 /// Create a subscription to monitor data changes and events.
220 /// @deprecated Use Subscription constructor
221 [[deprecated("use Subscription constructor")]]
223
224 /// Get all active subscriptions
225 std::vector<Subscription<Client>> subscriptions();
226#endif
227
228 /**
229 * Run a single iteration of the client's main loop.
230 * Listen on the network and process arriving asynchronous responses in the background.
231 * Internal housekeeping, renewal of SecureChannels and subscription management is done as well.
232 * @param timeoutMilliseconds Timeout in milliseconds
233 */
234 void runIterate(uint16_t timeoutMilliseconds = 1000);
235 /// Run the client's main loop by. This method will block until Client::stop is called.
236 void run();
237 /// Stop the client's main loop.
238 void stop();
239 /// Check if the client's main loop is running.
240 bool isRunning() const noexcept;
241
242 UA_Client* handle() noexcept;
243 const UA_Client* handle() const noexcept;
244
245private:
246 detail::ClientContext& context() noexcept;
247 const detail::ClientContext& context() const noexcept;
248
249 friend detail::ClientContext& detail::getContext(Client& client) noexcept;
250
251 struct Deleter {
252 void operator()(UA_Client* client) noexcept;
253 };
254
255 std::unique_ptr<detail::ClientContext> context_;
256 std::unique_ptr<UA_Client, Deleter> client_;
257};
258
259/// Convert native UA_Client pointer to its wrapper instance.
260/// The native client must be owned by a Client instance.
261/// @relates Client
262Client* asWrapper(UA_Client* client) noexcept;
263
264/// @relates Client
265inline bool operator==(const Client& lhs, const Client& rhs) noexcept {
266 return (lhs.handle() == rhs.handle());
267}
268
269/// @relates Client
270inline bool operator!=(const Client& lhs, const Client& rhs) noexcept {
271 return !(lhs == rhs);
272}
273
274} // namespace opcua
UA_ByteString wrapper class.
Definition types.hpp:537
Client configuration.
Definition client.hpp:38
ClientConfig(const ByteString &certificate, const ByteString &privateKey, Span< const ByteString > trustList, Span< const ByteString > revocationList={})
Create client config with encryption enabled (PKI).
ClientConfig(UA_ClientConfig &&native) noexcept
Definition client.hpp:73
void setTimeout(uint32_t milliseconds) noexcept
Set response timeout in milliseconds.
ClientConfig(const ClientConfig &)=delete
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).
ClientConfig(ClientConfig &&) noexcept=default
void addCustomDataTypes(Span< const DataType > types)
Add custom data types.
void setUserIdentityToken(const AnonymousIdentityToken &token)
Set anonymous identity token.
High-level client class.
Definition client.hpp:130
void disconnect()
Disconnect and close the connection to the server.
Client(Client &&other) noexcept
Client & operator=(const Client &)=delete
Client & operator=(Client &&other) noexcept
Client(const Client &)=delete
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:270
Client(ClientConfig &&config)
Create client with given configuration (move ownership to client).
bool operator==(const Client &lhs, const Client &rhs) noexcept
Definition client.hpp:265
void connect(std::string_view endpointUrl)
Connect to the selected server.
void onDisconnected(StateCallback callback)
Set a state callback that will be called after the client is disconnected.
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 onInactive(InactivityCallback callback)
Set an inactivity callback.
void disconnectAsync()
Asynchronously disconnect and close the connection to the server.
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).
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.
void onSubscriptionInactive(SubscriptionInactivityCallback callback)
Set a subscription inactivity callback.
void stop()
Stop the client's main loop.
bool isRunning() const noexcept
Check if the client's main loop is running.
UA_DataType wrapper class.
Definition datatype.hpp:111
View to a contiguous sequence of objects, similar to std::span in C++20.
Definition span.hpp:29
UA_String wrapper class.
Definition types.hpp:256
High-level subscription class.
Template base class to wrap (native) objects.
Definition wrapper.hpp:135
constexpr UA_ClientConfig * handle() noexcept
Return pointer to native object.
Definition wrapper.hpp:221
constexpr const UA_ClientConfig & native() const noexcept
Definition wrapper.hpp:243
UA_AnonymousIdentityToken wrapper class.
Definition types.hpp:644
UA_ApplicationDescription wrapper class.
Definition types.hpp:127
UA_EndpointDescription wrapper class.
Definition types.hpp:271
UA_IssuedIdentityToken wrapper class.
Definition types.hpp:697
UA_UserNameIdentityToken wrapper class.
Definition types.hpp:656
UA_X509IdentityToken wrapper class.
Definition types.hpp:680
MessageSecurityMode
Message security mode.
Definition types.hpp:215
uint32_t IntegerId
IntegerId.
Definition types.hpp:84
std::function< void(IntegerId subscriptionId)> SubscriptionInactivityCallback
Definition client.hpp:111
std::function< void()> StateCallback
Definition client.hpp:109
std::function< void(LogLevel, LogCategory, std::string_view msg)> LogFunction
Log function.
std::function< void()> InactivityCallback
Definition client.hpp:110
static void clear(UA_ClientConfig &config) noexcept
static UA_ClientConfig move(UA_ClientConfig &&config) noexcept
static UA_ClientConfig copy(const UA_ClientConfig &config)
Default type handler providing standard copy and move operations.
Definition wrapper.hpp:52
Subscription parameters with default values from open62541.