server_datasource.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 <signal.h>
  6. #include <stdio.h>
  7. #ifdef UA_NO_AMALGAMATION
  8. # include "ua_types.h"
  9. # include "ua_server.h"
  10. # include "logger_stdout.h"
  11. # include "networklayer_tcp.h"
  12. #else
  13. # include "open62541.h"
  14. #endif
  15. UA_Boolean running = 1;
  16. UA_Logger logger;
  17. static void stopHandler(int sign) {
  18. UA_LOG_INFO(logger, UA_LOGCATEGORY_SERVER, "received ctrl-c");
  19. running = 0;
  20. }
  21. static UA_StatusCode readInteger(void *handle, UA_Boolean sourceTimeStamp, const UA_NumericRange *range, UA_DataValue *dataValue) {
  22. dataValue->hasValue = UA_TRUE;
  23. UA_Variant_setScalarCopy(&dataValue->value, (UA_UInt32*)handle, &UA_TYPES[UA_TYPES_INT32]);
  24. UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND, "read value %i", *(UA_UInt32*)handle);
  25. return UA_STATUSCODE_GOOD;
  26. }
  27. static UA_StatusCode writeInteger(void *handle, const UA_Variant *data, const UA_NumericRange *range){
  28. if(UA_Variant_isScalar(data) && data->type == &UA_TYPES[UA_TYPES_INT32] && data->data){
  29. *(UA_UInt32*)handle = *(UA_Int32*)data->data;
  30. }
  31. UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND, "written value %i", *(UA_UInt32*)handle);
  32. return UA_STATUSCODE_GOOD;
  33. }
  34. int main(int argc, char** argv) {
  35. signal(SIGINT, stopHandler); /* catches ctrl-c */
  36. UA_Server *server = UA_Server_new(UA_ServerConfig_standard);
  37. logger = Logger_Stdout_new();
  38. UA_Server_setLogger(server, logger);
  39. UA_Server_addNetworkLayer(server, ServerNetworkLayerTCP_new(UA_ConnectionConfig_standard, 16664));
  40. UA_Int32 myInteger = 42;
  41. /* add a variable node to the address space */
  42. UA_NodeId myIntegerNodeId = UA_NODEID_STRING(1, "the.answer"); /* UA_NODEID_NULL would assign a random free nodeid */
  43. UA_QualifiedName myIntegerName = UA_QUALIFIEDNAME(1, "the answer");
  44. UA_LocalizedText myIntegerBrowseName = UA_LOCALIZEDTEXT("en_US","the answer");
  45. UA_DataSource dateDataSource = (UA_DataSource) {.handle = &myInteger, .read = readInteger, .write = writeInteger};
  46. UA_Server_addDataSourceVariableNode(server, myIntegerNodeId, myIntegerName, myIntegerBrowseName, myIntegerBrowseName, 0, 0,
  47. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  48. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  49. dateDataSource,
  50. NULL);
  51. UA_StatusCode retval = UA_Server_run(server, 1, &running);
  52. UA_Server_delete(server);
  53. return retval;
  54. }