open62541pp 0.20.0
C++ wrapper of open62541
Loading...
Searching...
No Matches
server.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cstdint>
4#include <memory>
5#include <optional>
6#include <string_view>
7#include <utility> // move
8#include <vector>
9
10#include "open62541pp/common.hpp" // NamespaceIndex
11#include "open62541pp/config.hpp"
16#include "open62541pp/span.hpp"
17#include "open62541pp/types.hpp"
21
24#include "open62541pp/plugin/log_default.hpp" // LogFunction
26
27namespace opcua {
28
29/* ---------------------------------------- ServerConfig ---------------------------------------- */
30
31template <>
33 static UA_ServerConfig copy(const UA_ServerConfig& config);
34 static UA_ServerConfig move(UA_ServerConfig&& config) noexcept;
35 static void clear(UA_ServerConfig& config) noexcept;
36};
37
38/**
39 * Server configuration.
40 * @see UA_ServerConfig
41 */
42class ServerConfig : public Wrapper<UA_ServerConfig> {
43public:
44 /**
45 * Create server config with default configuration.
46 * Security policies:
47 * - [None](http://opcfoundation.org/UA/SecurityPolicy#None)
48 */
50
51 /**
52 * Create server config with minimal configuration.
53 * Security policies:
54 * - [None](http://opcfoundation.org/UA/SecurityPolicy#None)
55 *
56 * @param port Port number
57 * @param certificate Optional X.509 v3 certificate in `DER` encoded format
58 */
59 explicit ServerConfig(uint16_t port, const ByteString& certificate = {});
60
61#ifdef UA_ENABLE_ENCRYPTION
62 /**
63 * Create server config with encryption enabled (PKI).
64 * Security policies:
65 * - [None](http://opcfoundation.org/UA/SecurityPolicy#None)
66 * - [Basic128Rsa15](http://opcfoundation.org/UA/SecurityPolicy#Basic128Rsa15)
67 * - [Basic256](http://opcfoundation.org/UA/SecurityPolicy#Basic256)
68 * - [Basic256Sha256](http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256)
69 * - [Aes128_Sha256_RsaOaep](http://opcfoundation.org/UA/SecurityPolicy#Aes128_Sha256_RsaOaep)
70 *
71 * @param port Port number
72 * @param certificate X.509 v3 certificate in `DER` encoded format
73 * @param privateKey Private key in `PEM` encoded format
74 * @param trustList List of trusted certificates in `DER` encoded format
75 * @param issuerList List of issuer certificates (i.e. CAs) in `DER` encoded format
76 * @param revocationList Certificate revocation lists (CRL) in `DER` encoded format
77 *
78 * @see https://reference.opcfoundation.org/Core/Part2/v105/docs/9
79 * @see https://reference.opcfoundation.org/Core/Part4/v105/docs/6.1
80 * @see https://reference.opcfoundation.org/Core/Part6/v105/docs/6.2
81 */
83 uint16_t port,
84 const ByteString& certificate,
85 const ByteString& privateKey,
86 Span<const ByteString> trustList,
87 Span<const ByteString> issuerList,
88 Span<const ByteString> revocationList = {}
89 );
90#endif
91
93 : Wrapper{std::move(native)} {} // NOLINT
94
95 ServerConfig(const ServerConfig&) = delete;
96 ServerConfig(ServerConfig&&) noexcept = default;
97 ServerConfig& operator=(const ServerConfig&) = delete;
98 ServerConfig& operator=(ServerConfig&&) noexcept = default;
99
100 ~ServerConfig() noexcept = default;
101
103
104 void setBuildInfo(BuildInfo buildInfo);
105
106 /// Set application URI, default: `urn:open62541.server.application`.
107 void setApplicationUri(std::string_view uri);
108 /// Set product URI, default: `http://open62541.org`.
109 void setProductUri(std::string_view uri);
110 /// Set application name, default: `open62541-based OPC UA Application`.
111 void setApplicationName(std::string_view name);
112
113 /// Add custom data types.
114 /// All data types provided are automatically considered for decoding of received messages.
115 void addCustomDataTypes(Span<const DataType> types);
116
117 /// Set custom access control.
119 /// Set custom access control (transfer ownership to Server).
120 void setAccessControl(std::unique_ptr<AccessControlBase>&& accessControl);
121};
122
123/* ------------------------------------------- Server ------------------------------------------- */
124
125/**
126 * High-level server class.
127 *
128 * A server is usually created in two steps:
129 * 1. Create and modify a server configuration (ServerConfig)
130 * 2. Create a Server with a ServerConfig (move ownership to the Server instance)
131 *
132 * The server expects that the configuration is not modified during runtime.
133 *
134 * Use the handle() method to get access the underlying UA_Server instance and use the full power
135 * of open62541.
136 *
137 * Don't overwrite the UA_ServerConfig::context pointer! The context pointer is used to store a
138 * pointer to the Server instance (for asWrapper(UA_Server*)) and to get access to the underlying
139 * server context.
140 */
141class Server {
142public:
143 /// Create server with default configuration.
145
146 /// Create server with given configuration (move ownership to server).
147 explicit Server(ServerConfig&& config);
148
149 /// Create server from native instance (move ownership to server).
151
153
154 Server(const Server&) = delete;
155 Server(Server&& other) noexcept;
156 Server& operator=(const Server&) = delete;
157 Server& operator=(Server&& other) noexcept;
158
159 ServerConfig& config() noexcept;
160 const ServerConfig& config() const noexcept;
161
162 [[deprecated("use ServerConfig::addCustomDataTypes via config() or pass config to Server")]]
163 void setCustomDataTypes(Span<const DataType> dataTypes) {
164 config().addCustomDataTypes(dataTypes);
165 }
166
167 /// Get active sessions.
168 std::vector<Session> sessions();
169
170 /// Get all defined namespaces.
171 std::vector<String> namespaceArray();
172 /// Get namespace index for given URI.
173 std::optional<NamespaceIndex> namespaceIndex(std::string_view uri) noexcept;
174
175 /// Register namespace. The new namespace index will be returned.
176 [[nodiscard]] NamespaceIndex registerNamespace(std::string_view uri);
177
178 [[deprecated("use free function setVariableNodeValueCallback instead")]]
180 [[deprecated("use free function setVariableNodeValueCallback instead")]]
182 const NodeId& id, std::unique_ptr<ValueCallbackBase>&& callback
183 );
184 [[deprecated("use free function setVariableNodeValueBackend instead")]]
186 [[deprecated("use free function setVariableNodeValueBackend instead")]]
187 void setVariableNodeDataSource(const NodeId& id, std::unique_ptr<DataSourceBase>&& source);
188
189 /// Run a single iteration of the server's main loop.
190 /// @return Maximum wait period until next Server::runIterate call (in ms)
191 uint16_t runIterate();
192 /// Run the server's main loop. This method will block until Server::stop is called.
193 void run();
194 /// Stop the server's main loop.
195 void stop();
196 /// Check if the server is running.
197 bool isRunning() const noexcept;
198
199 UA_Server* handle() noexcept;
200 const UA_Server* handle() const noexcept;
201
202private:
203 detail::ServerContext& context() noexcept;
204 const detail::ServerContext& context() const noexcept;
205
206 friend detail::ServerContext& detail::getContext(Server& server) noexcept;
207
208 struct Deleter {
209 void operator()(UA_Server* server) const noexcept;
210 };
211
212 std::unique_ptr<detail::ServerContext> context_;
213 std::unique_ptr<UA_Server, Deleter> server_;
214};
215
216/// Convert native UA_Server pointer to its wrapper instance.
217/// The native server must be owned by a Server instance.
218/// @relates Server
219Server* asWrapper(UA_Server* server) noexcept;
220
221/// @relates Server
222inline bool operator==(const Server& lhs, const Server& rhs) noexcept {
223 return (lhs.handle() == rhs.handle());
224}
225
226/// @relates Server
227inline bool operator!=(const Server& lhs, const Server& rhs) noexcept {
228 return !(lhs == rhs);
229}
230
231/* -------------------------------------- Utility functions ------------------------------------- */
232
233inline const UA_DataType* findDataType(Server& server, const NodeId& id) noexcept {
234 return findDataType(id, server.config()->customDataTypes);
235}
236
237/* ---------------------------- Variable node value backend/callback ---------------------------- */
238
239/// Set value callback for variable node.
241/// Set value callback for variable node (move ownership to server).
243 Server& server, const NodeId& id, std::unique_ptr<ValueCallbackBase>&& callback
244);
245
246/// Set data source value backend for variable node.
247void setVariableNodeValueBackend(Server& server, const NodeId& id, DataSourceBase& source);
248/// Set data source value backend for variable node (move ownership to server).
250 Server& server, const NodeId& id, std::unique_ptr<DataSourceBase>&& source
251);
252
253/* -------------------------------------- Async operations -------------------------------------- */
254
255#if UAPP_HAS_ASYNC_OPERATIONS
256/// Enable or disable async operations for the specified node.
257/// When enabled, operations on the node are queued and must processed by a worker thread using
258/// @ref runAsyncOperation.
259/// @note Only supported for method nodes.
260/// @relates Server
261void useAsyncOperation(Server& server, const NodeId& id, bool enabled);
262
263/// Wraps an async operation request.
265 UA_AsyncOperationType type;
266 const UA_AsyncOperationRequest* request;
267 void* context;
268};
269
270/// Get the next queued async operation if available.
271/// Async operations are queued by nodes with async operations enabled (see @ref useAsyncOperation).
272/// @relates Server
273std::optional<AsyncOperation> getAsyncOperation(Server& server) noexcept;
274
275/// Run the provided async operation.
276/// @relates Server
277void runAsyncOperation(Server& server, const AsyncOperation& operation);
278#endif
279
280} // namespace opcua
Access control base class.
UA_ByteString wrapper class.
Definition types.hpp:548
Data source base class for variable nodes.
Definition nodestore.hpp:60
UA_DataType wrapper class.
Definition datatype.hpp:111
UA_NodeId wrapper class.
Definition types.hpp:652
Server configuration.
Definition server.hpp:42
ServerConfig(uint16_t port, const ByteString &certificate={})
Create server config with minimal configuration.
void setApplicationName(std::string_view name)
Set application name, default: open62541-based OPC UA Application.
ServerConfig()
Create server config with default configuration.
void setLogger(LogFunction func)
ServerConfig(ServerConfig &&) noexcept=default
void setAccessControl(AccessControlBase &accessControl)
Set custom access control.
ServerConfig(const ServerConfig &)=delete
void addCustomDataTypes(Span< const DataType > types)
Add custom data types.
ServerConfig(UA_ServerConfig &&native)
Definition server.hpp:92
void setProductUri(std::string_view uri)
Set product URI, default: http://open62541.org.
void setBuildInfo(BuildInfo buildInfo)
void setApplicationUri(std::string_view uri)
Set application URI, default: urn:open62541.server.application.
ServerConfig(uint16_t port, const ByteString &certificate, const ByteString &privateKey, Span< const ByteString > trustList, Span< const ByteString > issuerList, Span< const ByteString > revocationList={})
Create server config with encryption enabled (PKI).
High-level server class.
Definition server.hpp:141
bool operator==(const Server &lhs, const Server &rhs) noexcept
Definition server.hpp:222
Server(UA_Server *native)
Create server from native instance (move ownership to server).
std::optional< NamespaceIndex > namespaceIndex(std::string_view uri) noexcept
Get namespace index for given URI.
NamespaceIndex registerNamespace(std::string_view uri)
Register namespace. The new namespace index will be returned.
void stop()
Stop the server's main loop.
void setVariableNodeDataSource(const NodeId &id, DataSourceBase &source)
Server(Server &&other) noexcept
void run()
Run the server's main loop. This method will block until Server::stop is called.
uint16_t runIterate()
Run a single iteration of the server's main loop.
Server & operator=(const Server &)=delete
ServerConfig & config() noexcept
void setVariableNodeValueCallback(const NodeId &id, ValueCallbackBase &callback)
std::vector< Session > sessions()
Get active sessions.
Server & operator=(Server &&other) noexcept
Server(ServerConfig &&config)
Create server with given configuration (move ownership to server).
bool operator!=(const Server &lhs, const Server &rhs) noexcept
Definition server.hpp:227
Server()
Create server with default configuration.
std::optional< AsyncOperation > getAsyncOperation(Server &server) noexcept
Get the next queued async operation if available.
Server * asWrapper(UA_Server *server) noexcept
Convert native UA_Server pointer to its wrapper instance.
bool isRunning() const noexcept
Check if the server is running.
Server(const Server &)=delete
void setVariableNodeDataSource(const NodeId &id, std::unique_ptr< DataSourceBase > &&source)
void runAsyncOperation(Server &server, const AsyncOperation &operation)
Run the provided async operation.
void setVariableNodeValueCallback(const NodeId &id, std::unique_ptr< ValueCallbackBase > &&callback)
void useAsyncOperation(Server &server, const NodeId &id, bool enabled)
Enable or disable async operations for the specified node.
std::vector< String > namespaceArray()
Get all defined namespaces.
View to a contiguous sequence of objects, similar to std::span in C++20.
Definition span.hpp:29
Value callback base class for variable nodes.
Definition nodestore.hpp:18
Template base class to wrap (native) objects.
Definition wrapper.hpp:135
constexpr UA_ServerConfig * handle() noexcept
Return pointer to native object.
Definition wrapper.hpp:221
constexpr const UA_ServerConfig & native() const noexcept
Definition wrapper.hpp:243
UA_BuildInfo wrapper class.
Definition types.hpp:1483
uint16_t NamespaceIndex
Namespace index.
Definition common.hpp:12
std::function< void(LogLevel, LogCategory, std::string_view msg)> LogFunction
Log function.
void setVariableNodeValueCallback(Server &server, const NodeId &id, ValueCallbackBase &callback)
Set value callback for variable node.
const UA_DataType * findDataType(Client &client, const NodeId &id) noexcept
Definition client.hpp:271
void setVariableNodeValueBackend(Server &server, const NodeId &id, DataSourceBase &source)
Set data source value backend for variable node.
Wraps an async operation request.
Definition server.hpp:264
const UA_AsyncOperationRequest * request
Definition server.hpp:266
UA_AsyncOperationType type
Definition server.hpp:265
static UA_ServerConfig copy(const UA_ServerConfig &config)
static UA_ServerConfig move(UA_ServerConfig &&config) noexcept
static void clear(UA_ServerConfig &config) noexcept
Default type handler providing standard copy and move operations.
Definition wrapper.hpp:52