tutorial_client_firstSteps.rst 11 KB

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