client_async.c 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. #ifdef UA_ENABLE_METHODCALLS
  64. static void
  65. methodCalled(UA_Client *client, void *userdata, UA_UInt32 requestId,
  66. UA_CallResponse *response) {
  67. printf ("%-50s%i\n", "Called method for request ", requestId);
  68. size_t outputSize;
  69. UA_Variant *output;
  70. UA_StatusCode retval = response->responseHeader.serviceResult;
  71. if (retval == UA_STATUSCODE_GOOD) {
  72. if (response->resultsSize == 1)
  73. retval = response->results[0].statusCode;
  74. else
  75. retval = UA_STATUSCODE_BADUNEXPECTEDERROR;
  76. }
  77. if (retval != UA_STATUSCODE_GOOD) {
  78. UA_CallResponse_deleteMembers (response);
  79. }
  80. /* Move the output arguments */
  81. output = response->results[0].outputArguments;
  82. outputSize = response->results[0].outputArgumentsSize;
  83. response->results[0].outputArguments = NULL;
  84. response->results[0].outputArgumentsSize = 0;
  85. if (retval == UA_STATUSCODE_GOOD) {
  86. printf ("---Method call was successful, returned %lu values.\n",
  87. (unsigned long) outputSize);
  88. UA_Array_delete (output, outputSize, &UA_TYPES[UA_TYPES_VARIANT]);
  89. }
  90. else {
  91. printf ("---Method call was unsuccessful, returned %x values.\n",
  92. retval);
  93. }
  94. UA_CallResponse_deleteMembers (response);
  95. }
  96. static void
  97. translateCalled (UA_Client *client, void *userdata, UA_UInt32 requestId,
  98. UA_TranslateBrowsePathsToNodeIdsResponse *response) {
  99. printf ("%-50s%i\n", "Translated path for request ", requestId);
  100. if (response->results[0].targetsSize == 1) {
  101. return;
  102. }
  103. UA_TranslateBrowsePathsToNodeIdsResponse_deleteMembers (response);
  104. }
  105. #endif /* UA_ENABLE_METHODCALLS */
  106. #endif
  107. int
  108. main (int argc, char *argv[]) {
  109. UA_Client *client = UA_Client_new (UA_ClientConfig_default);
  110. UA_UInt32 reqId = 0;
  111. UA_String userdata = UA_STRING ("userdata");
  112. UA_BrowseRequest bReq;
  113. UA_BrowseRequest_init (&bReq);
  114. bReq.requestedMaxReferencesPerNode = 0;
  115. bReq.nodesToBrowse = UA_BrowseDescription_new ();
  116. bReq.nodesToBrowseSize = 1;
  117. bReq.nodesToBrowse[0].nodeId = UA_NODEID_NUMERIC (0,
  118. UA_NS0ID_OBJECTSFOLDER); /* browse objects folder */
  119. bReq.nodesToBrowse[0].resultMask = UA_BROWSERESULTMASK_ALL; /* return everything */
  120. UA_Client_connect_async (client, "opc.tcp://localhost:4840", onConnect,
  121. NULL);
  122. /*Windows needs time to response*/
  123. UA_sleep_ms(100);
  124. /* What happens if client tries to send request before connected? */
  125. UA_Client_sendAsyncBrowseRequest (client, &bReq, fileBrowsed, &userdata,
  126. &reqId);
  127. UA_DateTime startTime = UA_DateTime_nowMonotonic();
  128. do {
  129. /*TODO: fix memory-related bugs if condition not checked*/
  130. if (UA_Client_getState (client) == UA_CLIENTSTATE_SESSION) {
  131. /* If not connected requests are not sent */
  132. UA_Client_sendAsyncBrowseRequest (client, &bReq, fileBrowsed,
  133. &userdata, &reqId);
  134. }
  135. /* Requests are processed */
  136. UA_BrowseRequest_deleteMembers(&bReq);
  137. UA_Client_run_iterate (client, 0);
  138. UA_sleep_ms(100);
  139. /* Break loop if server cannot be connected within 2s -- prevents build timeout */
  140. if (UA_DateTime_nowMonotonic() - startTime > 2000 * UA_DATETIME_MSEC)
  141. break;
  142. }
  143. while (reqId < 10);
  144. /* Demo: high-level functions */
  145. UA_Int32 value = 0;
  146. UA_Variant myVariant;
  147. UA_Variant_init(&myVariant);
  148. UA_Variant input;
  149. UA_Variant_init (&input);
  150. for (UA_UInt16 i = 0; i < 5; i++) {
  151. if (UA_Client_getState (client) == UA_CLIENTSTATE_SESSION) {
  152. /* writing and reading value 1 to 5 */
  153. UA_Variant_setScalarCopy (&myVariant, &value, &UA_TYPES[UA_TYPES_INT32]);
  154. value++;
  155. UA_Client_writeValueAttribute_async(client,
  156. UA_NODEID_STRING (1, "the.answer"),
  157. &myVariant, attrWritten, NULL,
  158. &reqId);
  159. UA_Variant_deleteMembers (&myVariant);
  160. UA_Client_readValueAttribute_async(client,
  161. UA_NODEID_STRING (1, "the.answer"),
  162. readValueAttributeCallback, NULL,
  163. &reqId);
  164. //TODO: check the existance of the nodes inside these functions (otherwise seg faults)
  165. #ifdef NODES_EXIST
  166. #ifdef UA_ENABLE_METHODCALLS
  167. UA_String stringValue = UA_String_fromChars ("World");
  168. UA_Variant_setScalar (&input, &stringValue, &UA_TYPES[UA_TYPES_STRING]);
  169. UA_Client_call_async(client,
  170. UA_NODEID_NUMERIC (0, UA_NS0ID_OBJECTSFOLDER),
  171. UA_NODEID_NUMERIC (1, 62541), 1, &input,
  172. methodCalled, NULL, &reqId);
  173. UA_String_deleteMembers(&stringValue);
  174. #define pathSize 3
  175. char *paths[pathSize] = { "Server", "ServerStatus", "State" };
  176. UA_UInt32 ids[pathSize] = { UA_NS0ID_ORGANIZES,
  177. UA_NS0ID_HASCOMPONENT, UA_NS0ID_HASCOMPONENT };
  178. UA_Cient_translateBrowsePathsToNodeIds_async (client, paths, ids,
  179. pathSize,
  180. translateCalled, NULL,
  181. &reqId);
  182. #endif /* UA_ENABLE_METHODCALLS */
  183. #endif
  184. /* How often UA_Client_run_iterate is called depends on the number of request sent */
  185. UA_Client_run_iterate(client, 0);
  186. UA_Client_run_iterate(client, 0);
  187. }
  188. }
  189. UA_Client_run_iterate (client, 0);
  190. /* Async disconnect kills unprocessed requests */
  191. // UA_Client_disconnect_async (client, &reqId); //can only be used when connected = true
  192. // UA_Client_run_iterate (client, &timedOut);
  193. UA_Client_disconnect(client);
  194. UA_Client_delete (client);
  195. return (int) UA_STATUSCODE_GOOD;
  196. }