tutorial_server_monitoreditems.c 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 <ua_server.h>
  21. #include <ua_config_default.h>
  22. #include <ua_log_stdout.h>
  23. #include <ua_client_subscriptions.h>
  24. #include <signal.h>
  25. #include <stdlib.h>
  26. static void
  27. dataChangeNotificationCallback(UA_Server *server, UA_UInt32 monitoredItemId,
  28. void *monitoredItemContext, const UA_NodeId *nodeId,
  29. void *nodeContext, UA_UInt32 attributeId,
  30. const UA_DataValue *value) {
  31. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Received Notification");
  32. }
  33. static void
  34. addMonitoredItemToCurrentTimeVariable(UA_Server *server) {
  35. UA_NodeId currentTimeNodeId =
  36. UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER_SERVERSTATUS_CURRENTTIME);
  37. UA_MonitoredItemCreateRequest monRequest =
  38. UA_MonitoredItemCreateRequest_default(currentTimeNodeId);
  39. monRequest.requestedParameters.samplingInterval = 100.0; /* 100 ms interval */
  40. UA_Server_createDataChangeMonitoredItem(server, UA_TIMESTAMPSTORETURN_SOURCE,
  41. monRequest, NULL, dataChangeNotificationCallback);
  42. }
  43. /** It follows the main server code, making use of the above definitions. */
  44. UA_Boolean running = true;
  45. static void stopHandler(int sign) {
  46. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "received ctrl-c");
  47. running = false;
  48. }
  49. int main(void) {
  50. signal(SIGINT, stopHandler);
  51. signal(SIGTERM, stopHandler);
  52. UA_ServerConfig *config = UA_ServerConfig_new_default();
  53. UA_Server *server = UA_Server_new(config);
  54. addMonitoredItemToCurrentTimeVariable(server);
  55. UA_StatusCode retval = UA_Server_run(server, &running);
  56. UA_Server_delete(server);
  57. UA_ServerConfig_delete(config);
  58. return retval == UA_STATUSCODE_GOOD ? EXIT_SUCCESS : EXIT_FAILURE;
  59. }