client_async.c 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. #ifndef _XOPEN_SOURCE
  4. # define _XOPEN_SOURCE 600
  5. #endif
  6. #ifndef _DEFAULT_SOURCE
  7. # define _DEFAULT_SOURCE
  8. #endif
  9. /* On older systems we need to define _BSD_SOURCE.
  10. * _DEFAULT_SOURCE is an alias for that. */
  11. #ifndef _BSD_SOURCE
  12. # define _BSD_SOURCE
  13. #endif
  14. #include <stdio.h>
  15. #include "open62541.h"
  16. #ifdef _WIN32
  17. # include <windows.h>
  18. # define UA_sleep_ms(X) Sleep(X)
  19. #else
  20. # include <unistd.h>
  21. # define UA_sleep_ms(X) usleep(X * 1000)
  22. #endif
  23. #define NODES_EXIST
  24. /* async connection callback, it only gets called after the completion of the whole
  25. * connection process*/
  26. static void
  27. onConnect (UA_Client *client, void *userdata, UA_UInt32 requestId,
  28. void *status) {
  29. printf ("Async connect returned with status code %s\n",
  30. UA_StatusCode_name (*(UA_StatusCode *) status));
  31. }
  32. static
  33. void
  34. fileBrowsed (UA_Client *client, void *userdata, UA_UInt32 requestId,
  35. UA_BrowseResponse *response) {
  36. printf ("%-50s%i\n", "Received BrowseResponse for request ", requestId);
  37. UA_String us = *(UA_String *) userdata;
  38. printf ("---%.*s passed safely \n", (int) us.length, us.data);
  39. }
  40. /*high-level function callbacks*/
  41. static
  42. void
  43. readValueAttributeCallback (UA_Client *client, void *userdata,
  44. UA_UInt32 requestId, UA_Variant *var) {
  45. printf ("%-50s%i\n", "Read value attribute for request", requestId);
  46. if (UA_Variant_hasScalarType (var, &UA_TYPES[UA_TYPES_INT32])) {
  47. UA_Int32 int_val = *(UA_Int32*) var->data;
  48. printf ("---%-40s%-8i\n",
  49. "Reading the value of node (1, \"the.answer\"):", int_val);
  50. }
  51. /*more type distinctions possible*/
  52. return;
  53. }
  54. static
  55. void
  56. attrWritten (UA_Client *client, void *userdata, UA_UInt32 requestId,
  57. UA_WriteResponse *response) {
  58. /*assuming no data to be retrieved by writing attributes*/
  59. printf ("%-50s%i\n", "Wrote value attribute for request ", requestId);
  60. UA_WriteResponse_deleteMembers(response);
  61. }
  62. #ifdef NODES_EXIST
  63. static void
  64. methodCalled (UA_Client *client, void *userdata, UA_UInt32 requestId,
  65. UA_CallResponse *response) {
  66. printf ("%-50s%i\n", "Called method for request ", requestId);
  67. size_t outputSize;
  68. UA_Variant *output;
  69. UA_StatusCode retval = response->responseHeader.serviceResult;
  70. if (retval == UA_STATUSCODE_GOOD) {
  71. if (response->resultsSize == 1)
  72. retval = response->results[0].statusCode;
  73. else
  74. retval = UA_STATUSCODE_BADUNEXPECTEDERROR;
  75. }
  76. if (retval != UA_STATUSCODE_GOOD) {
  77. UA_CallResponse_deleteMembers (response);
  78. }
  79. /* Move the output arguments */
  80. output = response->results[0].outputArguments;
  81. outputSize = response->results[0].outputArgumentsSize;
  82. response->results[0].outputArguments = NULL;
  83. response->results[0].outputArgumentsSize = 0;
  84. if (retval == UA_STATUSCODE_GOOD) {
  85. printf ("---Method call was successful, returned %lu values.\n",
  86. (unsigned long) outputSize);
  87. UA_Array_delete (output, outputSize, &UA_TYPES[UA_TYPES_VARIANT]);
  88. }
  89. else {
  90. printf ("---Method call was unsuccessful, returned %x values.\n",
  91. retval);
  92. }
  93. UA_CallResponse_deleteMembers (response);
  94. }
  95. static void
  96. translateCalled (UA_Client *client, void *userdata, UA_UInt32 requestId,
  97. UA_TranslateBrowsePathsToNodeIdsResponse *response) {
  98. printf ("%-50s%i\n", "Translated path for request ", requestId);
  99. if (response->results[0].targetsSize == 1) {
  100. return;
  101. }
  102. UA_TranslateBrowsePathsToNodeIdsResponse_deleteMembers (response);
  103. }
  104. #endif
  105. int
  106. main (int argc, char *argv[]) {
  107. UA_Client *client = UA_Client_new (UA_ClientConfig_default);
  108. UA_UInt32 reqId = 0;
  109. UA_String userdata = UA_STRING ("userdata");
  110. UA_BrowseRequest bReq;
  111. UA_BrowseRequest_init (&bReq);
  112. bReq.requestedMaxReferencesPerNode = 0;
  113. bReq.nodesToBrowse = UA_BrowseDescription_new ();
  114. bReq.nodesToBrowseSize = 1;
  115. bReq.nodesToBrowse[0].nodeId = UA_NODEID_NUMERIC (0,
  116. UA_NS0ID_OBJECTSFOLDER); /* browse objects folder */
  117. bReq.nodesToBrowse[0].resultMask = UA_BROWSERESULTMASK_ALL; /* return everything */
  118. UA_Client_connect_async (client, "opc.tcp://localhost:4840", onConnect,
  119. NULL);
  120. /*Windows needs time to response*/
  121. UA_sleep_ms(100);
  122. /* What happens if client tries to send request before connected? */
  123. UA_Client_sendAsyncBrowseRequest (client, &bReq, fileBrowsed, &userdata,
  124. &reqId);
  125. UA_DateTime startTime = UA_DateTime_nowMonotonic();
  126. do {
  127. /*TODO: fix memory-related bugs if condition not checked*/
  128. if (UA_Client_getState (client) == UA_CLIENTSTATE_SESSION) {
  129. /* If not connected requests are not sent */
  130. UA_Client_sendAsyncBrowseRequest (client, &bReq, fileBrowsed,
  131. &userdata, &reqId);
  132. }
  133. /* Requests are processed */
  134. UA_BrowseRequest_deleteMembers(&bReq);
  135. UA_Client_run_iterate (client, 0);
  136. UA_sleep_ms(100);
  137. /* Break loop if server cannot be connected within 2s -- prevents build timeout */
  138. if (UA_DateTime_nowMonotonic() - startTime > 2000 * UA_DATETIME_MSEC)
  139. break;
  140. }
  141. while (reqId < 10);
  142. /* Demo: high-level functions */
  143. UA_Int32 value = 0;
  144. UA_Variant myVariant;
  145. UA_Variant_init(&myVariant);
  146. UA_Variant input;
  147. UA_Variant_init (&input);
  148. for (UA_UInt16 i = 0; i < 5; i++) {
  149. if (UA_Client_getState (client) == UA_CLIENTSTATE_SESSION) {
  150. /* writing and reading value 1 to 5 */
  151. UA_Variant_setScalarCopy (&myVariant, &value, &UA_TYPES[UA_TYPES_INT32]);
  152. value++;
  153. UA_Client_writeValueAttribute_async(client,
  154. UA_NODEID_STRING (1, "the.answer"),
  155. &myVariant, attrWritten, NULL,
  156. &reqId);
  157. UA_Variant_deleteMembers (&myVariant);
  158. UA_Client_readValueAttribute_async(client,
  159. UA_NODEID_STRING (1, "the.answer"),
  160. readValueAttributeCallback, NULL,
  161. &reqId);
  162. //TODO: check the existance of the nodes inside these functions (otherwise seg faults)
  163. #ifdef NODES_EXIST
  164. UA_String stringValue = UA_String_fromChars ("World");
  165. UA_Variant_setScalar (&input, &stringValue, &UA_TYPES[UA_TYPES_STRING]);
  166. UA_Client_call_async(client,
  167. UA_NODEID_NUMERIC (0, UA_NS0ID_OBJECTSFOLDER),
  168. UA_NODEID_NUMERIC (1, 62541), 1, &input,
  169. methodCalled, NULL, &reqId);
  170. UA_String_deleteMembers(&stringValue);
  171. #define pathSize 3
  172. char *paths[pathSize] = { "Server", "ServerStatus", "State" };
  173. UA_UInt32 ids[pathSize] = { UA_NS0ID_ORGANIZES,
  174. UA_NS0ID_HASCOMPONENT, UA_NS0ID_HASCOMPONENT };
  175. UA_Cient_translateBrowsePathsToNodeIds_async (client, paths, ids,
  176. pathSize,
  177. translateCalled, NULL,
  178. &reqId);
  179. #endif
  180. /* How often UA_Client_run_iterate is called depends on the number of request sent */
  181. UA_Client_run_iterate(client, 0);
  182. UA_Client_run_iterate(client, 0);
  183. }
  184. }
  185. UA_Client_run_iterate (client, 0);
  186. /* Async disconnect kills unprocessed requests */
  187. // UA_Client_disconnect_async (client, &reqId); //can only be used when connected = true
  188. // UA_Client_run_iterate (client, &timedOut);
  189. UA_Client_disconnect(client);
  190. UA_Client_delete (client);
  191. return (int) UA_STATUSCODE_GOOD;
  192. }