tutorial_server_monitoreditems.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. * Observing Attributes with Local MonitoredItems
  5. * ----------------------------------------------
  6. *
  7. * A client that is interested in the current value of a variable does not need
  8. * to regularly poll the variable. Instead, he can use the Subscription
  9. * mechanism to be notified about changes.
  10. *
  11. * So-called MonitoredItems define which values (node attributes) and events the
  12. * client wants to monitor. Under the right conditions, a notification is
  13. * created and added to the Subscription. The notifications currently in the
  14. * queue are regularly send to the client.
  15. *
  16. * The local user can add MonitoredItems as well. Locally, the MonitoredItems to
  17. * not go via a Subscription and each have an individual callback method and a
  18. * context pointer.
  19. */
  20. #include "open62541.h"
  21. #include <signal.h>
  22. static void
  23. dataChangeNotificationCallback(UA_Server *server, UA_UInt32 monitoredItemId,
  24. void *monitoredItemContext, const UA_NodeId *nodeId,
  25. void *nodeContext, UA_UInt32 attributeId,
  26. const UA_DataValue *value) {
  27. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Received Notification");
  28. }
  29. static void
  30. addMonitoredItemToCurrentTimeVariable(UA_Server *server) {
  31. UA_NodeId currentTimeNodeId =
  32. UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER_SERVERSTATUS_CURRENTTIME);
  33. UA_MonitoredItemCreateRequest monRequest =
  34. UA_MonitoredItemCreateRequest_default(currentTimeNodeId);
  35. monRequest.requestedParameters.samplingInterval = 100.0; /* 100 ms interval */
  36. UA_Server_createDataChangeMonitoredItem(server, UA_TIMESTAMPSTORETURN_SOURCE,
  37. monRequest, NULL, dataChangeNotificationCallback);
  38. }
  39. /** It follows the main server code, making use of the above definitions. */
  40. UA_Boolean running = true;
  41. static void stopHandler(int sign) {
  42. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "received ctrl-c");
  43. running = false;
  44. }
  45. int main(void) {
  46. signal(SIGINT, stopHandler);
  47. signal(SIGTERM, stopHandler);
  48. UA_ServerConfig *config = UA_ServerConfig_new_default();
  49. UA_Server *server = UA_Server_new(config);
  50. addMonitoredItemToCurrentTimeVariable(server);
  51. UA_StatusCode retval = UA_Server_run(server, &running);
  52. UA_Server_delete(server);
  53. UA_ServerConfig_delete(config);
  54. return (int)retval;
  55. }