tutorial_server_events.c 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  2. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
  3. /**
  4. * Generating events
  5. * -----------------
  6. * To make sense of the many things going on in a server, monitoring items can be useful. Though in many cases, data
  7. * change does not convey enough information to be the optimal solution. Events can be generated at any time,
  8. * hold a lot of information and can be filtered so the client only receives the specific attributes he is interested in.
  9. *
  10. * Emitting events by calling methods
  11. * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  12. * The following example will be based on the server method tutorial. We will be
  13. * creating a method node which generates an event from the server node.
  14. */
  15. #include <signal.h>
  16. #include "open62541.h"
  17. UA_Boolean running = true;
  18. static void stopHandler(int sig) {
  19. running = false;
  20. }
  21. /** The event we want to generate should be very simple. Since the `BaseEventType` is abstract,
  22. * we will have to create our own event type. `EventTypes` are saved internally as `ObjectTypes`,
  23. * so add the type as you would a new `ObjectType`.
  24. */
  25. static UA_NodeId eventType;
  26. static UA_StatusCode addNewEventType(UA_Server *server) {
  27. UA_ObjectTypeAttributes attr = UA_ObjectTypeAttributes_default;
  28. attr.displayName = UA_LOCALIZEDTEXT_ALLOC("en-US", "SimpleEventType");
  29. attr.description = UA_LOCALIZEDTEXT_ALLOC("en-US", "The simple event type we created");
  30. UA_Server_addObjectTypeNode(server, UA_NODEID_NULL,
  31. UA_NODEID_NUMERIC(0, UA_NS0ID_BASEEVENTTYPE),
  32. UA_NODEID_NUMERIC(0, UA_NS0ID_HASSUBTYPE),
  33. UA_QUALIFIEDNAME(0, "SimpleEventType"),
  34. attr, NULL, &eventType);
  35. UA_LocalizedText_deleteMembers(&attr.displayName);
  36. UA_LocalizedText_deleteMembers(&attr.description);
  37. return UA_STATUSCODE_GOOD;
  38. }
  39. /** Setting up an event
  40. * ^^^^^^^^^^^^^^^^^^^^^^
  41. * In order to set up the event, we can first use ``UA_Server_createEvent`` to give us a node representation of the event.
  42. * All we need for this is our `EventType`. Once we have our event node, which is saved internally as an `ObjectNode`,
  43. * we can define the attributes the event has the same way we would define the attributes of an object node. It is not
  44. * necessary to define the attributes `EventId`, `ReceiveTime`, `SourceNode` or `EventType` since these are set
  45. * automatically by the server. In this example, we will only be setting `Severity` and `Message`.
  46. */
  47. static UA_StatusCode setUpEvent(UA_Server *server, UA_NodeId *outId) {
  48. UA_StatusCode retval;
  49. retval = UA_Server_createEvent(server, eventType, outId);
  50. if (retval != UA_STATUSCODE_GOOD) {
  51. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
  52. "createEvent failed. StatusCode %s", UA_StatusCode_name(retval));
  53. return retval;
  54. }
  55. UA_Variant value;
  56. UA_RelativePathElement rpe;
  57. UA_RelativePathElement_init(&rpe);
  58. rpe.referenceTypeId = UA_NODEID_NUMERIC(0, UA_NS0ID_HASPROPERTY);
  59. rpe.isInverse = false;
  60. rpe.includeSubtypes = false;
  61. UA_BrowsePath bp;
  62. UA_BrowsePath_init(&bp);
  63. bp.startingNode = *outId;
  64. bp.relativePath.elementsSize = 1;
  65. bp.relativePath.elements = &rpe;
  66. /* severity */
  67. rpe.targetName = UA_QUALIFIEDNAME(0, "Severity");
  68. UA_BrowsePathResult bpr = UA_Server_translateBrowsePathToNodeIds(server, &bp);
  69. if (bpr.statusCode != UA_STATUSCODE_GOOD || bpr.targetsSize < 1) {
  70. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Event is missing severity attribute.\n");
  71. return bpr.statusCode;
  72. }
  73. UA_UInt16 eventSeverity = 100;
  74. UA_Variant_setScalar(&value, &eventSeverity, &UA_TYPES[UA_TYPES_UINT16]);
  75. UA_Server_writeValue(server, bpr.targets[0].targetId.nodeId, value);
  76. UA_BrowsePathResult_deleteMembers(&bpr);
  77. /* message */
  78. rpe.targetName = UA_QUALIFIEDNAME(0, "Message");
  79. bpr = UA_Server_translateBrowsePathToNodeIds(server, &bp);
  80. if (bpr.statusCode != UA_STATUSCODE_GOOD || bpr.targetsSize < 1) {
  81. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Event is missing message attribute.\n");
  82. return bpr.statusCode;
  83. }
  84. UA_LocalizedText eventMessage = UA_LOCALIZEDTEXT("en-US", "An event has been generated.");
  85. UA_Variant_setScalar(&value, &eventMessage, &UA_TYPES[UA_TYPES_LOCALIZEDTEXT]);
  86. UA_Server_writeValue(server, bpr.targets[0].targetId.nodeId, value);
  87. UA_BrowsePathResult_deleteMembers(&bpr);
  88. return UA_STATUSCODE_GOOD;
  89. }
  90. /** Triggering an event
  91. * ^^^^^^^^^^^^^^^^^^^^
  92. * First a node representing an event is generated using ``setUpEvent``. Once our event is good to go, we specify
  93. * a node which emits the event - in this case the server node. We can use ``UA_Server_triggerEvent`` to trigger our
  94. * event onto said node. Passing ``NULL`` as the second-last argument means we will not receive the `EventId`.
  95. * The last boolean argument states whether the node should be deleted. */
  96. static UA_StatusCode
  97. generateEventMethodCallback(UA_Server *server,
  98. const UA_NodeId *sessionId, void *sessionHandle,
  99. const UA_NodeId *methodId, void *methodContext,
  100. const UA_NodeId *objectId, void *objectContext,
  101. size_t inputSize, const UA_Variant *input,
  102. size_t outputSize, UA_Variant *output) {
  103. /* set up event */
  104. UA_NodeId eventNodeId;
  105. UA_StatusCode retval = setUpEvent(server, &eventNodeId);
  106. if (retval != UA_STATUSCODE_GOOD) {
  107. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
  108. "Creating event failed. StatusCode %s", UA_StatusCode_name(retval));
  109. return retval;
  110. }
  111. retval = UA_Server_triggerEvent(server, eventNodeId, UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER), NULL, UA_TRUE);
  112. if (retval != UA_STATUSCODE_GOOD) {
  113. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
  114. "Triggering event failed. StatusCode %s", UA_StatusCode_name(retval));
  115. return retval;
  116. }
  117. return retval;
  118. }
  119. /** Now, all that is left to do is to create a method node which uses our callback. We do not
  120. * require any input and as output we will be using the `EventId` we receive from ``triggerEvent``. The `EventId` is
  121. * generated by the server internally and is a random unique ID which identifies that specific event.
  122. *
  123. * This method node will be added to a basic server setup.
  124. */
  125. static void
  126. addGenerateEventMethod(UA_Server *server) {
  127. UA_MethodAttributes generateAttr = UA_MethodAttributes_default;
  128. generateAttr.description = UA_LOCALIZEDTEXT("en-US","Generate an event.");
  129. generateAttr.displayName = UA_LOCALIZEDTEXT("en-US","Generate Event");
  130. generateAttr.executable = true;
  131. generateAttr.userExecutable = true;
  132. UA_Server_addMethodNode(server, UA_NODEID_NUMERIC(1, 62541),
  133. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  134. UA_NODEID_NUMERIC(0, UA_NS0ID_HASORDEREDCOMPONENT),
  135. UA_QUALIFIEDNAME(1, "Generate Event"),
  136. generateAttr, &generateEventMethodCallback,
  137. 0, NULL, 0, NULL, NULL, NULL);
  138. }
  139. int main (void) {
  140. /* default server values */
  141. signal(SIGINT, stopHandler);
  142. signal(SIGTERM, stopHandler);
  143. UA_ServerConfig *config = UA_ServerConfig_new_default();
  144. UA_Server *server = UA_Server_new(config);
  145. addNewEventType(server);
  146. addGenerateEventMethod(server);
  147. /* return value */
  148. UA_StatusCode retval = UA_Server_run(server, &running);
  149. UA_Server_delete(server);
  150. UA_ServerConfig_delete(config);
  151. return (int) retval;
  152. }