Coverage Report

Created: 2025-07-11 07:04

/src/open62541/include/open62541/server.h
Line
Count
Source (jump to first uncovered line)
1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
 * License, v. 2.0. If a copy of the MPL was not distributed with this
3
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
 *
5
 *    Copyright 2014-2024 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
6
 *    Copyright 2015-2016 (c) Sten GrĂ¼ner
7
 *    Copyright 2014-2015, 2017 (c) Florian Palm
8
 *    Copyright 2015-2016 (c) Chris Iatrou
9
 *    Copyright 2015-2016 (c) Oleksiy Vasylyev
10
 *    Copyright 2016-2017 (c) Stefan Profanter, fortiss GmbH
11
 *    Copyright 2017 (c) Henrik Norrman
12
 *    Copyright 2018 (c) Fabian Arndt, Root-Core
13
 *    Copyright 2017-2020 (c) HMS Industrial Networks AB (Author: Jonas Green)
14
 *    Copyright 2020-2022 (c) Christian von Arnim, ISW University of Stuttgart  (for VDW and umati)
15
 */
16
17
#ifndef UA_SERVER_H_
18
#define UA_SERVER_H_
19
20
#include <open62541/types.h>
21
#include <open62541/common.h>
22
#include <open62541/util.h>
23
24
#include <open62541/plugin/log.h>
25
#include <open62541/plugin/certificategroup.h>
26
#include <open62541/plugin/nodestore.h>
27
#include <open62541/plugin/eventloop.h>
28
#include <open62541/plugin/accesscontrol.h>
29
#include <open62541/plugin/securitypolicy.h>
30
31
#include <open62541/client.h>
32
33
#ifdef UA_ENABLE_PUBSUB
34
#include <open62541/server_pubsub.h>
35
#endif
36
37
#ifdef UA_ENABLE_HISTORIZING
38
#include <open62541/plugin/historydatabase.h>
39
#endif
40
41
_UA_BEGIN_DECLS
42
43
/* Forward declarations */
44
typedef void (*UA_Server_AsyncOperationNotifyCallback)(UA_Server *server);
45
46
/**
47
 * .. _server:
48
 *
49
 * Server
50
 * ======
51
 *
52
 * .. _server-configuration:
53
 *
54
 * Server Configuration
55
 * --------------------
56
 * The configuration structure is passed to the server during initialization.
57
 * The server expects that the configuration is not modified during runtime.
58
 * Currently, only one server can use a configuration at a time. During
59
 * shutdown, the server will clean up the parts of the configuration that are
60
 * modified at runtime through the provided API.
61
 *
62
 * Examples for configurations are provided in the ``/plugins`` folder.
63
 * The usual usage is as follows:
64
 *
65
 * 1. Create a server configuration with default settings as a starting point
66
 * 2. Modifiy the configuration, e.g. by adding a server certificate
67
 * 3. Instantiate a server with it
68
 * 4. After shutdown of the server, clean up the configuration (free memory)
69
 *
70
 * The :ref:`tutorials` provide a good starting point for this. */
71
72
struct UA_ServerConfig {
73
    void *context; /* Used to attach custom data to a server config. This can
74
                    * then be retrieved e.g. in a callback that forwards a
75
                    * pointer to the server. */
76
    UA_Logger *logging; /* Plugin for log output */
77
78
    /* Server Description
79
     * ~~~~~~~~~~~~~~~~~~
80
     * The description must be internally consistent. The ApplicationUri set in
81
     * the ApplicationDescription must match the URI set in the server
82
     * certificate.
83
     * The applicationType is not just descriptive, it changes the actual
84
     * functionality of the server. The RegisterServer service is available only
85
     * if the server is a DiscoveryServer and the applicationType is set to the
86
     * appropriate value.*/
87
    UA_BuildInfo buildInfo;
88
    UA_ApplicationDescription applicationDescription;
89
90
    /* Server Lifecycle
91
     * ~~~~~~~~~~~~~~~~
92
     * Delay in ms from the shutdown signal (ctrl-c) until the actual shutdown.
93
     * Clients need to be able to get a notification ahead of time. */
94
    UA_Double shutdownDelay;
95
96
    /* If an asynchronous server shutdown is used, this callback notifies about
97
     * the current lifecycle state (notably the STOPPING -> STOPPED
98
     * transition). */
99
    void (*notifyLifecycleState)(UA_Server *server, UA_LifecycleState state);
100
101
    /* Rule Handling
102
     * ~~~~~~~~~~~~~
103
     * Override the handling of standard-defined behavior. These settings are
104
     * used to balance the following contradicting requirements:
105
     *
106
     * - Strict conformance with the standard (for certification).
107
     * - Ensure interoperability with old/non-conforming implementations
108
     *   encountered in the wild.
109
     *
110
     * The defaults are set for compatibility with the largest number of OPC UA
111
     * vendors (with log warnings activated). Cf. Postel's Law "be conservative
112
     * in what you send, be liberal in what you accept".
113
     *
114
     * See the section :ref:`rule-handling` for the possible settings. */
115
116
    /* Verify that the server sends a timestamp in the request header */
117
    UA_RuleHandling verifyRequestTimestamp;
118
119
    /* Variables (that don't have a DataType of BaseDataType) must not have an
120
     * empty variant value. The default behaviour is to auto-create a matching
121
     * zeroed-out value for empty VariableNodes when they are added. */
122
    UA_RuleHandling allowEmptyVariables;
123
124
    UA_RuleHandling allowAllCertificateUris;
125
126
    /* Custom Data Types
127
     * ~~~~~~~~~~~~~~~~~
128
     * The following is a linked list of arrays with custom data types. All data
129
     * types that are accessible from here are automatically considered for the
130
     * decoding of received messages. Custom data types are not cleaned up
131
     * together with the configuration. So it is possible to allocate them on
132
     * ROM.
133
     *
134
     * See the section on :ref:`generic-types`. Examples for working with custom
135
     * data types are provided in ``/examples/custom_datatype/``. */
136
    const UA_DataTypeArray *customDataTypes;
137
138
    /* EventLoop
139
     * ~~~~~~~~~
140
     * The sever can be plugged into an external EventLoop. Otherwise the
141
     * EventLoop is considered to be attached to the server's lifecycle and will
142
     * be destroyed when the config is cleaned up. */
143
    UA_EventLoop *eventLoop;
144
    UA_Boolean externalEventLoop; /* The EventLoop is not deleted with the config */
145
146
    /* Networking
147
     * ~~~~~~~~~~
148
     * The `severUrls` array contains the server URLs like
149
     * `opc.tcp://my-server:4840` or `opc.wss://localhost:443`. The URLs are
150
     * used both for discovery and to set up the server sockets based on the
151
     * defined hostnames (and ports).
152
     *
153
     * - If the list is empty: Listen on all network interfaces with TCP port 4840.
154
     * - If the hostname of a URL is empty: Use the define protocol and port and
155
     *   listen on all interfaces. */
156
    UA_String *serverUrls;
157
    size_t serverUrlsSize;
158
159
    /* The following settings are specific to OPC UA with TCP transport. */
160
    UA_Boolean tcpEnabled;
161
    UA_UInt32 tcpBufSize;    /* Max length of sent and received chunks (packets)
162
                              * (default: 64kB) */
163
    UA_UInt32 tcpMaxMsgSize; /* Max length of messages
164
                              * (default: 0 -> unbounded) */
165
    UA_UInt32 tcpMaxChunks;  /* Max number of chunks per message
166
                              * (default: 0 -> unbounded) */
167
    UA_Boolean tcpReuseAddr;
168
169
    /* Security and Encryption
170
     * ~~~~~~~~~~~~~~~~~~~~~~~ */
171
    size_t securityPoliciesSize;
172
    UA_SecurityPolicy* securityPolicies;
173
174
    /* Endpoints with combinations of SecurityPolicy and SecurityMode. If the
175
     * UserIdentityToken array of the Endpoint is not set, then it will be
176
     * filled by the server for all UserTokenPolicies that are configured in the
177
     * AccessControl plugin. */
178
    size_t endpointsSize;
179
    UA_EndpointDescription *endpoints;
180
181
    /* Only allow the following discovery services to be executed on a
182
     * SecureChannel with SecurityPolicyNone: GetEndpointsRequest,
183
     * FindServersRequest and FindServersOnNetworkRequest.
184
     *
185
     * Only enable this option if there is no endpoint with SecurityPolicy#None
186
     * in the endpoints list. The SecurityPolicy#None must be present in the
187
     * securityPolicies list. */
188
    UA_Boolean securityPolicyNoneDiscoveryOnly;
189
190
    /* Allow clients without encryption support to connect with username and password.
191
     * This requires to transmit the password in plain text over the network which is
192
     * why this option is disabled by default.
193
     * Make sure you really need this before enabling plain text passwords. */
194
    UA_Boolean allowNonePolicyPassword;
195
196
    /* Different sets of certificates are trusted for SecureChannel / Session */
197
    UA_CertificateGroup secureChannelPKI;
198
    UA_CertificateGroup sessionPKI;
199
200
    /* See the AccessControl Plugin API */
201
    UA_AccessControl accessControl;
202
203
    /* Nodes and Node Lifecycle
204
     * ~~~~~~~~~~~~~~~~~~~~~~~~
205
     * See the section for :ref:`node lifecycle handling<node-lifecycle>`. */
206
    UA_Nodestore nodestore;
207
    UA_GlobalNodeLifecycle nodeLifecycle;
208
209
    /* Copy the HasModellingRule reference in instances from the type
210
     * definition in UA_Server_addObjectNode and UA_Server_addVariableNode.
211
     *
212
     * Part 3 - 6.4.4: [...] it is not required that newly created or referenced
213
     * instances based on InstanceDeclarations have a ModellingRule, however, it
214
     * is allowed that they have any ModellingRule independent of the
215
     * ModellingRule of their InstanceDeclaration */
216
    UA_Boolean modellingRulesOnInstances;
217
218
    /* Limits
219
     * ~~~~~~ */
220
    /* Limits for SecureChannels */
221
    UA_UInt16 maxSecureChannels;
222
    UA_UInt32 maxSecurityTokenLifetime; /* in ms */
223
224
    /* Limits for Sessions */
225
    UA_UInt16 maxSessions;
226
    UA_Double maxSessionTimeout; /* in ms */
227
228
    /* Operation limits */
229
    UA_UInt32 maxNodesPerRead;
230
    UA_UInt32 maxNodesPerWrite;
231
    UA_UInt32 maxNodesPerMethodCall;
232
    UA_UInt32 maxNodesPerBrowse;
233
    UA_UInt32 maxNodesPerRegisterNodes;
234
    UA_UInt32 maxNodesPerTranslateBrowsePathsToNodeIds;
235
    UA_UInt32 maxNodesPerNodeManagement;
236
    UA_UInt32 maxMonitoredItemsPerCall;
237
238
    /* Limits for Requests */
239
    UA_UInt32 maxReferencesPerNode;
240
241
#ifdef UA_ENABLE_ENCRYPTION
242
    /* Limits for TrustList */
243
    UA_UInt32 maxTrustListSize; /* in bytes, 0 => unlimited */
244
    UA_UInt32 maxRejectedListSize; /* 0 => unlimited */
245
#endif
246
247
    /* Async Operations
248
     * ~~~~~~~~~~~~~~~~
249
     * See the section for :ref:`async operations<async-operations>`. */
250
#if UA_MULTITHREADING >= 100
251
    UA_Double asyncOperationTimeout; /* in ms, 0 => unlimited */
252
    size_t maxAsyncOperationQueueSize; /* 0 => unlimited */
253
    /* Notify workers when an async operation was enqueued */
254
    UA_Server_AsyncOperationNotifyCallback asyncOperationNotifyCallback;
255
#endif
256
257
    /* Discovery
258
     * ~~~~~~~~~ */
259
#ifdef UA_ENABLE_DISCOVERY
260
    /* Timeout in seconds when to automatically remove a registered server from
261
     * the list, if it doesn't re-register within the given time frame. A value
262
     * of 0 disables automatic removal. Default is 60 Minutes (60*60). Must be
263
     * bigger than 10 seconds, because cleanup is only triggered approximately
264
     * every 10 seconds. The server will still be removed depending on the
265
     * state of the semaphore file. */
266
    UA_UInt32 discoveryCleanupTimeout;
267
268
# ifdef UA_ENABLE_DISCOVERY_MULTICAST
269
    UA_Boolean mdnsEnabled;
270
    UA_MdnsDiscoveryConfiguration mdnsConfig;
271
#  ifdef UA_ENABLE_DISCOVERY_MULTICAST_MDNSD
272
    UA_String mdnsInterfaceIP;
273
#   if !defined(UA_HAS_GETIFADDR)
274
    size_t mdnsIpAddressListSize;
275
    UA_UInt32 *mdnsIpAddressList;
276
#   endif
277
#  endif
278
# endif
279
#endif
280
281
    /* Subscriptions
282
     * ~~~~~~~~~~~~~ */
283
    UA_Boolean subscriptionsEnabled;
284
#ifdef UA_ENABLE_SUBSCRIPTIONS
285
    /* Limits for Subscriptions */
286
    UA_UInt32 maxSubscriptions;
287
    UA_UInt32 maxSubscriptionsPerSession;
288
    UA_DurationRange publishingIntervalLimits; /* in ms (must not be less than 5) */
289
    UA_UInt32Range lifeTimeCountLimits;
290
    UA_UInt32Range keepAliveCountLimits;
291
    UA_UInt32 maxNotificationsPerPublish;
292
    UA_Boolean enableRetransmissionQueue;
293
    UA_UInt32 maxRetransmissionQueueSize; /* 0 -> unlimited size */
294
# ifdef UA_ENABLE_SUBSCRIPTIONS_EVENTS
295
    UA_UInt32 maxEventsPerNode; /* 0 -> unlimited size */
296
# endif
297
298
    /* Limits for MonitoredItems */
299
    UA_UInt32 maxMonitoredItems;
300
    UA_UInt32 maxMonitoredItemsPerSubscription;
301
    UA_DurationRange samplingIntervalLimits; /* in ms (must not be less than 5) */
302
    UA_UInt32Range queueSizeLimits; /* Negotiated with the client */
303
304
    /* Limits for PublishRequests */
305
    UA_UInt32 maxPublishReqPerSession;
306
307
    /* Register MonitoredItem in Userland
308
     *
309
     * @param server Allows the access to the server object
310
     * @param sessionId The session id, represented as an node id
311
     * @param sessionContext An optional pointer to user-defined data for the
312
     *        specific data source
313
     * @param nodeid Id of the node in question
314
     * @param nodeidContext An optional pointer to user-defined data, associated
315
     *        with the node in the nodestore. Note that, if the node has already
316
     *        been removed, this value contains a NULL pointer.
317
     * @param attributeId Identifies which attribute (value, data type etc.) is
318
     *        monitored
319
     * @param removed Determines if the MonitoredItem was removed or created. */
320
    void (*monitoredItemRegisterCallback)(UA_Server *server,
321
                                          const UA_NodeId *sessionId,
322
                                          void *sessionContext,
323
                                          const UA_NodeId *nodeId,
324
                                          void *nodeContext,
325
                                          UA_UInt32 attibuteId,
326
                                          UA_Boolean removed);
327
#endif
328
329
    /* PubSub
330
     * ~~~~~~ */
331
#ifdef UA_ENABLE_PUBSUB
332
    UA_Boolean pubsubEnabled;
333
    UA_PubSubConfiguration pubSubConfig;
334
#endif
335
336
    /* Historical Access
337
     * ~~~~~~~~~~~~~~~~~ */
338
    UA_Boolean historizingEnabled;
339
#ifdef UA_ENABLE_HISTORIZING
340
    UA_HistoryDatabase historyDatabase;
341
342
    UA_Boolean accessHistoryDataCapability;
343
    UA_UInt32  maxReturnDataValues; /* 0 -> unlimited size */
344
345
    UA_Boolean accessHistoryEventsCapability;
346
    UA_UInt32  maxReturnEventValues; /* 0 -> unlimited size */
347
348
    UA_Boolean insertDataCapability;
349
    UA_Boolean insertEventCapability;
350
    UA_Boolean insertAnnotationsCapability;
351
352
    UA_Boolean replaceDataCapability;
353
    UA_Boolean replaceEventCapability;
354
355
    UA_Boolean updateDataCapability;
356
    UA_Boolean updateEventCapability;
357
358
    UA_Boolean deleteRawCapability;
359
    UA_Boolean deleteEventCapability;
360
    UA_Boolean deleteAtTimeDataCapability;
361
#endif
362
363
    /* Reverse Connect
364
     * ~~~~~~~~~~~~~~~ */
365
    UA_UInt32 reverseReconnectInterval; /* Default is 15000 ms */
366
367
    /* Certificate Password Callback
368
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
369
#ifdef UA_ENABLE_ENCRYPTION
370
    /* If the private key is in PEM format and password protected, this callback
371
     * is called during initialization to get the password to decrypt the
372
     * private key. The memory containing the password is freed by the client
373
     * after use. The callback should be set early, other parts of the client
374
     * config setup may depend on it. */
375
    UA_StatusCode (*privateKeyPasswordCallback)(UA_ServerConfig *sc,
376
                                                UA_ByteString *password);
377
#endif
378
};
379
380
void UA_EXPORT
381
UA_ServerConfig_clear(UA_ServerConfig *config);
382
383
UA_DEPRECATED static UA_INLINE void
384
0
UA_ServerConfig_clean(UA_ServerConfig *config) {
385
0
    UA_ServerConfig_clear(config);
386
0
}
Unexecuted instantiation: fuzz_binary_message.cc:UA_ServerConfig_clean(UA_ServerConfig*)
Unexecuted instantiation: ua_util.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_session.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_nodes.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_ns0.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_ns0_diagnostics.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_ns0_gds.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_config.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_binary.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_utils.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_server_async.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_view.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_method.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_session.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_attribute.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_discovery.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_subscription.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_monitoreditem.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_securechannel.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_services_nodemanagement.c:UA_ServerConfig_clean
Unexecuted instantiation: namespace0_generated.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_connection.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_dataset.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_writer.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_writergroup.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_reader.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_readergroup.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_manager.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_ns0.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_pubsub_keystorage.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_subscription.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_subscription_datachange.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_subscription_event.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_subscription_eventfilter.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_discovery_mdns.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_discovery.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_accesscontrol_default.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_config_default.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_config_json.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_history_data_backend_memory.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_history_data_gathering_default.c:UA_ServerConfig_clean
Unexecuted instantiation: ua_history_database_default.c:UA_ServerConfig_clean
387
388
/**
389
 * .. _server-lifecycle:
390
 *
391
 * Server Lifecycle
392
 * ----------------
393
 *
394
 * The server continuously listens on the network to consume incoming messages.
395
 * Furthermore the server internally registers timed callbacks. For the control
396
 * flow of the server, these are the options (with increasing complexity):
397
 *
398
 * - Run ``UA_Server_runUntilInterrupt`` or similar.
399
 * - Run ``UA_Server_run_startup`` followed by repeated calls of
400
 *   ``UA_Server_run_iterate`` during the server lifetime.
401
 * - Configure an external EventLoop and run ``UA_Server_run_startup`` to
402
 *   register sockets and timed callbacks. */
403
404
/* Create a new server with a default configuration that adds plugins for
405
 * networking, security, logging and so on. See `server_config_default.h` for
406
 * more detailed options.
407
 *
408
 * The default configuration can be used as the starting point to adjust the
409
 * server configuration to individual needs. UA_Server_new is implemented in the
410
 * /plugins folder under the CC0 license. Furthermore the server confiugration
411
 * only uses the public server API.
412
 *
413
 * Returns the configured server or NULL if an error occurs. */
414
UA_EXPORT UA_Server *
415
UA_Server_new(void);
416
417
/* Creates a new server. Moves the config into the server with a shallow copy.
418
 * The config content is cleared together with the server. */
419
UA_EXPORT UA_Server *
420
UA_Server_newWithConfig(UA_ServerConfig *config);
421
422
/* Delete the server. */
423
UA_EXPORT UA_StatusCode
424
UA_Server_delete(UA_Server *server);
425
426
/* Get the configuration. Always succeeds as this simplfy resolves a pointer.
427
 * Attention! Do not adjust the configuration while the server is running! */
428
UA_EXPORT UA_ServerConfig *
429
UA_Server_getConfig(UA_Server *server);
430
431
/* Get the current server lifecycle state */
432
UA_EXPORT UA_LifecycleState
433
UA_Server_getLifecycleState(UA_Server *server);
434
435
/* Runs the server until until "running" is set to false. The logical sequence
436
 * is as follows:
437
 *
438
 * - UA_Server_run_startup
439
 * - Loop until interrupt: UA_Server_run_iterate
440
 * - UA_Server_run_shutdown */
441
UA_EXPORT UA_StatusCode
442
UA_Server_run(UA_Server *server, const volatile UA_Boolean *running);
443
444
/* Runs the server until interrupted. On Unix/Windows this registers an
445
 * interrupt for SIGINT (ctrl-c). The method only returns after having received
446
 * the interrupt or upon an error condition. The logical sequence is as follows:
447
 *
448
 * - Register the interrupt
449
 * - UA_Server_run_startup
450
 * - Loop until interrupt: UA_Server_run_iterate
451
 * - UA_Server_run_shutdown
452
 * - Deregister the interrupt
453
 *
454
 * Attention! This method is implemented individually for the different
455
 * platforms (POSIX/Win32/etc.). The default implementation is in
456
 * /plugins/ua_config_default.c under the CC0 license. Adjust as needed. */
457
UA_EXPORT UA_StatusCode
458
UA_Server_runUntilInterrupt(UA_Server *server);
459
460
/* The prologue part of UA_Server_run (no need to use if you call
461
 * UA_Server_run or UA_Server_runUntilInterrupt) */
462
UA_EXPORT UA_StatusCode
463
UA_Server_run_startup(UA_Server *server);
464
465
/* Executes a single iteration of the server's main loop.
466
 *
467
 * @param server The server object.
468
 * @param waitInternal Should we wait for messages in the networklayer?
469
 *        Otherwise, the timeouts for the networklayers are set to zero.
470
 *        The default max wait time is 200ms.
471
 * @return Returns how long we can wait until the next scheduled
472
 *         callback (in ms) */
473
UA_EXPORT UA_UInt16
474
UA_Server_run_iterate(UA_Server *server, UA_Boolean waitInternal);
475
476
/* The epilogue part of UA_Server_run (no need to use if you call
477
 * UA_Server_run or UA_Server_runUntilInterrupt) */
478
UA_EXPORT UA_StatusCode
479
UA_Server_run_shutdown(UA_Server *server);
480
481
/**
482
 * Session Handling
483
 * ----------------
484
 * A new session is announced via the AccessControl plugin. The session
485
 * identifier is forwarded to the relevant callbacks back into userland. The
486
 * following methods enable an interaction with a particular session. */
487
488
/* Manually close a session */
489
UA_EXPORT UA_StatusCode UA_THREADSAFE
490
UA_Server_closeSession(UA_Server *server, const UA_NodeId *sessionId);
491
492
/**
493
 * Session attributes: Besides the user-definable session context pointer (set
494
 * by the AccessControl plugin when the Session is created), a session carries
495
 * attributes in a key-value list. Some attributes are present in every session
496
 * and shown in the list below. Additional attributes can be manually set as
497
 * meta-data.
498
 *
499
 * Always present as session attributes are:
500
 *
501
 * - ``0:localeIds`` (``UA_String``): List of preferred languages (read-only)
502
 * - ``0:clientDescription`` (``UA_ApplicationDescription``): Client description (read-only)
503
 * - ``0:sessionName`` (``String``): Client-defined name of the session (read-only)
504
 * - ``0:clientUserId`` (``String``): User identifier used to activate the session (read-only) */
505
506
/* Returns a shallow copy of the attribute. Don't _clear or _delete the value
507
 * variant. Don't use the value once the Session could be already closed in the
508
 * background or the attribute of the session replaced. Hence don't use this in a
509
 * multi-threaded application. */
510
UA_EXPORT UA_StatusCode
511
UA_Server_getSessionAttribute(UA_Server *server, const UA_NodeId *sessionId,
512
                              const UA_QualifiedName key, UA_Variant *outValue);
513
514
/* Return a deep copy of the attribute */
515
UA_EXPORT UA_StatusCode UA_THREADSAFE
516
UA_Server_getSessionAttributeCopy(UA_Server *server, const UA_NodeId *sessionId,
517
                                  const UA_QualifiedName key, UA_Variant *outValue);
518
519
/* Returns NULL if the attribute is not defined or not a scalar or not of the
520
 * right datatype. Otherwise a shallow copy of the scalar value is created at
521
 * the target location of the void pointer. Hence don't use this in a
522
 * multi-threaded application. */
523
UA_EXPORT UA_StatusCode
524
UA_Server_getSessionAttribute_scalar(UA_Server *server,
525
                                     const UA_NodeId *sessionId,
526
                                     const UA_QualifiedName key,
527
                                     const UA_DataType *type,
528
                                     void *outValue);
529
530
UA_EXPORT UA_StatusCode UA_THREADSAFE
531
UA_Server_setSessionAttribute(UA_Server *server, const UA_NodeId *sessionId,
532
                              const UA_QualifiedName key,
533
                              const UA_Variant *value);
534
535
UA_EXPORT UA_StatusCode UA_THREADSAFE
536
UA_Server_deleteSessionAttribute(UA_Server *server, const UA_NodeId *sessionId,
537
                                 const UA_QualifiedName key);
538
539
/**
540
 * Reading and Writing Node Attributes
541
 * -----------------------------------
542
 * The functions for reading and writing node attributes call the regular read
543
 * and write service in the background that are also used over the network.
544
 *
545
 * The following attributes cannot be read, since the local "admin" user always
546
 * has full rights.
547
 *
548
 * - UserWriteMask
549
 * - UserAccessLevel
550
 * - UserExecutable */
551
552
/* Read an attribute of a node. Returns a deep copy. */
553
UA_DataValue UA_EXPORT UA_THREADSAFE
554
UA_Server_read(UA_Server *server, const UA_ReadValueId *item,
555
               UA_TimestampsToReturn timestamps);
556
557
/**
558
 * The following specialized read methods are a shorthand for the regular read
559
 * and set a deep copy of the attribute to the ``out`` pointer (when
560
 * successful). */
561
562
UA_EXPORT UA_THREADSAFE UA_StatusCode
563
UA_Server_readNodeId(UA_Server *server, const UA_NodeId nodeId,
564
                     UA_NodeId *out);
565
566
UA_EXPORT UA_THREADSAFE UA_StatusCode
567
UA_Server_readNodeClass(UA_Server *server, const UA_NodeId nodeId,
568
                        UA_NodeClass *out);
569
570
UA_EXPORT UA_THREADSAFE UA_StatusCode
571
UA_Server_readBrowseName(UA_Server *server, const UA_NodeId nodeId,
572
                         UA_QualifiedName *out);
573
574
UA_EXPORT UA_THREADSAFE UA_StatusCode
575
UA_Server_readDisplayName(UA_Server *server, const UA_NodeId nodeId,
576
                          UA_LocalizedText *out);
577
578
UA_EXPORT UA_THREADSAFE UA_StatusCode
579
UA_Server_readDescription(UA_Server *server, const UA_NodeId nodeId,
580
                          UA_LocalizedText *out);
581
582
UA_EXPORT UA_THREADSAFE UA_StatusCode
583
UA_Server_readWriteMask(UA_Server *server, const UA_NodeId nodeId,
584
                        UA_UInt32 *out);
585
586
UA_EXPORT UA_THREADSAFE UA_StatusCode
587
UA_Server_readIsAbstract(UA_Server *server, const UA_NodeId nodeId,
588
                         UA_Boolean *out);
589
590
UA_EXPORT UA_THREADSAFE UA_StatusCode
591
UA_Server_readSymmetric(UA_Server *server, const UA_NodeId nodeId,
592
                        UA_Boolean *out);
593
594
UA_EXPORT UA_THREADSAFE UA_StatusCode
595
UA_Server_readInverseName(UA_Server *server, const UA_NodeId nodeId,
596
                          UA_LocalizedText *out);
597
598
UA_EXPORT UA_THREADSAFE UA_StatusCode
599
UA_Server_readContainsNoLoops(UA_Server *server, const UA_NodeId nodeId,
600
                              UA_Boolean *out);
601
602
UA_EXPORT UA_THREADSAFE UA_StatusCode
603
UA_Server_readEventNotifier(UA_Server *server, const UA_NodeId nodeId,
604
                            UA_Byte *out);
605
606
UA_EXPORT UA_THREADSAFE UA_StatusCode
607
UA_Server_readValue(UA_Server *server, const UA_NodeId nodeId,
608
                    UA_Variant *out);
609
610
UA_EXPORT UA_THREADSAFE UA_StatusCode
611
UA_Server_readDataType(UA_Server *server, const UA_NodeId nodeId,
612
                       UA_NodeId *out);
613
614
UA_EXPORT UA_THREADSAFE UA_StatusCode
615
UA_Server_readValueRank(UA_Server *server, const UA_NodeId nodeId,
616
                        UA_Int32 *out);
617
618
/* Returns a variant with an uint32 array */
619
UA_EXPORT UA_THREADSAFE UA_StatusCode
620
UA_Server_readArrayDimensions(UA_Server *server, const UA_NodeId nodeId,
621
                              UA_Variant *out);
622
623
UA_EXPORT UA_THREADSAFE UA_StatusCode
624
UA_Server_readAccessLevel(UA_Server *server, const UA_NodeId nodeId,
625
                          UA_Byte *out);
626
627
UA_EXPORT UA_THREADSAFE UA_StatusCode
628
UA_Server_readAccessLevelEx(UA_Server *server, const UA_NodeId nodeId,
629
                            UA_UInt32 *out);
630
631
UA_EXPORT UA_THREADSAFE UA_StatusCode
632
UA_Server_readMinimumSamplingInterval(UA_Server *server, const UA_NodeId nodeId,
633
                                      UA_Double *out);
634
635
UA_EXPORT UA_THREADSAFE UA_StatusCode
636
UA_Server_readHistorizing(UA_Server *server, const UA_NodeId nodeId,
637
                          UA_Boolean *out);
638
639
UA_EXPORT UA_THREADSAFE UA_StatusCode
640
UA_Server_readExecutable(UA_Server *server, const UA_NodeId nodeId,
641
                         UA_Boolean *out);
642
643
/**
644
 * The following node attributes cannot be changed once a node has been created:
645
 *
646
 * - NodeClass
647
 * - NodeId
648
 * - Symmetric
649
 * - ContainsNoLoops
650
 *
651
 * The following attributes cannot be written from the server, as they are
652
 * specific to the different users and set by the access control callback:
653
 *
654
 * - UserWriteMask
655
 * - UserAccessLevel
656
 * - UserExecutable
657
 */
658
659
UA_EXPORT UA_THREADSAFE UA_StatusCode
660
UA_Server_write(UA_Server *server, const UA_WriteValue *value);
661
662
UA_EXPORT UA_THREADSAFE UA_StatusCode
663
UA_Server_writeBrowseName(UA_Server *server, const UA_NodeId nodeId,
664
                          const UA_QualifiedName browseName);
665
666
UA_EXPORT UA_THREADSAFE UA_StatusCode
667
UA_Server_writeDisplayName(UA_Server *server, const UA_NodeId nodeId,
668
                           const UA_LocalizedText displayName);
669
670
UA_EXPORT UA_THREADSAFE UA_StatusCode
671
UA_Server_writeDescription(UA_Server *server, const UA_NodeId nodeId,
672
                           const UA_LocalizedText description);
673
674
UA_EXPORT UA_THREADSAFE UA_StatusCode
675
UA_Server_writeWriteMask(UA_Server *server, const UA_NodeId nodeId,
676
                         const UA_UInt32 writeMask);
677
678
UA_EXPORT UA_THREADSAFE UA_StatusCode
679
UA_Server_writeIsAbstract(UA_Server *server, const UA_NodeId nodeId,
680
                          const UA_Boolean isAbstract);
681
682
UA_EXPORT UA_THREADSAFE UA_StatusCode
683
UA_Server_writeInverseName(UA_Server *server, const UA_NodeId nodeId,
684
                           const UA_LocalizedText inverseName);
685
686
UA_EXPORT UA_THREADSAFE UA_StatusCode
687
UA_Server_writeEventNotifier(UA_Server *server, const UA_NodeId nodeId,
688
                             const UA_Byte eventNotifier);
689
690
/* THe value attribute is a DataValue. Here only a variant is provided. The
691
 * StatusCode is set to UA_STATUSCODE_GOOD, sourceTimestamp and serverTimestamp
692
 * are set to UA_DateTime_now(). See below for setting the full DataValue. */
693
UA_EXPORT UA_THREADSAFE UA_StatusCode
694
UA_Server_writeValue(UA_Server *server, const UA_NodeId nodeId,
695
                     const UA_Variant value);
696
697
UA_EXPORT UA_THREADSAFE UA_StatusCode
698
UA_Server_writeDataValue(UA_Server *server, const UA_NodeId nodeId,
699
                         const UA_DataValue value);
700
701
UA_EXPORT UA_THREADSAFE UA_StatusCode
702
UA_Server_writeDataType(UA_Server *server, const UA_NodeId nodeId,
703
                        const UA_NodeId dataType);
704
705
UA_EXPORT UA_THREADSAFE UA_StatusCode
706
UA_Server_writeValueRank(UA_Server *server, const UA_NodeId nodeId,
707
                         const UA_Int32 valueRank);
708
709
UA_EXPORT UA_THREADSAFE UA_StatusCode
710
UA_Server_writeArrayDimensions(UA_Server *server, const UA_NodeId nodeId,
711
                               const UA_Variant arrayDimensions);
712
713
UA_EXPORT UA_THREADSAFE UA_StatusCode
714
UA_Server_writeAccessLevel(UA_Server *server, const UA_NodeId nodeId,
715
                           const UA_Byte accessLevel);
716
717
UA_EXPORT UA_THREADSAFE UA_StatusCode
718
UA_Server_writeAccessLevelEx(UA_Server *server, const UA_NodeId nodeId,
719
                             const UA_UInt32 accessLevelEx);
720
721
UA_EXPORT UA_THREADSAFE UA_StatusCode
722
UA_Server_writeMinimumSamplingInterval(UA_Server *server, const UA_NodeId nodeId,
723
                                       const UA_Double miniumSamplingInterval);
724
725
UA_EXPORT UA_THREADSAFE UA_StatusCode
726
UA_Server_writeHistorizing(UA_Server *server, const UA_NodeId nodeId,
727
                           const UA_Boolean historizing);
728
729
UA_EXPORT UA_THREADSAFE UA_StatusCode
730
UA_Server_writeExecutable(UA_Server *server, const UA_NodeId nodeId,
731
                          const UA_Boolean executable);
732
733
/**
734
 * Browsing
735
 * -------- */
736
737
/* Browse the references of a particular node. See the definition of
738
 * BrowseDescription structure for details. */
739
UA_BrowseResult UA_EXPORT UA_THREADSAFE
740
UA_Server_browse(UA_Server *server, UA_UInt32 maxReferences,
741
                 const UA_BrowseDescription *bd);
742
743
UA_BrowseResult UA_EXPORT UA_THREADSAFE
744
UA_Server_browseNext(UA_Server *server, UA_Boolean releaseContinuationPoint,
745
                     const UA_ByteString *continuationPoint);
746
747
/* Non-standard version of the Browse service that recurses into child nodes.
748
 *
749
 * Possible loops (that can occur for non-hierarchical references) are handled
750
 * internally. Every node is added at most once to the results array.
751
 *
752
 * Nodes are only added if they match the NodeClassMask in the
753
 * BrowseDescription. However, child nodes are still recursed into if the
754
 * NodeClass does not match. So it is possible, for example, to get all
755
 * VariableNodes below a certain ObjectNode, with additional objects in the
756
 * hierarchy below. */
757
UA_StatusCode UA_EXPORT UA_THREADSAFE
758
UA_Server_browseRecursive(UA_Server *server, const UA_BrowseDescription *bd,
759
                          size_t *resultsSize, UA_ExpandedNodeId **results);
760
761
UA_BrowsePathResult UA_EXPORT UA_THREADSAFE
762
UA_Server_translateBrowsePathToNodeIds(UA_Server *server,
763
                                       const UA_BrowsePath *browsePath);
764
765
/* A simplified TranslateBrowsePathsToNodeIds based on the
766
 * SimpleAttributeOperand type (Part 4, 7.4.4.5).
767
 *
768
 * This specifies a relative path using a list of BrowseNames instead of the
769
 * RelativePath structure. The list of BrowseNames is equivalent to a
770
 * RelativePath that specifies forward references which are subtypes of the
771
 * HierarchicalReferences ReferenceType. All Nodes followed by the browsePath
772
 * shall be of the NodeClass Object or Variable. */
773
UA_BrowsePathResult UA_EXPORT UA_THREADSAFE
774
UA_Server_browseSimplifiedBrowsePath(UA_Server *server, const UA_NodeId origin,
775
                                     size_t browsePathSize,
776
                                     const UA_QualifiedName *browsePath);
777
778
#ifndef HAVE_NODEITER_CALLBACK
779
#define HAVE_NODEITER_CALLBACK
780
/* Iterate over all nodes referenced by parentNodeId by calling the callback
781
 * function for each child node (in ifdef because GCC/CLANG handle include order
782
 * differently) */
783
typedef UA_StatusCode
784
(*UA_NodeIteratorCallback)(UA_NodeId childId, UA_Boolean isInverse,
785
                           UA_NodeId referenceTypeId, void *handle);
786
#endif
787
788
UA_StatusCode UA_EXPORT UA_THREADSAFE
789
UA_Server_forEachChildNodeCall(UA_Server *server, UA_NodeId parentNodeId,
790
                               UA_NodeIteratorCallback callback, void *handle);
791
792
#ifdef UA_ENABLE_DISCOVERY
793
794
/**
795
 * Discovery
796
 * ---------
797
 *
798
 * Registering at a Discovery Server
799
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
800
801
/* Register the given server instance at the discovery server. This should be
802
 * called periodically, for example every 10 minutes, depending on the
803
 * configuration of the discovery server. You should also call
804
 * _unregisterDiscovery when the server shuts down.
805
 *
806
 * The supplied client configuration is used to create a new client to connect
807
 * to the discovery server. The client configuration is moved over to the server
808
 * and eventually cleaned up internally. The structure pointed at by `cc` is
809
 * zeroed to avoid accessing outdated information.
810
 *
811
 * The eventloop and logging plugins in the client configuration are replaced by
812
 * those configured in the server. */
813
UA_StatusCode UA_EXPORT UA_THREADSAFE
814
UA_Server_registerDiscovery(UA_Server *server, UA_ClientConfig *cc,
815
                            const UA_String discoveryServerUrl,
816
                            const UA_String semaphoreFilePath);
817
818
/* Deregister the given server instance from the discovery server.
819
 * This should be called when the server is shutting down. */
820
UA_StatusCode UA_EXPORT UA_THREADSAFE
821
UA_Server_deregisterDiscovery(UA_Server *server, UA_ClientConfig *cc,
822
                              const UA_String discoveryServerUrl);
823
824
/**
825
 * Operating a Discovery Server
826
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
827
828
/* Callback for RegisterServer. Data is passed from the register call */
829
typedef void
830
(*UA_Server_registerServerCallback)(const UA_RegisteredServer *registeredServer,
831
                                    void* data);
832
833
/* Set the callback which is called if another server registeres or unregisters
834
 * with this instance. This callback is called every time the server gets a
835
 * register call. This especially means that for every periodic server register
836
 * the callback will be called.
837
 *
838
 * @param server
839
 * @param cb the callback
840
 * @param data data passed to the callback
841
 * @return ``UA_STATUSCODE_SUCCESS`` on success */
842
void UA_EXPORT UA_THREADSAFE
843
UA_Server_setRegisterServerCallback(UA_Server *server,
844
                                    UA_Server_registerServerCallback cb, void* data);
845
846
#ifdef UA_ENABLE_DISCOVERY_MULTICAST
847
848
/* Callback for server detected through mDNS. Data is passed from the register
849
 * call
850
 *
851
 * @param isServerAnnounce indicates if the server has just been detected. If
852
 *        set to false, this means the server is shutting down.
853
 * @param isTxtReceived indicates if we already received the corresponding TXT
854
 *        record with the path and caps data */
855
typedef void
856
(*UA_Server_serverOnNetworkCallback)(const UA_ServerOnNetwork *serverOnNetwork,
857
                                     UA_Boolean isServerAnnounce,
858
                                     UA_Boolean isTxtReceived, void* data);
859
860
/* Set the callback which is called if another server is found through mDNS or
861
 * deleted. It will be called for any mDNS message from the remote server, thus
862
 * it may be called multiple times for the same instance. Also the SRV and TXT
863
 * records may arrive later, therefore for the first call the server
864
 * capabilities may not be set yet. If called multiple times, previous data will
865
 * be overwritten.
866
 *
867
 * @param server
868
 * @param cb the callback
869
 * @param data data passed to the callback
870
 * @return ``UA_STATUSCODE_SUCCESS`` on success */
871
void UA_EXPORT UA_THREADSAFE
872
UA_Server_setServerOnNetworkCallback(UA_Server *server,
873
                                     UA_Server_serverOnNetworkCallback cb,
874
                                     void* data);
875
876
#endif /* UA_ENABLE_DISCOVERY_MULTICAST */
877
878
#endif /* UA_ENABLE_DISCOVERY */
879
880
/**
881
 * Information Model Callbacks
882
 * ---------------------------
883
 * There are three places where a callback from an information model to
884
 * user-defined code can happen.
885
 *
886
 * - Custom node constructors and destructors
887
 * - Linking VariableNodes with a data source
888
 * - MethodNode callbacks */
889
890
void UA_EXPORT
891
UA_Server_setAdminSessionContext(UA_Server *server,
892
                                 void *context);
893
894
UA_StatusCode UA_EXPORT UA_THREADSAFE
895
UA_Server_setNodeTypeLifecycle(UA_Server *server, UA_NodeId nodeId,
896
                               UA_NodeTypeLifecycle lifecycle);
897
898
UA_StatusCode UA_EXPORT UA_THREADSAFE
899
UA_Server_getNodeContext(UA_Server *server, UA_NodeId nodeId,
900
                         void **nodeContext);
901
902
/* Careful! The user has to ensure that the destructor callbacks still work. */
903
UA_StatusCode UA_EXPORT UA_THREADSAFE
904
UA_Server_setNodeContext(UA_Server *server, UA_NodeId nodeId,
905
                         void *nodeContext);
906
907
/**
908
 * .. _datasource:
909
 *
910
 * Value Source
911
 * ~~~~~~~~~~~~
912
 *
913
 * There are two options for storing the value of a VariableNode: Internal in
914
 * the VariableNode itself or with callbacks to the application. See
915
 * the section on :ref:`variable-node` for details. */
916
917
/* Set the internal value source. Both the value argument and the notifications
918
 * argument can be NULL. If value is NULL, the Read service is used to get the
919
 * latest value before switching from a callback to an internal value source.
920
 * If notifications is NULL, then all onRead/onWrite notifications are
921
 * disabled. */
922
UA_StatusCode UA_EXPORT UA_THREADSAFE
923
UA_Server_setVariableNode_internalValueSource(UA_Server *server,
924
    const UA_NodeId nodeId, const UA_DataValue *value,
925
    const UA_ValueSourceNotifications *notifications);
926
927
/* For the external value, no initial copy is made. The node "just" points to
928
 * the provided double-pointer. Otherwise identical to the internal data
929
 * source. */
930
UA_StatusCode UA_EXPORT UA_THREADSAFE
931
UA_Server_setVariableNode_externalValueSource(UA_Server *server,
932
    const UA_NodeId nodeId, UA_DataValue **value,
933
    const UA_ValueSourceNotifications *notifications);
934
935
/* It is expected that the read callback is implemented. Whenever the value
936
 * attribute is read, the function will be called and asked to fill a
937
 * UA_DataValue structure that contains the value content and additional
938
 * metadata like timestamps.
939
 *
940
 * The write callback can be set to a null-pointer. Then writing into the value
941
 * is disabled. */
942
UA_StatusCode UA_EXPORT UA_THREADSAFE
943
UA_Server_setVariableNode_callbackValueSource(UA_Server *server,
944
    const UA_NodeId nodeId, const UA_CallbackValueSource evs);
945
946
/* Deprecated API */
947
typedef UA_CallbackValueSource UA_DataSource;
948
#define UA_Server_setVariableNode_dataSource(server, nodeId, dataSource) \
949
    UA_Server_setVariableNode_callbackValueSource(server, nodeId, dataSource);
950
951
/* Deprecated API */
952
typedef UA_ValueSourceNotifications UA_ValueCallback;
953
#define UA_Server_setVariableNode_valueCallback(server, nodeId, callback) \
954
    UA_Server_setVariableNode_internalValueSource(server, nodeId, NULL, &callback);
955
956
/**
957
 * .. _local-monitoreditems:
958
 *
959
 * Local MonitoredItems
960
 * ~~~~~~~~~~~~~~~~~~~~
961
 * MonitoredItems are used with the Subscription mechanism of OPC UA to
962
 * transported notifications for data changes and events. MonitoredItems can
963
 * also be registered locally. Notifications are then forwarded to a
964
 * user-defined callback instead of a remote client.
965
 *
966
 * Local MonitoredItems are delivered asynchronously. That is, the notification
967
 * is inserted as a *Delayed Callback* for the EventLoop. The callback is then
968
 * triggered when the control flow next returns to the EventLoop. */
969
970
#ifdef UA_ENABLE_SUBSCRIPTIONS
971
972
/* Delete a local MonitoredItem. Used for both DataChange- and
973
 * Event-MonitoredItems. */
974
UA_StatusCode UA_EXPORT UA_THREADSAFE
975
UA_Server_deleteMonitoredItem(UA_Server *server, UA_UInt32 monitoredItemId);
976
977
typedef void (*UA_Server_DataChangeNotificationCallback)
978
    (UA_Server *server, UA_UInt32 monitoredItemId, void *monitoredItemContext,
979
     const UA_NodeId *nodeId, void *nodeContext, UA_UInt32 attributeId,
980
     const UA_DataValue *value);
981
982
/**
983
 * DataChange MonitoredItem use a sampling interval and filter criteria to
984
 * notify the userland about value changes. Note that the sampling interval can
985
 * also be zero to be notified about changes "right away". For this we hook the
986
 * MonitoredItem into the observed Node and check the filter after every call of
987
 * the Write-Service. */
988
989
/* Create a local MonitoredItem to detect data changes.
990
 *
991
 * @param server The server executing the MonitoredItem
992
 * @param timestampsToReturn Shall timestamps be added to the value for the
993
 *        callback?
994
 * @param item The parameters of the new MonitoredItem. Note that the attribute
995
 *        of the ReadValueId (the node that is monitored) can not be
996
 *        ``UA_ATTRIBUTEID_EVENTNOTIFIER``. See below for event notifications.
997
 * @param monitoredItemContext A pointer that is forwarded with the callback
998
 * @param callback The callback that is executed on detected data changes
999
 * @return Returns a description of the created MonitoredItem. The structure
1000
 *         also contains a StatusCode (in case of an error) and the identifier
1001
 *         of the new MonitoredItem. */
1002
UA_MonitoredItemCreateResult UA_EXPORT UA_THREADSAFE
1003
UA_Server_createDataChangeMonitoredItem(UA_Server *server,
1004
          UA_TimestampsToReturn timestampsToReturn,
1005
          const UA_MonitoredItemCreateRequest item,
1006
          void *monitoredItemContext,
1007
          UA_Server_DataChangeNotificationCallback callback);
1008
1009
/**
1010
 * See the section on :ref`events` for how to emit events in the server.
1011
 *
1012
 * Event-MonitoredItems emit notifications with a list of "fields" (variants).
1013
 * The fields are specified as *SimpleAttributeOperands* in the select-clause of
1014
 * the MonitoredItem's event filter. For the local event callback, instead of
1015
 * using a list of variants, we use a key-value map for the event fields. They
1016
 * key names are generated with ``UA_SimpleAttributeOperand_print`` to get a
1017
 * human-readable representation.
1018
 *
1019
 * The received event-fields map could look like this::
1020
 *
1021
 *   0:/Severity   => UInt16(1000)
1022
 *   0:/Message    => LocalizedText("en-US", "My Event Message")
1023
 *   0:/EventType  => NodeId(i=50831)
1024
 *   0:/SourceNode => NodeId(i=2253)
1025
 *
1026
 * The order of the keys is identical to the order of SimpleAttributeOperands in
1027
 * the select-clause. This feature requires the build flag ``UA_ENABLE_PARSING``
1028
 * enabled. Otherwise the key-value map uses empty keys (the order of fields is
1029
 * still the same as the specified select-clauses). */
1030
1031
#ifdef UA_ENABLE_SUBSCRIPTIONS_EVENTS
1032
1033
typedef void (*UA_Server_EventNotificationCallback)
1034
    (UA_Server *server, UA_UInt32 monitoredItemId, void *monitoredItemContext,
1035
     const UA_KeyValueMap eventFields);
1036
1037
/* Create a local MonitoredItem for Events. The API is simplifed compared to a
1038
 * UA_MonitoredItemCreateRequest. The unavailable options are not relevant for
1039
 * local MonitoredItems (e.g. the queue size) or not relevant for Event
1040
 * MonitoredItems (e.g. the sampling interval).
1041
 *
1042
 * @param server The server executing the MonitoredItem
1043
 * @param nodeId The node where events are collected. Note that events "bubble
1044
 *        up" to their parents (via hierarchical references).
1045
 * @param filter The filter defined which event fields are selected (select
1046
 *        clauses) and which events are considered for this particular
1047
 *        MonitoredItem (where clause).
1048
 * @param monitoredItemContext A pointer that is forwarded with the callback
1049
 * @param callback The callback that is executed for each event
1050
 * @return Returns a description of the created MonitoredItem. The structure
1051
 *         also contains a StatusCode (in case of an error) and the identifier
1052
 *         of the new MonitoredItem. */
1053
UA_MonitoredItemCreateResult UA_EXPORT UA_THREADSAFE
1054
UA_Server_createEventMonitoredItem(UA_Server *server, const UA_NodeId nodeId,
1055
                                   const UA_EventFilter filter,
1056
                                   void *monitoredItemContext,
1057
                                   UA_Server_EventNotificationCallback callback);
1058
1059
/* Extended version UA_Server_createEventMonitoredItem that allows setting of
1060
 * uncommon parameters (for local MonitoredItems) like the MonitoringMode and
1061
 * queue sizes.
1062
 *
1063
 * @param server The server executing the MonitoredItem
1064
 * @param item The description of the MonitoredItem. Must use
1065
 *        UA_ATTRIBUTEID_EVENTNOTIFIER and an EventFilter.
1066
 * @param monitoredItemContext A pointer that is forwarded with the callback
1067
 * @param callback The callback that is executed for each event
1068
 * @return Returns a description of the created MonitoredItem. The structure
1069
 *         also contains a StatusCode (in case of an error) and the identifier
1070
 *         of the new MonitoredItem. */
1071
UA_MonitoredItemCreateResult UA_EXPORT UA_THREADSAFE
1072
UA_Server_createEventMonitoredItemEx(UA_Server *server,
1073
                                     const UA_MonitoredItemCreateRequest item,
1074
                                     void *monitoredItemContext,
1075
                                     UA_Server_EventNotificationCallback callback);
1076
1077
#endif
1078
1079
#endif
1080
1081
/**
1082
 * Method Callbacks
1083
 * ~~~~~~~~~~~~~~~~
1084
 * Method callbacks are set to `NULL` (not executable) when a method node is
1085
 * added over the network. In theory, it is possible to add a callback via
1086
 * ``UA_Server_setMethodNode_callback`` within the global constructor when
1087
 * adding methods over the network is really wanted. See the Section
1088
 * :ref:`object-interaction` for calling methods on an object. */
1089
1090
#ifdef UA_ENABLE_METHODCALLS
1091
UA_StatusCode UA_EXPORT UA_THREADSAFE
1092
UA_Server_setMethodNodeCallback(UA_Server *server,
1093
                                const UA_NodeId methodNodeId,
1094
                                UA_MethodCallback methodCallback);
1095
1096
/* Backwards compatibility definition */
1097
#define UA_Server_setMethodNode_callback(server, methodNodeId, methodCallback) \
1098
    UA_Server_setMethodNodeCallback(server, methodNodeId, methodCallback)
1099
1100
UA_StatusCode UA_EXPORT UA_THREADSAFE
1101
UA_Server_getMethodNodeCallback(UA_Server *server,
1102
                                const UA_NodeId methodNodeId,
1103
                                UA_MethodCallback *outMethodCallback);
1104
1105
UA_CallMethodResult UA_EXPORT UA_THREADSAFE
1106
UA_Server_call(UA_Server *server, const UA_CallMethodRequest *request);
1107
#endif
1108
1109
/**
1110
 * .. _addnodes:
1111
 *
1112
 * Node Management
1113
 * ---------------
1114
 * When creating dynamic node instances at runtime, chances are that you will
1115
 * not care about the specific NodeId of the new node, as long as you can
1116
 * reference it later. When passing numeric NodeIds with a numeric identifier 0,
1117
 * the stack evaluates this as "select a random unassigned numeric NodeId in
1118
 * that namespace". To find out which NodeId was actually assigned to the new
1119
 * node, you may pass a pointer `outNewNodeId`, which will (after a successful
1120
 * node insertion) contain the nodeId of the new node. You may also pass a
1121
 * ``NULL`` pointer if this result is not needed.
1122
 *
1123
 * See the Section :ref:`node-lifecycle` on constructors and on attaching
1124
 * user-defined data to nodes.
1125
 *
1126
 * The Section :ref:`default-node-attributes` contains useful starting points
1127
 * for defining node attributes. Forgetting to set the ValueRank or the
1128
 * AccessLevel leads to errors that can be hard to track down for new users. The
1129
 * default attributes have a high likelihood to "do the right thing".
1130
 *
1131
 * The methods for node addition and deletion take mostly const arguments that
1132
 * are not modified. When creating a node, a deep copy of the node identifier,
1133
 * node attributes, etc. is created. Therefore, it is possible to call for
1134
 * example ``UA_Server_addVariablenode`` with a value attribute (a
1135
 * :ref:`variant`) pointing to a memory location on the stack. If you need
1136
 * changes to a variable value to manifest at a specific memory location, please
1137
 * use a :ref:`datasource`. */
1138
1139
UA_EXPORT UA_THREADSAFE UA_StatusCode
1140
UA_Server_addVariableNode(UA_Server *server, const UA_NodeId requestedNewNodeId,
1141
                          const UA_NodeId parentNodeId,
1142
                          const UA_NodeId referenceTypeId,
1143
                          const UA_QualifiedName browseName,
1144
                          const UA_NodeId typeDefinition,
1145
                          const UA_VariableAttributes attr,
1146
                          void *nodeContext, UA_NodeId *outNewNodeId);
1147
1148
UA_EXPORT UA_THREADSAFE UA_StatusCode
1149
UA_Server_addVariableTypeNode(UA_Server *server,
1150
                              const UA_NodeId requestedNewNodeId,
1151
                              const UA_NodeId parentNodeId,
1152
                              const UA_NodeId referenceTypeId,
1153
                              const UA_QualifiedName browseName,
1154
                              const UA_NodeId typeDefinition,
1155
                              const UA_VariableTypeAttributes attr,
1156
                              void *nodeContext, UA_NodeId *outNewNodeId);
1157
1158
UA_EXPORT UA_THREADSAFE UA_StatusCode
1159
UA_Server_addObjectNode(UA_Server *server, const UA_NodeId requestedNewNodeId,
1160
                        const UA_NodeId parentNodeId,
1161
                        const UA_NodeId referenceTypeId,
1162
                        const UA_QualifiedName browseName,
1163
                        const UA_NodeId typeDefinition,
1164
                        const UA_ObjectAttributes attr,
1165
                        void *nodeContext, UA_NodeId *outNewNodeId);
1166
1167
UA_EXPORT UA_THREADSAFE UA_StatusCode
1168
UA_Server_addObjectTypeNode(UA_Server *server, const UA_NodeId requestedNewNodeId,
1169
                            const UA_NodeId parentNodeId,
1170
                            const UA_NodeId referenceTypeId,
1171
                            const UA_QualifiedName browseName,
1172
                            const UA_ObjectTypeAttributes attr,
1173
                            void *nodeContext, UA_NodeId *outNewNodeId);
1174
1175
UA_EXPORT UA_THREADSAFE UA_StatusCode
1176
UA_Server_addViewNode(UA_Server *server, const UA_NodeId requestedNewNodeId,
1177
                      const UA_NodeId parentNodeId,
1178
                      const UA_NodeId referenceTypeId,
1179
                      const UA_QualifiedName browseName,
1180
                      const UA_ViewAttributes attr,
1181
                      void *nodeContext, UA_NodeId *outNewNodeId);
1182
1183
UA_EXPORT UA_THREADSAFE UA_StatusCode
1184
UA_Server_addReferenceTypeNode(UA_Server *server,
1185
                               const UA_NodeId requestedNewNodeId,
1186
                               const UA_NodeId parentNodeId,
1187
                               const UA_NodeId referenceTypeId,
1188
                               const UA_QualifiedName browseName,
1189
                               const UA_ReferenceTypeAttributes attr,
1190
                               void *nodeContext, UA_NodeId *outNewNodeId);
1191
1192
UA_EXPORT UA_THREADSAFE UA_StatusCode
1193
UA_Server_addDataTypeNode(UA_Server *server,
1194
                          const UA_NodeId requestedNewNodeId,
1195
                          const UA_NodeId parentNodeId,
1196
                          const UA_NodeId referenceTypeId,
1197
                          const UA_QualifiedName browseName,
1198
                          const UA_DataTypeAttributes attr,
1199
                          void *nodeContext, UA_NodeId *outNewNodeId);
1200
1201
/* Add a VariableNode with a callback value-source */
1202
UA_StatusCode UA_EXPORT UA_THREADSAFE
1203
UA_Server_addCallbackValueSourceVariableNode(UA_Server *server,
1204
                                             const UA_NodeId requestedNewNodeId,
1205
                                             const UA_NodeId parentNodeId,
1206
                                             const UA_NodeId referenceTypeId,
1207
                                             const UA_QualifiedName browseName,
1208
                                             const UA_NodeId typeDefinition,
1209
                                             const UA_VariableAttributes attr,
1210
                                             const UA_CallbackValueSource evs,
1211
                                             void *nodeContext, UA_NodeId *outNewNodeId);
1212
1213
/* Legacy API */
1214
#define UA_Server_addDataSourceVariableNode(server, requestedNewNodeId, parentNodeId,    \
1215
                                            referenceTypeId, browseName, typeDefinition, \
1216
                                            attr, dataSource, nodeContext, outNewNodeId) \
1217
    UA_Server_addCallbackValueSourceVariableNode(server, requestedNewNodeId,             \
1218
                                                 parentNodeId, referenceTypeId,          \
1219
                                                 browseName, typeDefinition,             \
1220
                                                 attr, dataSource, nodeContext,          \
1221
                                                 outNewNodeId)
1222
1223
/* VariableNodes that are "dynamic" (default for user-created variables) receive
1224
 * and store a SourceTimestamp. For non-dynamic VariableNodes the current time
1225
 * is used for the SourceTimestamp. */
1226
UA_StatusCode UA_EXPORT UA_THREADSAFE
1227
UA_Server_setVariableNodeDynamic(UA_Server *server, const UA_NodeId nodeId,
1228
                                 UA_Boolean isDynamic);
1229
1230
#ifdef UA_ENABLE_METHODCALLS
1231
1232
UA_EXPORT UA_THREADSAFE UA_StatusCode
1233
UA_Server_addMethodNode(UA_Server *server, const UA_NodeId requestedNewNodeId,
1234
                        const UA_NodeId parentNodeId, const UA_NodeId referenceTypeId,
1235
                        const UA_QualifiedName browseName, const UA_MethodAttributes attr,
1236
                        UA_MethodCallback method,
1237
                        size_t inputArgumentsSize, const UA_Argument *inputArguments,
1238
                        size_t outputArgumentsSize, const UA_Argument *outputArguments,
1239
                        void *nodeContext, UA_NodeId *outNewNodeId);
1240
1241
/* Extended version, allows the additional definition of fixed NodeIds for the
1242
 * InputArgument/OutputArgument child variables */
1243
UA_StatusCode UA_EXPORT UA_THREADSAFE
1244
UA_Server_addMethodNodeEx(UA_Server *server, const UA_NodeId requestedNewNodeId,
1245
                          const UA_NodeId parentNodeId,
1246
                          const UA_NodeId referenceTypeId,
1247
                          const UA_QualifiedName browseName,
1248
                          const UA_MethodAttributes attr, UA_MethodCallback method,
1249
                          size_t inputArgumentsSize, const UA_Argument *inputArguments,
1250
                          const UA_NodeId inputArgumentsRequestedNewNodeId,
1251
                          UA_NodeId *inputArgumentsOutNewNodeId,
1252
                          size_t outputArgumentsSize, const UA_Argument *outputArguments,
1253
                          const UA_NodeId outputArgumentsRequestedNewNodeId,
1254
                          UA_NodeId *outputArgumentsOutNewNodeId,
1255
                          void *nodeContext, UA_NodeId *outNewNodeId);
1256
1257
#endif
1258
1259
/**
1260
 * The method pair UA_Server_addNode_begin and _finish splits the AddNodes
1261
 * service in two parts. This is useful if the node shall be modified before
1262
 * finish the instantiation. For example to add children with specific NodeIds.
1263
 * Otherwise, mandatory children (e.g. of an ObjectType) are added with
1264
 * pseudo-random unique NodeIds. Existing children are detected during the
1265
 * _finish part via their matching BrowseName.
1266
 *
1267
 * The _begin method:
1268
 *  - prepares the node and adds it to the nodestore
1269
 *  - copies some unassigned attributes from the TypeDefinition node internally
1270
 *  - adds the references to the parent (and the TypeDefinition if applicable)
1271
 *  - performs type-checking of variables.
1272
 *
1273
 * You can add an object node without a parent if you set the parentNodeId and
1274
 * referenceTypeId to UA_NODE_ID_NULL. Then you need to add the parent reference
1275
 * and hasTypeDef reference yourself before calling the _finish method.
1276
 * Not that this is only allowed for object nodes.
1277
 *
1278
 * The _finish method:
1279
 *  - copies mandatory children
1280
 *  - calls the node constructor(s) at the end
1281
 *  - may remove the node if it encounters an error.
1282
 *
1283
 * The special UA_Server_addMethodNode_finish method needs to be used for method
1284
 * nodes, since there you need to explicitly specifiy the input and output
1285
 * arguments which are added in the finish step (if not yet already there) */
1286
1287
/* The ``attr`` argument must have a type according to the NodeClass.
1288
 * ``VariableAttributes`` for variables, ``ObjectAttributes`` for objects, and
1289
 * so on. Missing attributes are taken from the TypeDefinition node if
1290
 * applicable. */
1291
UA_StatusCode UA_EXPORT UA_THREADSAFE
1292
UA_Server_addNode_begin(UA_Server *server, const UA_NodeClass nodeClass,
1293
                        const UA_NodeId requestedNewNodeId,
1294
                        const UA_NodeId parentNodeId,
1295
                        const UA_NodeId referenceTypeId,
1296
                        const UA_QualifiedName browseName,
1297
                        const UA_NodeId typeDefinition,
1298
                        const void *attr, const UA_DataType *attributeType,
1299
                        void *nodeContext, UA_NodeId *outNewNodeId);
1300
1301
UA_StatusCode UA_EXPORT UA_THREADSAFE
1302
UA_Server_addNode_finish(UA_Server *server, const UA_NodeId nodeId);
1303
1304
#ifdef UA_ENABLE_METHODCALLS
1305
1306
UA_StatusCode UA_EXPORT UA_THREADSAFE
1307
UA_Server_addMethodNode_finish(UA_Server *server, const UA_NodeId nodeId,
1308
                         UA_MethodCallback method,
1309
                         size_t inputArgumentsSize, const UA_Argument *inputArguments,
1310
                         size_t outputArgumentsSize, const UA_Argument *outputArguments);
1311
1312
#endif
1313
1314
/* Deletes a node and optionally all references leading to the node. */
1315
UA_StatusCode UA_EXPORT UA_THREADSAFE
1316
UA_Server_deleteNode(UA_Server *server, const UA_NodeId nodeId,
1317
                     UA_Boolean deleteReferences);
1318
1319
UA_StatusCode UA_EXPORT UA_THREADSAFE
1320
UA_Server_addReference(UA_Server *server, const UA_NodeId sourceId,
1321
                       const UA_NodeId refTypeId,
1322
                       const UA_ExpandedNodeId targetId, UA_Boolean isForward);
1323
1324
UA_StatusCode UA_EXPORT UA_THREADSAFE
1325
UA_Server_deleteReference(UA_Server *server, const UA_NodeId sourceNodeId,
1326
                          const UA_NodeId referenceTypeId, UA_Boolean isForward,
1327
                          const UA_ExpandedNodeId targetNodeId,
1328
                          UA_Boolean deleteBidirectional);
1329
1330
/**
1331
 * .. _events:
1332
 *
1333
 * Events
1334
 * ------
1335
 * The method ``UA_Server_createEvent`` creates an event and represents it as
1336
 * node. The node receives a unique `EventId` which is automatically added to
1337
 * the node. The method returns a `NodeId` to the object node which represents
1338
 * the event through ``outNodeId``. The `NodeId` can be used to set the
1339
 * attributes of the event. The generated `NodeId` is always numeric.
1340
 * ``outNodeId`` cannot be ``NULL``.
1341
 *
1342
 * Note: In order to see an event in UAExpert, the field `Time` must be given a
1343
 * value!
1344
 *
1345
 * The method ``UA_Server_triggerEvent`` "triggers" an event by adding it to all
1346
 * monitored items of the specified origin node and those of all its parents.
1347
 * Any filters specified by the monitored items are automatically applied. Using
1348
 * this method deletes the node generated by ``UA_Server_createEvent``. The
1349
 * `EventId` for the new event is generated automatically and is returned
1350
 * through ``outEventId``. ``NULL`` can be passed if the `EventId` is not
1351
 * needed. ``deleteEventNode`` specifies whether the node representation of the
1352
 * event should be deleted after invoking the method. This can be useful if
1353
 * events with the similar attributes are triggered frequently. ``UA_TRUE``
1354
 * would cause the node to be deleted. */
1355
1356
#ifdef UA_ENABLE_SUBSCRIPTIONS_EVENTS
1357
1358
/* Creates a node representation of an event
1359
 *
1360
 * @param server The server object
1361
 * @param eventType The type of the event for which a node should be created
1362
 * @param outNodeId The NodeId of the newly created node for the event
1363
 * @return The StatusCode of the UA_Server_createEvent method */
1364
UA_StatusCode UA_EXPORT UA_THREADSAFE
1365
UA_Server_createEvent(UA_Server *server, const UA_NodeId eventType,
1366
                      UA_NodeId *outNodeId);
1367
1368
/* Triggers a node representation of an event by applying EventFilters and
1369
 * adding the event to the appropriate queues.
1370
 *
1371
 * @param server The server object
1372
 * @param eventNodeId The NodeId of the node representation of the event which
1373
 *        should be triggered
1374
 * @param outEvent the EventId of the new event
1375
 * @param deleteEventNode Specifies whether the node representation of the event
1376
 *        should be deleted
1377
 * @return The StatusCode of the UA_Server_triggerEvent method */
1378
UA_StatusCode UA_EXPORT UA_THREADSAFE
1379
UA_Server_triggerEvent(UA_Server *server, const UA_NodeId eventNodeId,
1380
                       const UA_NodeId originId, UA_ByteString *outEventId,
1381
                       const UA_Boolean deleteEventNode);
1382
1383
#endif /* UA_ENABLE_SUBSCRIPTIONS_EVENTS */
1384
1385
/**
1386
 * Alarms & Conditions (Experimental)
1387
 * ---------------------------------- */
1388
1389
#ifdef UA_ENABLE_SUBSCRIPTIONS_ALARMS_CONDITIONS
1390
typedef enum UA_TwoStateVariableCallbackType {
1391
  UA_ENTERING_ENABLEDSTATE,
1392
  UA_ENTERING_ACKEDSTATE,
1393
  UA_ENTERING_CONFIRMEDSTATE,
1394
  UA_ENTERING_ACTIVESTATE
1395
} UA_TwoStateVariableCallbackType;
1396
1397
/* Callback prototype to set user specific callbacks */
1398
typedef UA_StatusCode
1399
(*UA_TwoStateVariableChangeCallback)(UA_Server *server, const UA_NodeId *condition);
1400
1401
/* Create condition instance. The function checks first whether the passed
1402
 * conditionType is a subType of ConditionType. Then checks whether the
1403
 * condition source has HasEventSource reference to its parent. If not, a
1404
 * HasEventSource reference will be created between condition source and server
1405
 * object. To expose the condition in address space, a hierarchical
1406
 * ReferenceType should be passed to create the reference to condition source.
1407
 * Otherwise, UA_NODEID_NULL should be passed to make the condition not exposed.
1408
 *
1409
 * @param server The server object
1410
 * @param conditionId The NodeId of the requested Condition Object. When passing
1411
 *        UA_NODEID_NUMERIC(X,0) an unused nodeid in namespace X will be used.
1412
 *        E.g. passing UA_NODEID_NULL will result in a NodeId in namespace 0.
1413
 * @param conditionType The NodeId of the node representation of the ConditionType
1414
 * @param conditionName The name of the condition to be created
1415
 * @param conditionSource The NodeId of the Condition Source (Parent of the Condition)
1416
 * @param hierarchialReferenceType The NodeId of Hierarchical ReferenceType
1417
 *                                 between Condition and its source
1418
 * @param outConditionId The NodeId of the created Condition
1419
 * @return The StatusCode of the UA_Server_createCondition method */
1420
UA_StatusCode UA_EXPORT
1421
UA_Server_createCondition(UA_Server *server,
1422
                          const UA_NodeId conditionId,
1423
                          const UA_NodeId conditionType,
1424
                          const UA_QualifiedName conditionName,
1425
                          const UA_NodeId conditionSource,
1426
                          const UA_NodeId hierarchialReferenceType,
1427
                          UA_NodeId *outConditionId);
1428
1429
/* The method pair UA_Server_addCondition_begin and _finish splits the
1430
 * UA_Server_createCondtion in two parts similiar to the
1431
 * UA_Server_addNode_begin / _finish pair. This is useful if the node shall be
1432
 * modified before finish the instantiation. For example to add children with
1433
 * specific NodeIds.
1434
 * For details refer to the UA_Server_addNode_begin / _finish methods.
1435
 *
1436
 * Additionally to UA_Server_addNode_begin UA_Server_addCondition_begin checks
1437
 * if the passed condition type is a subtype of the OPC UA ConditionType.
1438
 *
1439
 * @param server The server object
1440
 * @param conditionId The NodeId of the requested Condition Object. When passing
1441
 *        UA_NODEID_NUMERIC(X,0) an unused nodeid in namespace X will be used.
1442
 *        E.g. passing UA_NODEID_NULL will result in a NodeId in namespace 0.
1443
 * @param conditionType The NodeId of the node representation of the ConditionType
1444
 * @param conditionName The name of the condition to be added
1445
 * @param outConditionId The NodeId of the added Condition
1446
 * @return The StatusCode of the UA_Server_addCondition_begin method */
1447
UA_StatusCode UA_EXPORT
1448
UA_Server_addCondition_begin(UA_Server *server,
1449
                             const UA_NodeId conditionId,
1450
                             const UA_NodeId conditionType,
1451
                             const UA_QualifiedName conditionName,
1452
                             UA_NodeId *outConditionId);
1453
1454
/* Second call of the UA_Server_addCondition_begin and _finish pair.
1455
 * Additionally to UA_Server_addNode_finish UA_Server_addCondition_finish:
1456
 *  - checks whether the condition source has HasEventSource reference to its
1457
 *    parent. If not, a HasEventSource reference will be created between
1458
 *    condition source and server object
1459
 *  - exposes the condition in the address space if hierarchialReferenceType is
1460
 *    not UA_NODEID_NULL by adding a reference of this type from the condition
1461
 *    source to the condition instance
1462
 *  - initializes the standard condition fields and callbacks
1463
 *
1464
 * @param server The server object
1465
 * @param conditionId The NodeId of the unfinished Condition Object
1466
 * @param conditionSource The NodeId of the Condition Source (Parent of the Condition)
1467
 * @param hierarchialReferenceType The NodeId of Hierarchical ReferenceType
1468
 *                                 between Condition and its source
1469
 * @return The StatusCode of the UA_Server_addCondition_finish method */
1470
1471
UA_StatusCode UA_EXPORT
1472
UA_Server_addCondition_finish(UA_Server *server,
1473
                              const UA_NodeId conditionId,
1474
                              const UA_NodeId conditionSource,
1475
                              const UA_NodeId hierarchialReferenceType);
1476
1477
/* Set the value of condition field.
1478
 *
1479
 * @param server The server object
1480
 * @param condition The NodeId of the node representation of the Condition Instance
1481
 * @param value Variant Value to be written to the Field
1482
 * @param fieldName Name of the Field in which the value should be written
1483
 * @return The StatusCode of the UA_Server_setConditionField method*/
1484
UA_StatusCode UA_EXPORT UA_THREADSAFE
1485
UA_Server_setConditionField(UA_Server *server,
1486
                            const UA_NodeId condition,
1487
                            const UA_Variant *value,
1488
                            const UA_QualifiedName fieldName);
1489
1490
/* Set the value of property of condition field.
1491
 *
1492
 * @param server The server object
1493
 * @param condition The NodeId of the node representation of the Condition
1494
 *        Instance
1495
 * @param value Variant Value to be written to the Field
1496
 * @param variableFieldName Name of the Field which has a property
1497
 * @param variablePropertyName Name of the Field Property in which the value
1498
 *        should be written
1499
 * @return The StatusCode of the UA_Server_setConditionVariableFieldProperty*/
1500
UA_StatusCode UA_EXPORT
1501
UA_Server_setConditionVariableFieldProperty(UA_Server *server,
1502
                                            const UA_NodeId condition,
1503
                                            const UA_Variant *value,
1504
                                            const UA_QualifiedName variableFieldName,
1505
                                            const UA_QualifiedName variablePropertyName);
1506
1507
/* Triggers an event only for an enabled condition. The condition list is
1508
 * updated then with the last generated EventId.
1509
 *
1510
 * @param server The server object
1511
 * @param condition The NodeId of the node representation of the Condition Instance
1512
 * @param conditionSource The NodeId of the node representation of the Condition Source
1513
 * @param outEventId last generated EventId
1514
 * @return The StatusCode of the UA_Server_triggerConditionEvent method */
1515
UA_StatusCode UA_EXPORT
1516
UA_Server_triggerConditionEvent(UA_Server *server,
1517
                                const UA_NodeId condition,
1518
                                const UA_NodeId conditionSource,
1519
                                UA_ByteString *outEventId);
1520
1521
/* Add an optional condition field using its name. (TODO Adding optional methods
1522
 * is not implemented yet)
1523
 *
1524
 * @param server The server object
1525
 * @param condition The NodeId of the node representation of the Condition Instance
1526
 * @param conditionType The NodeId of the node representation of the Condition Type
1527
 * from which the optional field comes
1528
 * @param fieldName Name of the optional field
1529
 * @param outOptionalVariable The NodeId of the created field (Variable Node)
1530
 * @return The StatusCode of the UA_Server_addConditionOptionalField method */
1531
UA_StatusCode UA_EXPORT
1532
UA_Server_addConditionOptionalField(UA_Server *server,
1533
                                    const UA_NodeId condition,
1534
                                    const UA_NodeId conditionType,
1535
                                    const UA_QualifiedName fieldName,
1536
                                    UA_NodeId *outOptionalVariable);
1537
1538
/* Function used to set a user specific callback to TwoStateVariable Fields of a
1539
 * condition. The callbacks will be called before triggering the events when
1540
 * transition to true State of EnabledState/Id, AckedState/Id, ConfirmedState/Id
1541
 * and ActiveState/Id occurs.
1542
 *
1543
 * @param server The server object
1544
 * @param condition The NodeId of the node representation of the Condition Instance
1545
 * @param conditionSource The NodeId of the node representation of the Condition Source
1546
 * @param removeBranch (Not Implemented yet)
1547
 * @param callback User specific callback function
1548
 * @param callbackType Callback function type, indicates where it should be called
1549
 * @return The StatusCode of the UA_Server_setConditionTwoStateVariableCallback method */
1550
UA_StatusCode UA_EXPORT
1551
UA_Server_setConditionTwoStateVariableCallback(UA_Server *server,
1552
                                               const UA_NodeId condition,
1553
                                               const UA_NodeId conditionSource,
1554
                                               UA_Boolean removeBranch,
1555
                                               UA_TwoStateVariableChangeCallback callback,
1556
                                               UA_TwoStateVariableCallbackType callbackType);
1557
1558
/* Delete a condition from the address space and the internal lists.
1559
 *
1560
 * @param server The server object
1561
 * @param condition The NodeId of the node representation of the Condition Instance
1562
 * @param conditionSource The NodeId of the node representation of the Condition Source
1563
 * @return ``UA_STATUSCODE_GOOD`` on success */
1564
UA_StatusCode UA_EXPORT
1565
UA_Server_deleteCondition(UA_Server *server,
1566
                          const UA_NodeId condition,
1567
                          const UA_NodeId conditionSource);
1568
1569
/* Set the LimitState of the LimitAlarmType
1570
 *
1571
 * @param server The server object
1572
 * @param conditionId NodeId of the node representation of the Condition Instance
1573
 * @param limitValue The value from the trigger node */
1574
UA_StatusCode UA_EXPORT
1575
UA_Server_setLimitState(UA_Server *server, const UA_NodeId conditionId,
1576
                        UA_Double limitValue);
1577
1578
/* Parse the certifcate and set Expiration date
1579
 *
1580
 * @param server The server object
1581
 * @param conditionId NodeId of the node representation of the Condition Instance
1582
 * @param cert The certificate for parsing */
1583
UA_StatusCode UA_EXPORT
1584
UA_Server_setExpirationDate(UA_Server *server, const UA_NodeId conditionId,
1585
                            UA_ByteString  cert);
1586
1587
#endif /* UA_ENABLE_SUBSCRIPTIONS_ALARMS_CONDITIONS */
1588
1589
/**
1590
 * .. _async-operations:
1591
 *
1592
 * Async Operations
1593
 * ----------------
1594
 * Some operations (such as reading out a sensor that needs to warm up) can take
1595
 * quite some time. In order not to block the server during such an operation, it
1596
 * can be "outsourced" to a worker thread.
1597
 *
1598
 * Take the example of a CallRequest. It is split into the individual method call
1599
 * operations. If the method is marked as async, then the operation is put into a
1600
 * queue where it is be retrieved by a worker. The worker returns the result when
1601
 * ready. See the examples in ``/examples/tutorial_server_method_async.c`` for
1602
 * the usage.
1603
 *
1604
 * Note that the operation can time out (see the asyncOperationTimeout setting in
1605
 * the server config) also when it has been retrieved by the worker. */
1606
1607
#if UA_MULTITHREADING >= 100
1608
1609
/* Set the async flag in a method node */
1610
UA_StatusCode UA_EXPORT
1611
UA_Server_setMethodNodeAsync(UA_Server *server, const UA_NodeId id,
1612
                             UA_Boolean isAsync);
1613
1614
typedef enum {
1615
    UA_ASYNCOPERATIONTYPE_INVALID, /* 0, the default */
1616
    UA_ASYNCOPERATIONTYPE_CALL
1617
    /* UA_ASYNCOPERATIONTYPE_READ, */
1618
    /* UA_ASYNCOPERATIONTYPE_WRITE, */
1619
} UA_AsyncOperationType;
1620
1621
typedef union {
1622
    UA_CallMethodRequest callMethodRequest;
1623
    /* UA_ReadValueId readValueId; */
1624
    /* UA_WriteValue writeValue; */
1625
} UA_AsyncOperationRequest;
1626
1627
typedef union {
1628
    UA_CallMethodResult callMethodResult;
1629
    /* UA_DataValue readResult; */
1630
    /* UA_StatusCode writeResult; */
1631
} UA_AsyncOperationResponse;
1632
1633
/* Get the next async operation without blocking
1634
 *
1635
 * @param server The server object
1636
 * @param type The type of the async operation
1637
 * @param request Receives pointer to the operation
1638
 * @param context Receives the pointer to the operation context
1639
 * @param timeout The timestamp when the operation times out and can
1640
 *        no longer be returned to the client. The response has to
1641
 *        be set in UA_Server_setAsyncOperationResult in any case.
1642
 * @return false if queue is empty, true else */
1643
UA_Boolean UA_EXPORT
1644
UA_Server_getAsyncOperationNonBlocking(UA_Server *server,
1645
                                       UA_AsyncOperationType *type,
1646
                                       const UA_AsyncOperationRequest **request,
1647
                                       void **context, UA_DateTime *timeout);
1648
1649
/* UA_Boolean UA_EXPORT */
1650
/* UA_Server_getAsyncOperationBlocking(UA_Server *server, */
1651
/*                                     UA_AsyncOperationType *type, */
1652
/*                                     const UA_AsyncOperationRequest **request, */
1653
/*                                     void **context, UA_DateTime *timeout); */
1654
1655
/* Submit an async operation result
1656
 *
1657
 * @param server The server object
1658
 * @param response Pointer to the operation result
1659
 * @param context Pointer to the operation context */
1660
void UA_EXPORT
1661
UA_Server_setAsyncOperationResult(UA_Server *server,
1662
                                  const UA_AsyncOperationResponse *response,
1663
                                  void *context);
1664
1665
#endif /* !UA_MULTITHREADING >= 100 */
1666
1667
/**
1668
 * Statistics
1669
 * ----------
1670
 * Statistic counters keeping track of the current state of the stack. Counters
1671
 * are structured per OPC UA communication layer. */
1672
1673
typedef struct {
1674
   UA_SecureChannelStatistics scs;
1675
   UA_SessionStatistics ss;
1676
} UA_ServerStatistics;
1677
1678
UA_ServerStatistics UA_EXPORT UA_THREADSAFE
1679
UA_Server_getStatistics(UA_Server *server);
1680
1681
/**
1682
 * Reverse Connect
1683
 * ---------------
1684
 * The reverse connect feature of OPC UA permits the server instead of the
1685
 * client to establish the connection. The client must expose the listening port
1686
 * so the server is able to reach it. */
1687
1688
/* The reverse connect state change callback is called whenever the state of a
1689
 * reverse connect is changed by a connection attempt, a successful connection
1690
 * or a connection loss.
1691
 *
1692
 * The reverse connect states reflect the state of the secure channel currently
1693
 * associated with a reverse connect. The state will remain
1694
 * UA_SECURECHANNELSTATE_CONNECTING while the server attempts repeatedly to
1695
 * establish a connection. */
1696
typedef void (*UA_Server_ReverseConnectStateCallback)(UA_Server *server,
1697
                                                      UA_UInt64 handle,
1698
                                                      UA_SecureChannelState state,
1699
                                                      void *context);
1700
1701
/* Registers a reverse connect in the server. The server periodically attempts
1702
 * to establish a connection if the initial connect fails or if the connection
1703
 * breaks.
1704
 *
1705
 * @param server The server object
1706
 * @param url The URL of the remote client
1707
 * @param stateCallback The callback which will be called on state changes
1708
 * @param callbackContext The context for the state callback
1709
 * @param handle Is set to the handle of the reverse connect if not NULL
1710
 * @return Returns UA_STATUSCODE_GOOD if the reverse connect has been registered */
1711
UA_StatusCode UA_EXPORT
1712
UA_Server_addReverseConnect(UA_Server *server, UA_String url,
1713
                            UA_Server_ReverseConnectStateCallback stateCallback,
1714
                            void *callbackContext, UA_UInt64 *handle);
1715
1716
/* Removes a reverse connect from the server and closes the connection if it is
1717
 * currently open.
1718
 *
1719
 * @param server The server object
1720
 * @param handle The handle of the reverse connect to remove
1721
 * @return Returns UA_STATUSCODE_GOOD if the reverse connect has been
1722
 *         successfully removed */
1723
UA_StatusCode UA_EXPORT
1724
UA_Server_removeReverseConnect(UA_Server *server, UA_UInt64 handle);
1725
1726
/**
1727
 * Utility Functions
1728
 * ----------------- */
1729
1730
/* Lookup a datatype by its NodeId. Takes the custom types in the server
1731
 * configuration into account. Return NULL if none found. */
1732
UA_EXPORT const UA_DataType *
1733
UA_Server_findDataType(UA_Server *server, const UA_NodeId *typeId);
1734
1735
/* Add a new namespace to the server. Returns the index of the new namespace */
1736
UA_UInt16 UA_EXPORT UA_THREADSAFE
1737
UA_Server_addNamespace(UA_Server *server, const char* name);
1738
1739
/* Get namespace by name from the server. */
1740
UA_StatusCode UA_EXPORT UA_THREADSAFE
1741
UA_Server_getNamespaceByName(UA_Server *server, const UA_String namespaceUri,
1742
                             size_t* foundIndex);
1743
1744
/* Get namespace by id from the server. */
1745
UA_StatusCode UA_EXPORT UA_THREADSAFE
1746
UA_Server_getNamespaceByIndex(UA_Server *server, const size_t namespaceIndex,
1747
                              UA_String *foundUri);
1748
1749
/**
1750
 * .. _object-interaction:
1751
 *
1752
 * Interacting with Objects
1753
 * ~~~~~~~~~~~~~~~~~~~~~~~~
1754
 * Objects in the information model are represented as ObjectNodes. Some
1755
 * convenience functions are provided to simplify the interaction with objects. */
1756
1757
/* Write an object property. The property is represented as a VariableNode with
1758
 * a ``HasProperty`` reference from the ObjectNode. The VariableNode is
1759
 * identified by its BrowseName. Writing the property sets the value attribute
1760
 * of the VariableNode.
1761
 *
1762
 * @param server The server object
1763
 * @param objectId The identifier of the object (node)
1764
 * @param propertyName The name of the property
1765
 * @param value The value to be set for the event attribute
1766
 * @return The StatusCode for setting the event attribute */
1767
UA_StatusCode UA_EXPORT UA_THREADSAFE
1768
UA_Server_writeObjectProperty(UA_Server *server, const UA_NodeId objectId,
1769
                              const UA_QualifiedName propertyName,
1770
                              const UA_Variant value);
1771
1772
/* Directly point to the scalar value instead of a variant */
1773
UA_StatusCode UA_EXPORT UA_THREADSAFE
1774
UA_Server_writeObjectProperty_scalar(UA_Server *server, const UA_NodeId objectId,
1775
                                     const UA_QualifiedName propertyName,
1776
                                     const void *value, const UA_DataType *type);
1777
1778
/* Read an object property.
1779
 *
1780
 * @param server The server object
1781
 * @param objectId The identifier of the object (node)
1782
 * @param propertyName The name of the property
1783
 * @param value Contains the property value after reading. Must not be NULL.
1784
 * @return The StatusCode for setting the event attribute */
1785
UA_StatusCode UA_EXPORT UA_THREADSAFE
1786
UA_Server_readObjectProperty(UA_Server *server, const UA_NodeId objectId,
1787
                             const UA_QualifiedName propertyName,
1788
                             UA_Variant *value);
1789
1790
/**
1791
 * Timed Callbacks
1792
 * ~~~~~~~~~~~~~~~
1793
 * Add a callback to the server that is executed at a defined time.
1794
 * The callback can also be registered with a cyclic interval. */
1795
1796
/* Add a callback for execution at a specified time. If the indicated time lies
1797
 * in the past, then the callback is executed at the next iteration of the
1798
 * server's main loop.
1799
 *
1800
 * @param server The server object.
1801
 * @param callback The callback that shall be added.
1802
 * @param data Data that is forwarded to the callback.
1803
 * @param date The timestamp for the execution time.
1804
 * @param callbackId Set to the identifier of the repeated callback . This can
1805
 *        be used to cancel the callback later on. If the pointer is null, the
1806
 *        identifier is not set.
1807
 * @return Upon success, ``UA_STATUSCODE_GOOD`` is returned. An error code
1808
 *         otherwise. */
1809
UA_StatusCode UA_EXPORT UA_THREADSAFE
1810
UA_Server_addTimedCallback(UA_Server *server, UA_ServerCallback callback,
1811
                           void *data, UA_DateTime date, UA_UInt64 *callbackId);
1812
1813
/* Add a callback for cyclic repetition to the server.
1814
 *
1815
 * @param server The server object.
1816
 * @param callback The callback that shall be added.
1817
 * @param data Data that is forwarded to the callback.
1818
 * @param interval_ms The callback shall be repeatedly executed with the given
1819
 *        interval (in ms). The interval must be positive. The first execution
1820
 *        occurs at now() + interval at the latest.
1821
 * @param callbackId Set to the identifier of the repeated callback . This can
1822
 *        be used to cancel the callback later on. If the pointer is null, the
1823
 *        identifier is not set.
1824
 * @return Upon success, ``UA_STATUSCODE_GOOD`` is returned. An error code
1825
 *         otherwise. */
1826
UA_StatusCode UA_EXPORT UA_THREADSAFE
1827
UA_Server_addRepeatedCallback(UA_Server *server, UA_ServerCallback callback,
1828
                              void *data, UA_Double interval_ms,
1829
                              UA_UInt64 *callbackId);
1830
1831
UA_StatusCode UA_EXPORT UA_THREADSAFE
1832
UA_Server_changeRepeatedCallbackInterval(UA_Server *server, UA_UInt64 callbackId,
1833
                                         UA_Double interval_ms);
1834
1835
/* Remove a repeated callback. Does nothing if the callback is not found. */
1836
void UA_EXPORT UA_THREADSAFE
1837
UA_Server_removeCallback(UA_Server *server, UA_UInt64 callbackId);
1838
1839
#define UA_Server_removeRepeatedCallback(server, callbackId) \
1840
    UA_Server_removeCallback(server, callbackId);
1841
1842
/**
1843
 * Update the Server Certificate at Runtime
1844
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1845
 * If certificateGroupId is null the DefaultApplicationGroup is used.
1846
 */
1847
1848
UA_StatusCode UA_EXPORT
1849
UA_Server_updateCertificate(UA_Server *server,
1850
                            const UA_NodeId certificateGroupId,
1851
                            const UA_NodeId certificateTypeId,
1852
                            const UA_ByteString certificate,
1853
                            const UA_ByteString *privateKey);
1854
1855
/* Creates a PKCS #10 DER encoded certificate request signed with the server's
1856
 * private key.
1857
 * If certificateGroupId is null the DefaultApplicationGroup is used.
1858
 */
1859
UA_StatusCode UA_EXPORT
1860
UA_Server_createSigningRequest(UA_Server *server,
1861
                               const UA_NodeId certificateGroupId,
1862
                               const UA_NodeId certificateTypeId,
1863
                               const UA_String *subjectName,
1864
                               const UA_Boolean *regenerateKey,
1865
                               const UA_ByteString *nonce,
1866
                               UA_ByteString *csr);
1867
1868
/* Adds certificates and Certificate Revocation Lists (CRLs) to a specific
1869
 * certificate group on the server.
1870
 *
1871
 * @param server The server object
1872
 * @param certificateGroupId The NodeId of the certificate group where
1873
 *        certificates will be added
1874
 * @param certificates The certificates to be added
1875
 * @param certificatesSize The number of certificates
1876
 * @param crls The associated CRLs for the certificates, required when adding
1877
 *        issuer certificates
1878
 * @param crlsSize The number of CRLs
1879
 * @param isTrusted Indicates whether the certificates should be added to the
1880
 *        trusted list or the issuer list
1881
 * @param appendCertificates Indicates whether the certificates should be added
1882
 *        to the list or replace the existing list
1883
 * @return ``UA_STATUSCODE_GOOD`` on success */
1884
UA_StatusCode UA_EXPORT
1885
UA_Server_addCertificates(UA_Server *server,
1886
                          const UA_NodeId certificateGroupId,
1887
                          UA_ByteString *certificates,
1888
                          size_t certificatesSize,
1889
                          UA_ByteString *crls,
1890
                          size_t crlsSize,
1891
                          const UA_Boolean isTrusted,
1892
                          const UA_Boolean appendCertificates);
1893
1894
/* Removes certificates from a specific certificate group on the server. The
1895
 * corresponding CRLs are removed automatically.
1896
 *
1897
 * @param server The server object
1898
 * @param certificateGroupId The NodeId of the certificate group from which
1899
 *        certificates will be removed
1900
 * @param certificates The certificates to be removed
1901
 * @param certificatesSize The number of certificates
1902
 * @param isTrusted Indicates whether the certificates are being removed from
1903
 *        the trusted list or the issuer list
1904
 * @return ``UA_STATUSCODE_GOOD`` on success */
1905
UA_StatusCode UA_EXPORT
1906
UA_Server_removeCertificates(UA_Server *server,
1907
                          const UA_NodeId certificateGroupId,
1908
                          UA_ByteString *certificates,
1909
                          size_t certificatesSize,
1910
                          const UA_Boolean isTrusted);
1911
1912
_UA_END_DECLS
1913
1914
#ifdef UA_ENABLE_PUBSUB
1915
#include <open62541/server_pubsub.h>
1916
#endif
1917
1918
#endif /* UA_SERVER_H_ */