server_datasource.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  3. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information.
  4. */
  5. #include <time.h>
  6. #include "ua_types.h"
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <signal.h>
  10. // provided by the open62541 lib
  11. #include "ua_server.h"
  12. // provided by the user, implementations available in the /examples folder
  13. #include "logger_stdout.h"
  14. #include "networklayer_tcp.h"
  15. // data source
  16. static UA_StatusCode readTimeData(const void *handle, UA_VariantData* data) {
  17. UA_DateTime *currentTime = UA_DateTime_new();
  18. if(!currentTime)
  19. return UA_STATUSCODE_BADOUTOFMEMORY;
  20. *currentTime = UA_DateTime_now();
  21. data->arrayLength = 1;
  22. data->dataPtr = currentTime;
  23. data->arrayDimensionsSize = -1;
  24. data->arrayDimensions = UA_NULL;
  25. return UA_STATUSCODE_GOOD;
  26. }
  27. static void releaseTimeData(const void *handle, UA_VariantData* data) {
  28. UA_DateTime_delete((UA_DateTime*)data->dataPtr);
  29. }
  30. UA_Boolean running = 1;
  31. static void stopHandler(int sign) {
  32. printf("Received Ctrl-C\n");
  33. running = 0;
  34. }
  35. int main(int argc, char** argv) {
  36. signal(SIGINT, stopHandler); /* catches ctrl-c */
  37. UA_Server *server = UA_Server_new();
  38. UA_Server_addNetworkLayer(server, ServerNetworkLayerTCP_new(UA_ConnectionConfig_standard, 16664));
  39. // add node with a callback to the userspace
  40. UA_Variant *myDateTimeVariant = UA_Variant_new();
  41. myDateTimeVariant->storageType = UA_VARIANT_DATASOURCE;
  42. myDateTimeVariant->storage.datasource = (UA_VariantDataSource)
  43. {.handle = UA_NULL,
  44. .read = readTimeData,
  45. .release = releaseTimeData,
  46. .write = (UA_StatusCode (*)(const void*, const UA_VariantData*))UA_NULL};
  47. myDateTimeVariant->type = &UA_TYPES[UA_TYPES_DATETIME];
  48. myDateTimeVariant->typeId = UA_NODEID_STATIC(UA_TYPES_IDS[UA_TYPES_DATETIME],0);
  49. UA_QualifiedName myDateTimeName;
  50. UA_QUALIFIEDNAME_ASSIGN(myDateTimeName, "the time");
  51. UA_Server_addVariableNode(server, myDateTimeVariant, &UA_NODEID_NULL, &myDateTimeName,
  52. &UA_NODEID_STATIC(UA_NS0ID_OBJECTSFOLDER,0),
  53. &UA_NODEID_STATIC(UA_NS0ID_ORGANIZES,0));
  54. UA_StatusCode retval = UA_Server_run(server, 1, &running);
  55. UA_Server_delete(server);
  56. return retval;
  57. }