tutorial_server_monitoreditems.c 2.6 KB

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