server_multicast.c 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. * A simple server instance which registers with the discovery server.
  5. * Compared to server_register.c this example waits until the LDS server announces
  6. * itself through mDNS. Therefore the LDS server needs to support multicast extension
  7. * (i.e., LDS-ME).
  8. */
  9. #include <signal.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include "open62541.h"
  13. UA_Logger logger = UA_Log_Stdout;
  14. UA_Boolean running = true;
  15. static void stopHandler(int sign) {
  16. UA_LOG_INFO(logger, UA_LOGCATEGORY_SERVER, "received ctrl-c");
  17. running = false;
  18. }
  19. static UA_StatusCode
  20. readInteger(UA_Server *server, const UA_NodeId *sessionId,
  21. void *sessionContext, const UA_NodeId *nodeId,
  22. void *nodeContext, UA_Boolean includeSourceTimeStamp,
  23. const UA_NumericRange *range, UA_DataValue *value) {
  24. UA_Int32 *myInteger = (UA_Int32*)nodeContext;
  25. value->hasValue = true;
  26. UA_Variant_setScalarCopy(&value->value, myInteger, &UA_TYPES[UA_TYPES_INT32]);
  27. // we know the nodeid is a string
  28. UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND, "Node read %.*s",
  29. (int)nodeId->identifier.string.length,
  30. nodeId->identifier.string.data);
  31. UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND,
  32. "read value %i", *(UA_UInt32 *)myInteger);
  33. return UA_STATUSCODE_GOOD;
  34. }
  35. static UA_StatusCode
  36. writeInteger(UA_Server *server, const UA_NodeId *sessionId,
  37. void *sessionContext, const UA_NodeId *nodeId,
  38. void *nodeContext, const UA_NumericRange *range,
  39. const UA_DataValue *value) {
  40. UA_Int32 *myInteger = (UA_Int32*)nodeContext;
  41. if(value->hasValue && UA_Variant_isScalar(&value->value) &&
  42. value->value.type == &UA_TYPES[UA_TYPES_INT32] && value->value.data)
  43. *myInteger = *(UA_Int32 *)value->value.data;
  44. // we know the nodeid is a string
  45. UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND, "Node written %.*s",
  46. (int)nodeId->identifier.string.length,
  47. nodeId->identifier.string.data);
  48. UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND,
  49. "written value %i", *(UA_UInt32 *)myInteger);
  50. return UA_STATUSCODE_GOOD;
  51. }
  52. char *discovery_url = NULL;
  53. UA_String *self_discovery_url = NULL;
  54. static void
  55. serverOnNetworkCallback(const UA_ServerOnNetwork *serverOnNetwork, UA_Boolean isServerAnnounce,
  56. UA_Boolean isTxtReceived, void *data) {
  57. if (discovery_url != NULL || !isServerAnnounce) {
  58. UA_LOG_DEBUG(logger, UA_LOGCATEGORY_SERVER,
  59. "serverOnNetworkCallback called, but discovery URL "
  60. "already initialized or is not announcing. Ignoring.");
  61. return; // we already have everything we need or we only want server announces
  62. }
  63. if (self_discovery_url != NULL && UA_String_equal(&serverOnNetwork->discoveryUrl, self_discovery_url)) {
  64. // skip self
  65. return;
  66. }
  67. if (!isTxtReceived)
  68. return; // we wait until the corresponding TXT record is announced.
  69. // Problem: how to handle if a Server does not announce the
  70. // optional TXT?
  71. // here you can filter for a specific LDS server, e.g. call FindServers on
  72. // the serverOnNetwork to make sure you are registering with the correct
  73. // LDS. We will ignore this for now
  74. UA_LOG_INFO(logger, UA_LOGCATEGORY_SERVER, "Another server announced itself on %.*s",
  75. (int)serverOnNetwork->discoveryUrl.length, serverOnNetwork->discoveryUrl.data);
  76. if (discovery_url != NULL)
  77. UA_free(discovery_url);
  78. discovery_url = (char*)UA_malloc(serverOnNetwork->discoveryUrl.length + 1);
  79. memcpy(discovery_url, serverOnNetwork->discoveryUrl.data, serverOnNetwork->discoveryUrl.length);
  80. discovery_url[serverOnNetwork->discoveryUrl.length] = 0;
  81. }
  82. int main(int argc, char **argv) {
  83. signal(SIGINT, stopHandler); /* catches ctrl-c */
  84. signal(SIGTERM, stopHandler);
  85. UA_ServerConfig *config = UA_ServerConfig_new_default();
  86. // To enable mDNS discovery, set application type to discovery server.
  87. config->applicationDescription.applicationType = UA_APPLICATIONTYPE_DISCOVERYSERVER;
  88. UA_String_deleteMembers(&config->applicationDescription.applicationUri);
  89. config->applicationDescription.applicationUri =
  90. UA_String_fromChars("urn:open62541.example.server_multicast");
  91. config->mdnsServerName = UA_String_fromChars("Sample Multicast Server");
  92. // See http://www.opcfoundation.org/UA/schemas/1.03/ServerCapabilities.csv
  93. //config.serverCapabilitiesSize = 1;
  94. //UA_String caps = UA_String_fromChars("LDS");
  95. //config.serverCapabilities = &caps;
  96. UA_Server *server = UA_Server_new(config);
  97. self_discovery_url = &config->networkLayers[0].discoveryUrl;
  98. /* add a variable node to the address space */
  99. UA_Int32 myInteger = 42;
  100. UA_NodeId myIntegerNodeId = UA_NODEID_STRING(1, "the.answer");
  101. UA_QualifiedName myIntegerName = UA_QUALIFIEDNAME(1, "the answer");
  102. UA_DataSource dateDataSource;
  103. dateDataSource.read = readInteger;
  104. dateDataSource.write = writeInteger;
  105. UA_VariableAttributes attr;
  106. UA_VariableAttributes_init(&attr);
  107. attr.description = UA_LOCALIZEDTEXT("en_US", "the answer");
  108. attr.displayName = UA_LOCALIZEDTEXT("en_US", "the answer");
  109. UA_Server_addDataSourceVariableNode(server, myIntegerNodeId,
  110. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  111. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  112. myIntegerName, UA_NODEID_NULL, attr, dateDataSource,
  113. &myInteger, NULL);
  114. // callback which is called when a new server is detected through mDNS
  115. UA_Server_setServerOnNetworkCallback(server, serverOnNetworkCallback, NULL);
  116. // Start the server and call iterate to wait for the multicast discovery of the LDS
  117. UA_StatusCode retval = UA_Server_run_startup(server);
  118. if (retval != UA_STATUSCODE_GOOD) {
  119. UA_LOG_ERROR(logger, UA_LOGCATEGORY_SERVER,
  120. "Could not start the server. StatusCode %s",
  121. UA_StatusCode_name(retval));
  122. UA_Server_delete(server);
  123. UA_ServerConfig_delete(config);
  124. UA_free(discovery_url);
  125. return 1;
  126. }
  127. UA_LOG_INFO(logger, UA_LOGCATEGORY_SERVER,
  128. "Server started. Waiting for announce of LDS Server.");
  129. while (running && discovery_url == NULL)
  130. UA_Server_run_iterate(server, true);
  131. if (!running) {
  132. UA_Server_delete(server);
  133. UA_ServerConfig_delete(config);
  134. UA_free(discovery_url);
  135. return 1;
  136. }
  137. UA_LOG_INFO(logger, UA_LOGCATEGORY_SERVER, "LDS-ME server found on %s", discovery_url);
  138. // periodic server register after 10 Minutes, delay first register for 500ms
  139. retval = UA_Server_addPeriodicServerRegisterCallback(server, discovery_url,
  140. 10 * 60 * 1000, 500, NULL);
  141. if (retval != UA_STATUSCODE_GOOD) {
  142. UA_LOG_ERROR(logger, UA_LOGCATEGORY_SERVER,
  143. "Could not create periodic job for server register. StatusCode %s",
  144. UA_StatusCode_name(retval));
  145. UA_Server_delete(server);
  146. UA_ServerConfig_delete(config);
  147. return 1;
  148. }
  149. while (running)
  150. UA_Server_run_iterate(server, true);
  151. UA_Server_run_shutdown(server);
  152. // UNregister the server from the discovery server.
  153. retval = UA_Server_unregister_discovery(server, discovery_url);
  154. //retval = UA_Server_unregister_discovery(server, "opc.tcp://localhost:4840" );
  155. if(retval != UA_STATUSCODE_GOOD)
  156. UA_LOG_ERROR(logger, UA_LOGCATEGORY_SERVER,
  157. "Could not unregister server from discovery server. "
  158. "StatusCode %s", UA_StatusCode_name(retval));
  159. UA_Server_delete(server);
  160. UA_ServerConfig_delete(config);
  161. UA_free(discovery_url);
  162. return (int)retval;
  163. }