tutorial_client_firstSteps.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. First steps with open62541-client
  2. ===================================
  3. In the previous :doc:`tutorial_server_firstSteps` tutorial, you should have gotten your build environment verified and created a first OPC UA server using the open62541 stack. The created server however doesn't do much yet and there is no client to interact with the server. We are going to remedy that in this tutorial by creating some nodes and variables.
  4. ----------------------
  5. You should already have a basic server from the previous tutorial. open62541 provides both a server- and clientside API, so creating a client is equally as easy as creating a server. We are going to use dynamic linking (libopen62541.so) from now on, because our client and server will share a lot of code. Reusing the shared library will considerably reduce the overhead. To avoid confusion, remove the amalgated open62541.c/h files from your example directory.
  6. As a recap, your directory structure should now look like this::
  7. :myApp> rm *.o open62541.*
  8. :myApp> ln -s ../open62541/build/*so ./
  9. :myApp> tree
  10. .
  11. +── include
  12. │   +── logger_stdout.h
  13. │   +── networklayer_tcp.h
  14. │   +── networklayer_udp.h
  15. │   +── open62541.h
  16. │   +── ua_client.h
  17. │   +── ua_config.h
  18. │   +── ua_config.h.in
  19. │   +── ua_connection.h
  20. │   +── ua_log.h
  21. │   +── ua_nodeids.h
  22. │   +── ua_server.h
  23. │   +── ua_statuscodes.h
  24. │   +── ua_transport_generated.h
  25. │   +── ua_types_generated.h
  26. │   +── ua_types.h
  27. +── libopen62541.so -> ../../open62541/build/libopen62541.so
  28. +── myServer
  29. +── myServer.c
  30. Note that I have linked the library into the folder to spare me the trouble of copying it every time I change/rebuild the stack.
  31. To create a really basic client, navigate back into the myApp folder from the previous tutorial and create a client:
  32. .. code-block:: c
  33. #include <stdio.h>
  34. #include "ua_types.h"
  35. #include "ua_server.h"
  36. #include "logger_stdout.h"
  37. #include "networklayer_tcp.h"
  38. int main(void) {
  39. UA_Client *client = UA_Client_new(UA_ClientConfig_standard, Logger_Stdout_new());
  40. UA_StatusCode retval = UA_Client_connect(client, ClientNetworkLayerTCP_connect, "opc.tcp://localhost:16664");
  41. if(retval != UA_STATUSCODE_GOOD) {
  42. UA_Client_delete(client);
  43. return retval;
  44. }
  45. UA_Client_disconnect(client);
  46. UA_Client_delete(client);
  47. return 0;
  48. }
  49. Let's recompile both server and client - if you feel up to it, you can create a Makefile for this procedure. I will show a final command line compile example and ommit the compilation directives in future examples.::
  50. :myApp> gcc -Wl,-rpath=./ -L./ -I ./include -o myClient myClient.c -lopen62541
  51. Asserting success/failure
  52. -------------------------
  53. Almost all functions of the open62541 API will return a ``UA_StatusCode``, which in the C world would be represented by a ``unsigned int``. OPC UA defines large number of good and bad return codes represented by this number. The constant UA_STATUSCODE_GOOD is defined as 0 in ``include/ua_statuscodes.h`` along with many other return codes. It pays off to check the return code of your function calls, as we already did implicitly in the client.
  54. Minimalistic introduction to OPC UA nodes and node IDs
  55. -----------------------
  56. OPC UA nodespace model defines 9 standard attribute for every node:
  57. +---------------+----------------+
  58. | Type | Name |
  59. +===============+================+
  60. | NodeId | nodeID |
  61. +---------------+----------------+
  62. | NodeClass | nodeClass |
  63. +---------------+----------------+
  64. | QualifiedName | browseName |
  65. +---------------+----------------+
  66. | LocalizedText | displayName |
  67. +---------------+----------------+
  68. | LocalizedText | description |
  69. +---------------+----------------+
  70. | UInt32 | writeMask |
  71. +---------------+----------------+
  72. | UInt32 | userWriteMask |
  73. +---------------+----------------+
  74. | Int32 | referencesSize |
  75. +---------------+----------------+
  76. |ReferenceNode[]| references |
  77. +---------------+----------------+
  78. Furthermore, there are different node types that are stored in NodeClass.
  79. For different classes, nodes have additional properties.
  80. In this tutorial we are interested in one of these types: "Variable". In this case a node will have an additional attribute called "value" which we are going to read.
  81. Let us go on with node IDs. A node ID is a unique identifier in server's context. It is composed of two members:
  82. +-------------+-----------------+---------------------------+
  83. | Type | Name | Notes |
  84. +=============+=================+===========================+
  85. | UInt16 | namespaceIndex | Number of the namespace |
  86. +-------------+-----------------+---------------------------+
  87. | Union | identifier | One idenifier of the |
  88. | | * String | listed types |
  89. | | * Integer | |
  90. | | * GUID | |
  91. | | * ByteString | |
  92. +-------------+-----------------+---------------------------+
  93. The first parameter is the number of node's namespace, the second one may be a numeric, a string or a GUID (Globally Unique ID) identifier.
  94. Reading variable's node value
  95. -----------------------------
  96. In this example we are going to read node (n=0,i=2258), i.e. a node in namespace 0 with a numerical id 2258. This node is present in every server (since it is located in namespace 0) and contains server current time (encoded as UInt64).
  97. Let us extend the client with with an action reading node's value:
  98. .. code-block:: c
  99. #include <stdio.h>
  100. #include "ua_types.h"
  101. #include "ua_server.h"
  102. #include "logger_stdout.h"
  103. #include "networklayer_tcp.h"
  104. int main(void) {
  105. UA_Client *client = UA_Client_new(UA_ClientConfig_standard, Logger_Stdout_new());
  106. UA_StatusCode retval = UA_Client_connect(client, ClientNetworkLayerTCP_connect, "opc.tcp://localhost:16664");
  107. if(retval != UA_STATUSCODE_GOOD) {
  108. UA_Client_delete(client);
  109. return retval;
  110. }
  111. //variable to store data
  112. UA_DateTime raw_date = 0;
  113. UA_ReadRequest rReq;
  114. UA_ReadRequest_init(&rReq);
  115. rReq.nodesToRead = UA_ReadValueId_new();
  116. rReq.nodesToReadSize = 1;
  117. rReq.nodesToRead[0].nodeId = UA_NODEID_NUMERIC(0, 2258);
  118. rReq.nodesToRead[0].attributeId = UA_ATTRIBUTEID_VALUE;
  119. UA_ReadResponse rResp = UA_Client_read(client, &rReq);
  120. if(rResp.responseHeader.serviceResult == UA_STATUSCODE_GOOD &&
  121. rResp.resultsSize > 0 && rResp.results[0].hasValue &&
  122. UA_Variant_isScalar(&rResp.results[0].value) &&
  123. rResp.results[0].value.type == &UA_TYPES[UA_TYPES_DATETIME]) {
  124. raw_date = *(UA_DateTime*)rResp.results[0].value.data;
  125. printf("raw date is: %llu\n", raw_date);
  126. }
  127. UA_ReadRequest_deleteMembers(&rReq);
  128. UA_ReadResponse_deleteMembers(&rResp);
  129. UA_Client_disconnect(client);
  130. UA_Client_delete(client);
  131. return 0;
  132. }
  133. You should see raw time in milliseconds since January 1, 1601 UTC midnight::
  134. :myApp> ./myClient
  135. :myApp> raw date is: 130856974061125520
  136. Firstly we constructed a read request "rReq", it contains 1 node's attribute we want to query for. The attribute is filled with the numeric id "UA_NODEID_NUMERIC(0, 2258)" and the attribute we are reading "UA_ATTRIBUTEID_VALUE". After the read request was sent, we can find the actual read value in the read response.
  137. As the last step for this tutorial, we are going to convert the raw date value into a well formatted string:
  138. .. code-block:: c
  139. #include <stdio.h>
  140. #include "ua_types.h"
  141. #include "ua_server.h"
  142. #include "logger_stdout.h"
  143. #include "networklayer_tcp.h"
  144. int main(void) {
  145. UA_Client *client = UA_Client_new(UA_ClientConfig_standard, Logger_Stdout_new());
  146. UA_StatusCode retval = UA_Client_connect(client, ClientNetworkLayerTCP_connect, "opc.tcp://localhost:16664");
  147. if(retval != UA_STATUSCODE_GOOD) {
  148. UA_Client_delete(client);
  149. return retval;
  150. }
  151. //variables to store data
  152. UA_DateTime raw_date = 0;
  153. UA_String* string_date = UA_String_new();
  154. UA_ReadRequest rReq;
  155. UA_ReadRequest_init(&rReq);
  156. rReq.nodesToRead = UA_Array_new(&UA_TYPES[UA_TYPES_READVALUEID], 1);
  157. rReq.nodesToReadSize = 1;
  158. rReq.nodesToRead[0].nodeId = UA_NODEID_NUMERIC(0, 2258);
  159. rReq.nodesToRead[0].attributeId = UA_ATTRIBUTEID_VALUE;
  160. UA_ReadResponse rResp = UA_Client_read(client, &rReq);
  161. if(rResp.responseHeader.serviceResult == UA_STATUSCODE_GOOD &&
  162. rResp.resultsSize > 0 && rResp.results[0].hasValue &&
  163. UA_Variant_isScalar(&rResp.results[0].value) &&
  164. rResp.results[0].value.type == &UA_TYPES[UA_TYPES_DATETIME]) {
  165. raw_date = *(UA_DateTime*)rResp.results[0].value.data;
  166. printf("raw date is: %llu\n", raw_date);
  167. UA_DateTime_toString(raw_date, string_date);
  168. printf("string date is: %.*s\n", string_date->length, string_date->data);
  169. }
  170. UA_ReadRequest_deleteMembers(&rReq);
  171. UA_ReadResponse_deleteMembers(&rResp);
  172. UA_String_delete(string_date);
  173. UA_Client_disconnect(client);
  174. UA_Client_delete(client);
  175. return 0;
  176. }
  177. Note that this file can be found as "examples/client_firstSteps.c" in the repository.
  178. Now you should see raw time and a formatted date::
  179. :myApp> ./myClient
  180. :myApp> raw date is: 130856981449041870
  181. string date is: 09/02/2015 20:09:04.904.187.000
  182. Further tasks
  183. -------------
  184. * Try to connect to some other OPC UA server by changing "opc.tcp://localhost:16664" to an appropriate address (remember that the queried node is contained in any OPC UA server).
  185. * Display the value of the variable node (ns=1,i="the.answer") containing an "Int32" from the example server (which is built in :doc:`tutorial_server_firstSteps`). Note that the identifier of this node is a string type: use "UA_NODEID_STRING_ALLOC". The answer can be found in "examples/exampleClient.c".
  186. * Try to set the value of the variable node (ns=1,i="the.answer") containing an "Int32" from the example server (which is built in :doc:`tutorial_server_firstSteps`) using "UA_Client_write" function. The example server needs some more modifications, i.e., changing request types. The answer can be found in "examples/exampleClient.c".