tutorial_pubsub_subscribe.c 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. /**
  5. * IMPORTANT ANNOUNCEMENT
  6. * The PubSub subscriber API is currently not finished. This examples can be used to receive
  7. * and print the values, which are published by the tutorial_pubsub_publish example.
  8. * The following code uses internal API which will be later replaced by the higher-level
  9. * PubSub subscriber API.
  10. */
  11. #include "ua_pubsub_networkmessage.h"
  12. #include "ua_log_stdout.h"
  13. #include "ua_server.h"
  14. #include "ua_config_default.h"
  15. #include "ua_pubsub.h"
  16. #include "ua_network_pubsub_udp.h"
  17. #ifdef UA_ENABLE_PUBSUB_ETH_UADP
  18. #include "ua_network_pubsub_ethernet.h"
  19. #endif
  20. #include "src_generated/ua_types_generated.h"
  21. #include <stdio.h>
  22. #include <signal.h>
  23. #include <stdlib.h>
  24. UA_Boolean running = true;
  25. static void stopHandler(int sign) {
  26. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "received ctrl-c");
  27. running = false;
  28. }
  29. static void
  30. subscriptionPollingCallback(UA_Server *server, UA_PubSubConnection *connection) {
  31. UA_ByteString buffer;
  32. if (UA_ByteString_allocBuffer(&buffer, 512) != UA_STATUSCODE_GOOD) {
  33. UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
  34. "Message buffer allocation failed!");
  35. return;
  36. }
  37. /* Receive the message. Blocks for 5ms */
  38. UA_StatusCode retval =
  39. connection->channel->receive(connection->channel, &buffer, NULL, 5);
  40. if(retval != UA_STATUSCODE_GOOD || buffer.length == 0) {
  41. /* Workaround!! Reset buffer length. Receive can set the length to zero.
  42. * Then the buffer is not deleted because no memory allocation is
  43. * assumed.
  44. * TODO: Return an error code in 'receive' instead of setting the buf
  45. * length to zero. */
  46. buffer.length = 512;
  47. UA_ByteString_clear(&buffer);
  48. return;
  49. }
  50. /* Decode the message */
  51. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
  52. "Message length: %lu", (unsigned long) buffer.length);
  53. UA_NetworkMessage networkMessage;
  54. memset(&networkMessage, 0, sizeof(UA_NetworkMessage));
  55. size_t currentPosition = 0;
  56. UA_NetworkMessage_decodeBinary(&buffer, &currentPosition, &networkMessage);
  57. UA_ByteString_clear(&buffer);
  58. /* Is this the correct message type? */
  59. if(networkMessage.networkMessageType != UA_NETWORKMESSAGE_DATASET)
  60. goto cleanup;
  61. /* At least one DataSetMessage in the NetworkMessage? */
  62. if(networkMessage.payloadHeaderEnabled &&
  63. networkMessage.payloadHeader.dataSetPayloadHeader.count < 1)
  64. goto cleanup;
  65. /* Is this a KeyFrame-DataSetMessage? */
  66. UA_DataSetMessage *dsm = &networkMessage.payload.dataSetPayload.dataSetMessages[0];
  67. if(dsm->header.dataSetMessageType != UA_DATASETMESSAGE_DATAKEYFRAME)
  68. goto cleanup;
  69. /* Loop over the fields and print well-known content types */
  70. for(int i = 0; i < dsm->data.keyFrameData.fieldCount; i++) {
  71. const UA_DataType *currentType = dsm->data.keyFrameData.dataSetFields[i].value.type;
  72. if(currentType == &UA_TYPES[UA_TYPES_BYTE]) {
  73. UA_Byte value = *(UA_Byte *)dsm->data.keyFrameData.dataSetFields[i].value.data;
  74. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
  75. "Message content: [Byte] \tReceived data: %i", value);
  76. } else if (currentType == &UA_TYPES[UA_TYPES_DATETIME]) {
  77. UA_DateTime value = *(UA_DateTime *)dsm->data.keyFrameData.dataSetFields[i].value.data;
  78. UA_DateTimeStruct receivedTime = UA_DateTime_toStruct(value);
  79. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
  80. "Message content: [DateTime] \t"
  81. "Received date: %02i-%02i-%02i Received time: %02i:%02i:%02i",
  82. receivedTime.year, receivedTime.month, receivedTime.day,
  83. receivedTime.hour, receivedTime.min, receivedTime.sec);
  84. }
  85. }
  86. cleanup:
  87. UA_NetworkMessage_clear(&networkMessage);
  88. }
  89. static int
  90. run(UA_String *transportProfile, UA_NetworkAddressUrlDataType *networkAddressUrl) {
  91. signal(SIGINT, stopHandler);
  92. signal(SIGTERM, stopHandler);
  93. UA_ServerConfig *config = UA_ServerConfig_new_minimal(4801, NULL);
  94. /* Details about the PubSubTransportLayer can be found inside the
  95. * tutorial_pubsub_connection */
  96. config->pubsubTransportLayers = (UA_PubSubTransportLayer *)
  97. UA_calloc(2, sizeof(UA_PubSubTransportLayer));
  98. if (!config->pubsubTransportLayers) {
  99. UA_ServerConfig_delete(config);
  100. return EXIT_FAILURE;
  101. }
  102. config->pubsubTransportLayers[0] = UA_PubSubTransportLayerUDPMP();
  103. config->pubsubTransportLayersSize++;
  104. #ifdef UA_ENABLE_PUBSUB_ETH_UADP
  105. config->pubsubTransportLayers[1] = UA_PubSubTransportLayerEthernet();
  106. config->pubsubTransportLayersSize++;
  107. #endif
  108. UA_Server *server = UA_Server_new(config);
  109. UA_PubSubConnectionConfig connectionConfig;
  110. memset(&connectionConfig, 0, sizeof(connectionConfig));
  111. connectionConfig.name = UA_STRING("UADP Connection 1");
  112. connectionConfig.transportProfileUri = *transportProfile;
  113. connectionConfig.enabled = UA_TRUE;
  114. UA_Variant_setScalar(&connectionConfig.address, networkAddressUrl,
  115. &UA_TYPES[UA_TYPES_NETWORKADDRESSURLDATATYPE]);
  116. UA_NodeId connectionIdent;
  117. UA_StatusCode retval =
  118. UA_Server_addPubSubConnection(server, &connectionConfig, &connectionIdent);
  119. if(retval == UA_STATUSCODE_GOOD)
  120. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER,
  121. "The PubSub Connection was created successfully!");
  122. /* The following lines register the listening on the configured multicast
  123. * address and configure a repeated job, which is used to handle received
  124. * messages. */
  125. UA_PubSubConnection *connection =
  126. UA_PubSubConnection_findConnectionbyId(server, connectionIdent);
  127. if(connection != NULL) {
  128. UA_StatusCode rv = connection->channel->regist(connection->channel, NULL, NULL);
  129. if (rv == UA_STATUSCODE_GOOD) {
  130. UA_UInt64 subscriptionCallbackId;
  131. UA_Server_addRepeatedCallback(server, (UA_ServerCallback)subscriptionPollingCallback,
  132. connection, 100, &subscriptionCallbackId);
  133. } else {
  134. UA_LOG_WARNING(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "register channel failed: %s!",
  135. UA_StatusCode_name(rv));
  136. }
  137. }
  138. retval |= UA_Server_run(server, &running);
  139. UA_Server_delete(server);
  140. UA_ServerConfig_delete(config);
  141. return retval == UA_STATUSCODE_GOOD ? EXIT_SUCCESS : EXIT_FAILURE;;
  142. }
  143. static void
  144. usage(char *progname) {
  145. printf("usage: %s <uri> [device]\n", progname);
  146. }
  147. int main(int argc, char **argv) {
  148. UA_String transportProfile =
  149. UA_STRING("http://opcfoundation.org/UA-Profile/Transport/pubsub-udp-uadp");
  150. UA_NetworkAddressUrlDataType networkAddressUrl =
  151. {UA_STRING_NULL , UA_STRING("opc.udp://224.0.0.22:4840/")};
  152. if (argc > 1) {
  153. if (strcmp(argv[1], "-h") == 0) {
  154. usage(argv[0]);
  155. return EXIT_SUCCESS;
  156. } else if (strncmp(argv[1], "opc.udp://", 10) == 0) {
  157. networkAddressUrl.url = UA_STRING(argv[1]);
  158. } else if (strncmp(argv[1], "opc.eth://", 10) == 0) {
  159. transportProfile =
  160. UA_STRING("http://opcfoundation.org/UA-Profile/Transport/pubsub-eth-uadp");
  161. if (argc < 3) {
  162. printf("Error: UADP/ETH needs an interface name\n");
  163. return EXIT_FAILURE;
  164. }
  165. networkAddressUrl.networkInterface = UA_STRING(argv[2]);
  166. networkAddressUrl.url = UA_STRING(argv[1]);
  167. } else {
  168. printf("Error: unknown URI\n");
  169. return EXIT_FAILURE;
  170. }
  171. }
  172. return run(&transportProfile, &networkAddressUrl);
  173. }