tutorial_client_firstSteps.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. 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.
  5. As a recap, your directory structure should now look like this::
  6. :myApp> rm *.o open62541.*
  7. :myApp> ln -s ../open62541/build/*so ./
  8. :myApp> tree
  9. .
  10. +── include
  11. │   +── logger_stdout.h
  12. │   +── networklayer_tcp.h
  13. │   +── networklayer_udp.h
  14. │   +── open62541.h
  15. │   +── ua_client.h
  16. │   +── ua_config.h
  17. │   +── ua_config.h.in
  18. │   +── ua_connection.h
  19. │   +── ua_log.h
  20. │   +── ua_nodeids.h
  21. │   +── ua_server.h
  22. │   +── ua_statuscodes.h
  23. │   +── ua_transport_generated.h
  24. │   +── ua_types_generated.h
  25. │   +── ua_types.h
  26. +── libopen62541.so -> ../../open62541/build/libopen62541.so
  27. +── myServer
  28. +── myServer.c
  29. 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.
  30. To create a really basic client, navigate back into the myApp folder from the previous tutorial and create a client:
  31. .. code-block:: c
  32. #include <stdio.h>
  33. #include "ua_types.h"
  34. #include "ua_server.h"
  35. #include "logger_stdout.h"
  36. #include "networklayer_tcp.h"
  37. int main(void) {
  38. UA_Client *client = UA_Client_new(UA_ClientConfig_standard, Logger_Stdout_new());
  39. UA_StatusCode retval = UA_Client_connect(client, ClientNetworkLayerTCP_connect, "opc.tcp://localhost:16664");
  40. if(retval != UA_STATUSCODE_GOOD) {
  41. UA_Client_delete(client);
  42. return retval;
  43. }
  44. UA_Client_disconnect(client);
  45. UA_Client_delete(client);
  46. return 0;
  47. }
  48. 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.::
  49. :myApp> gcc -Wl,-rpath=./ -L./ -I ./include -o myClient myClient.c -lopen62541
  50. Asserting success/failure
  51. -------------------------
  52. 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.
  53. Minimalistic introduction to OPC UA nodes and node IDs
  54. ------------------------------------------------------
  55. OPC UA nodespace model defines 9 standard attribute for every node:
  56. +---------------+----------------+
  57. | Type | Name |
  58. +===============+================+
  59. | NodeId | nodeID |
  60. +---------------+----------------+
  61. | NodeClass | nodeClass |
  62. +---------------+----------------+
  63. | QualifiedName | browseName |
  64. +---------------+----------------+
  65. | LocalizedText | displayName |
  66. +---------------+----------------+
  67. | LocalizedText | description |
  68. +---------------+----------------+
  69. | UInt32 | writeMask |
  70. +---------------+----------------+
  71. | UInt32 | userWriteMask |
  72. +---------------+----------------+
  73. | Int32 | referencesSize |
  74. +---------------+----------------+
  75. |ReferenceNode[]| references |
  76. +---------------+----------------+
  77. Furthermore, there are different node types that are stored in NodeClass.
  78. For different classes, nodes have additional properties.
  79. 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.
  80. Let us go on with node IDs. A node ID is a unique identifier in server's context. It is composed of two members:
  81. +-------------+-----------------+---------------------------+
  82. | Type | Name | Notes |
  83. +=============+=================+===========================+
  84. | UInt16 | namespaceIndex | Number of the namespace |
  85. +-------------+-----------------+---------------------------+
  86. | Union | identifier | One idenifier of the |
  87. | | * String | listed types |
  88. | | * Integer | |
  89. | | * GUID | |
  90. | | * ByteString | |
  91. +-------------+-----------------+---------------------------+
  92. 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.
  93. Reading variable's node value
  94. -----------------------------
  95. 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).
  96. Let us extend the client with with an action reading node's value:
  97. .. code-block:: c
  98. #include <stdio.h>
  99. #include "ua_types.h"
  100. #include "ua_server.h"
  101. #include "logger_stdout.h"
  102. #include "networklayer_tcp.h"
  103. int main(void) {
  104. UA_Client *client = UA_Client_new(UA_ClientConfig_standard, Logger_Stdout_new());
  105. UA_StatusCode retval = UA_Client_connect(client, ClientNetworkLayerTCP_connect, "opc.tcp://localhost:16664");
  106. if(retval != UA_STATUSCODE_GOOD) {
  107. UA_Client_delete(client);
  108. return retval;
  109. }
  110. //variable to store data
  111. UA_DateTime raw_date = 0;
  112. UA_ReadRequest rReq;
  113. UA_ReadRequest_init(&rReq);
  114. rReq.nodesToRead = UA_ReadValueId_new();
  115. rReq.nodesToReadSize = 1;
  116. rReq.nodesToRead[0].nodeId = UA_NODEID_NUMERIC(0, 2258);
  117. rReq.nodesToRead[0].attributeId = UA_ATTRIBUTEID_VALUE;
  118. UA_ReadResponse rResp = UA_Client_read(client, &rReq);
  119. if(rResp.responseHeader.serviceResult == UA_STATUSCODE_GOOD &&
  120. rResp.resultsSize > 0 && rResp.results[0].hasValue &&
  121. UA_Variant_isScalar(&rResp.results[0].value) &&
  122. rResp.results[0].value.type == &UA_TYPES[UA_TYPES_DATETIME]) {
  123. raw_date = *(UA_DateTime*)rResp.results[0].value.data;
  124. printf("raw date is: %llu\n", raw_date);
  125. }
  126. UA_ReadRequest_deleteMembers(&rReq);
  127. UA_ReadResponse_deleteMembers(&rResp);
  128. UA_Client_disconnect(client);
  129. UA_Client_delete(client);
  130. return 0;
  131. }
  132. You should see raw time in milliseconds since January 1, 1601 UTC midnight::
  133. :myApp> ./myClient
  134. :myApp> raw date is: 130856974061125520
  135. 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.
  136. As the last step for this tutorial, we are going to convert the raw date value into a well formatted string:
  137. .. code-block:: c
  138. #include <stdio.h>
  139. #include "ua_types.h"
  140. #include "ua_server.h"
  141. #include "logger_stdout.h"
  142. #include "networklayer_tcp.h"
  143. int main(void) {
  144. UA_Client *client = UA_Client_new(UA_ClientConfig_standard, Logger_Stdout_new());
  145. UA_StatusCode retval = UA_Client_connect(client, ClientNetworkLayerTCP_connect, "opc.tcp://localhost:16664");
  146. if(retval != UA_STATUSCODE_GOOD) {
  147. UA_Client_delete(client);
  148. return retval;
  149. }
  150. //variables to store data
  151. UA_DateTime raw_date = 0;
  152. UA_String* string_date = UA_String_new();
  153. UA_ReadRequest rReq;
  154. UA_ReadRequest_init(&rReq);
  155. rReq.nodesToRead = UA_Array_new(&UA_TYPES[UA_TYPES_READVALUEID], 1);
  156. rReq.nodesToReadSize = 1;
  157. rReq.nodesToRead[0].nodeId = UA_NODEID_NUMERIC(0, 2258);
  158. rReq.nodesToRead[0].attributeId = UA_ATTRIBUTEID_VALUE;
  159. UA_ReadResponse rResp = UA_Client_read(client, &rReq);
  160. if(rResp.responseHeader.serviceResult == UA_STATUSCODE_GOOD &&
  161. rResp.resultsSize > 0 && rResp.results[0].hasValue &&
  162. UA_Variant_isScalar(&rResp.results[0].value) &&
  163. rResp.results[0].value.type == &UA_TYPES[UA_TYPES_DATETIME]) {
  164. raw_date = *(UA_DateTime*)rResp.results[0].value.data;
  165. printf("raw date is: %llu\n", raw_date);
  166. UA_DateTime_toString(raw_date, string_date);
  167. printf("string date is: %.*s\n", string_date->length, string_date->data);
  168. }
  169. UA_ReadRequest_deleteMembers(&rReq);
  170. UA_ReadResponse_deleteMembers(&rResp);
  171. UA_String_delete(string_date);
  172. UA_Client_disconnect(client);
  173. UA_Client_delete(client);
  174. return 0;
  175. }
  176. Note that this file can be found as "examples/client_firstSteps.c" in the repository.
  177. Now you should see raw time and a formatted date::
  178. :myApp> ./myClient
  179. :myApp> raw date is: 130856981449041870
  180. string date is: 09/02/2015 20:09:04.904.187.000
  181. Further tasks
  182. -------------
  183. * 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).
  184. * 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".
  185. * 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".