tutorial_server_firstSteps.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. First steps with open62541-server
  2. =================================
  3. This tutorial will attempt to guide you through your first steps with open62541. It offers a bit of a more "hands on" approach to learning how to use this stack by talking you through building several small example OPC UA server/client applications.
  4. Before we start: a word of warning; open62541 is under active development. New functionality is added and stale bits overhauled all the time in order to respond to our communities feedback. Please understand that if you come back here next week, some things might have changed... eeem... improved.
  5. Prerequisites
  6. -------------
  7. This series of tutorials assumes that you are familiar both with coding in C, the OPC Unified Architecture namespace concepts, its datatypes and services. This tutorial will not teach you OPC UA.
  8. For running these tutorials, you will require cmake, python (<= 2.7) and a compiler (MS Visual Studio 2015, gcc, clang and mingw32 are known to be working). Note that if you are using MSVS, the 2015 version is manditory. open62541 makes extensive use of C99, which is not supported by earlier Versions of MSVS. It will also be very helpfull to install a OPC UA Client with a graphical frontend, such as UAExpert by Unified Automation, that will enable you to examine the namespace of your server.
  9. For now, this tutorial will assume that you are using an up-to-date Linux or BSD distribution to run these examples.
  10. Before we can get started you will require the stack. You may either clone the current master or download a ZIP/TGZ archive from github. Let's assume that you want to clone the github repository. Open a shell, navigate to a folder of your choice and clone the repository::
  11. :> git clone https://github.com/acplt/open62541
  12. Cloning into './open62541'...
  13. remote: Counting objects: 14443, done.
  14. remote: Compressing objects: 100% (148/148), done.
  15. remote: Total 14443 (delta 106), reused 0 (delta 0), pack-reused 14293
  16. Receiving objects: 100% (14443/14443), 7.18 MiB | 654.00 KiB/s, done.
  17. Resolving deltas: 100% (10894/10894), done.
  18. Checking connectivity... done.
  19. :>
  20. Then create a build directory and read the next section.::
  21. :> cd open62541
  22. :open62541> mkdir build
  23. :open62541/build> cd build
  24. Note that the shell used here was BASH. You might have to adapt some of the following examples for your shell if you prefer tcsh or csh.
  25. Verifying your build environment
  26. --------------------------------
  27. Let's proceed with the default stack build, which will give you an impression of what you should see if your building process is successfull::
  28. :open62541/build> cmake ../
  29. -- The C compiler identification is GNU 4.8.3
  30. -- Check for working C compiler: /usr/bin/cc
  31. -- Check for working C compiler: /usr/bin/cc -- works
  32. -- Detecting C compiler ABI info
  33. -- Detecting C compiler ABI info - done
  34. -- Found PythonInterp: /usr/bin/python (found version "2.7.8")
  35. -- Found Git: /usr/bin/git (found version "2.1.4")
  36. -- Git version: v0.1.0-RC4-365-g35331dc
  37. -- CMAKE_BUILD_TYPE not given; setting to 'RelWithDebInfo'.
  38. -- Configuring done
  39. -- Generating done
  40. -- Build files have been written to: /home/ichrispa/work/svn/working_copies/tmpopen/build
  41. :open62541/build> make
  42. [ 3%] Generating src_generated/ua_nodeids.h
  43. [ 7%] Generating src_generated/ua_types_generated.c, src_generated/ua_types_generated.h
  44. [ 11%] Generating src_generated/ua_transport_generated.c, src_generated/ua_transport_generated.h
  45. Scanning dependencies of target open62541-object
  46. [ 14%] Building C object CMakeFiles/open62541-object.dir/src/ua_types.c.o
  47. [ 18%] Building C object CMakeFiles/open62541-object.dir/src/ua_types_encoding_binary.c.o
  48. [ 22%] Building C object CMakeFiles/open62541-object.dir/src_generated/ua_types_generated.c.o
  49. [ 25%] Building C object CMakeFiles/open62541-object.dir/src_generated/ua_transport_generated.c.o
  50. [ 29%] Building C object CMakeFiles/open62541-object.dir/src/ua_connection.c.o
  51. [ 33%] Building C object CMakeFiles/open62541-object.dir/src/ua_securechannel.c.o
  52. [ 37%] Building C object CMakeFiles/open62541-object.dir/src/ua_session.c.o
  53. [ 40%] Building C object CMakeFiles/open62541-object.dir/src/server/ua_server.c.o
  54. [ 44%] Building C object CMakeFiles/open62541-object.dir/src/server/ua_server_addressspace.c.o
  55. [ 48%] Building C object CMakeFiles/open62541-object.dir/src/server/ua_server_binary.c.o
  56. [ 51%] Building C object CMakeFiles/open62541-object.dir/src/server/ua_nodes.c.o
  57. [ 55%] Building C object CMakeFiles/open62541-object.dir/src/server/ua_server_worker.c.o
  58. [ 59%] Building C object CMakeFiles/open62541-object.dir/src/server/ua_securechannel_manager.c.o
  59. [ 62%] Building C object CMakeFiles/open62541-object.dir/src/server/ua_session_manager.c.o
  60. [ 66%] Building C object CMakeFiles/open62541-object.dir/src/server/ua_services_discovery.c.o
  61. [ 70%] Building C object CMakeFiles/open62541-object.dir/src/server/ua_services_securechannel.c.o
  62. [ 74%] Building C object CMakeFiles/open62541-object.dir/src/server/ua_services_session.c.o
  63. [ 77%] Building C object CMakeFiles/open62541-object.dir/src/server/ua_services_attribute.c.o
  64. [ 81%] Building C object CMakeFiles/open62541-object.dir/src/server/ua_services_nodemanagement.c.o
  65. [ 85%] Building C object CMakeFiles/open62541-object.dir/src/server/ua_services_view.c.o
  66. [ 88%] Building C object CMakeFiles/open62541-object.dir/src/client/ua_client.c.o
  67. [ 92%] Building C object CMakeFiles/open62541-object.dir/examples/networklayer_tcp.c.o
  68. [ 96%] Building C object CMakeFiles/open62541-object.dir/examples/logger_stdout.c.o
  69. [100%] Building C object CMakeFiles/open62541-object.dir/src/server/ua_nodestore.c.o
  70. [100%] Built target open62541-object
  71. Scanning dependencies of target open62541
  72. Linking C shared library libopen62541.so
  73. [100%] Built target open62541
  74. :open62541/build>
  75. The line where ``cmake ../`` is executed tells cmake to prepare the build process in the current subdirectory. ``make`` then executes the generated Makefiles which build the stack. At this point, a shared library named *libopen62541.so* should have been generated in the build folder. By using this library and the header files contained in the ``open62541/include`` folder you can enable your applications to use the open62541 OPC UA server and client stack.
  76. Creating your first server
  77. --------------------------
  78. Let's build a very rudimentary server. Create a separate folder for your application and copy the necessary source files into an a subfolder named ``include``. Don't forget to also copy the shared library. Then create a new C sourcefile called ``myServer.c``. If you choose to use a shell, the whole process should look like this::
  79. :open62541/build> cd ../../
  80. :> mkdir myServerApp
  81. :> cd myServerApp
  82. :myServerApp> mkdir include
  83. :myServerApp> cp ../open62541/include/* ./include
  84. :myServerApp> cp ../open62541/examples/*.h ./include
  85. :myServerApp> cp ../open62541/build/src_generated/*.h ./include
  86. :myServerApp> cp ../open62541/build/*.so .
  87. :myServerApp> tree
  88. .
  89. |-- include
  90. | |-- logger_stdout.h
  91. | |-- networklayer_tcp.h
  92. | |-- networklayer_udp.h
  93. | |-- ua_client.h
  94. | |-- ua_config.h
  95. | |-- ua_config.h.in
  96. | |-- ua_connection.h
  97. | |-- ua_log.h
  98. | |-- ua_nodeids.h
  99. | |-- ua_server.h
  100. | |-- ua_statuscodes.h
  101. | |-- ua_types_generated.h
  102. | `-- ua_types.h
  103. |-- libopen62541.so
  104. `-- myServer.c
  105. :myServerApp> touch myServer.c
  106. Open myServer.c and write/paste your minimal server application:
  107. .. code-block:: c
  108. #include <stdio.h>
  109. # include "ua_types.h"
  110. # include "ua_server.h"
  111. # include "logger_stdout.h"
  112. # include "networklayer_tcp.h"
  113. UA_Boolean running;
  114. int main(void) {
  115. UA_Server *server = UA_Server_new(UA_ServerConfig_standard);
  116. UA_Server_addNetworkLayer(server, ServerNetworkLayerTCP_new(UA_ConnectionConfig_standard, 16664));
  117. running = UA_TRUE;
  118. UA_Server_run(server, 1, &running);
  119. UA_Server_delete(server);
  120. return 0;
  121. }
  122. This is all that is needed to start your OPC UA Server. Compile the the server with GCC using the following command::
  123. :myServerApp> gcc -Wl,-rpath,`pwd` -I ./include -L ./ ./myServer.c -o myServer -lopen62541
  124. Some notes: You are using a dynamically linked library (libopen62541.so), which needs to be locates in your dynamic linkers search path. Unless you copy libopen62541.so into a common folder like /lib or /usr/lib, the linker will fail to find the library and complain (i.e. not run the application). ``-Wl,-rpath,`pwd``` adds your present working directory to the relative searchpaths of the linker when executing the binary (you can also use ``-Wl,-rpath,.`` if the binary and the library are always in the same directory).
  125. Now execute the server::
  126. :myServerApp> ./myServer
  127. You have now compiled and started your first OPC UA Server. Though quite unspectacular and only terminatable with ``CTRL+C`` (SIGTERM) at the moment, you can already launch it and browse around with UA Expert. The Server will be listening on localhost:16664 - go ahead and give it a try.
  128. We will also make a slight change to our server: We want it to exit cleanly when pressing ``CTRL+C``. We will add signal handler for SIGINT and SIGTERM to accomplish that to the server:
  129. .. code-block:: c
  130. #include <stdio.h>
  131. #include <signal.h>
  132. #include "ua_types.h"
  133. #include "ua_server.h"
  134. #include "logger_stdout.h"
  135. #include "networklayer_tcp.h"
  136. UA_Boolean running;
  137. UA_Logger logger;
  138. static void stopHandler(int signal) {
  139. running = UA_FALSE;
  140. }
  141. int main(void) {
  142. signal(SIGINT, stopHandler);
  143. signal(SIGTERM, stopHandler);
  144. UA_Server *server = UA_Server_new(UA_ServerConfig_standard);
  145. logger = Logger_Stdout_new();
  146. UA_Server_setLogger(server, logger);
  147. UA_Server_addNetworkLayer(server, ServerNetworkLayerTCP_new(UA_ConnectionConfig_standard, 16664));
  148. running = UA_TRUE;
  149. UA_Server_run(server, 1, &running);
  150. UA_Server_delete(server);
  151. printf("Terminated\n");
  152. return 0;
  153. }
  154. Note that this file can be found as "examples/server_firstSteps.c" in the repository.
  155. And then of course, recompile it::
  156. :myApp> gcc -Wl,-rpath=./ -L./ -I ./include -o myServer myServer.c -lopen62541
  157. You can now start and background the server, run the client, and then terminate the server like so::
  158. :myApp> ./myServer &
  159. [xx/yy/zz aa:bb:cc.dd.ee] info/communication Listening on opc.tcp://localhost:16664
  160. [1] 2114
  161. :myApp> ./myClient && killall myServer
  162. Terminated
  163. [1]+ Done ./myServer
  164. :myApp>
  165. Notice how the server received the SIGTERM signal from kill and exited cleany? We also used the return value of our client by inserting the ``&&``, so kill is only called after a clean client exit (``return 0``).
  166. Introduction to Configuration options (Amalgamation)
  167. ----------------------------------------------------
  168. If you browsed through your new servers namespace with UAExpert or some other client, you might have noticed that the server can't do a lot. Indeed, even Namespace 0 appears to be mostly missing.
  169. open62541 is a highly configurable stack that lets you turn several features on or off depending on your needs. This allows you to create anything from a very minimal and ressource saving OPC UA client to a full-fledged server. Picking which features you want is part of the cmake building process. CMake will handle the configuration of Makefiles, definition of precompiler variables and calling of auxilary scripts for you.If the building process above has failed on your system, please make sure that you have all the prerequisites installed and configured properly.
  170. A detailed list of all configuration options is given in the documentation of open62541. This tutorial will introduce you to some of these options one by one in due course, but I will mention a couple of non-feature related options at this point to give readers a heads-up on the advantages and consequences of using them.
  171. **Warning:** If you change cmake options, always make sure that you have a clean build directory first (unless you know what you are doing). CMake will *not* reliably detect changes to non-source files, such as source files for scripts and generators. Always run ``make clean`` between builds, and remove the ``CMakeCache.txt`` file from your build directory to make super-double-extra-sure that your build is clean before executing cmake.
  172. **ENABLE_AMALGAMATION**
  173. This one might appear quite mysterious at first... this option will enable a python script (tools/amalgate.py) that will merge all headers of open62541 into a single header and c files into a single c file. Why? The most obvious answer is that you might not want to use a shared library in your project, but compile everything into your own binary. Let's give that a try... get back into the build folder ``make clean`` and then try this::
  174. :open62541/build> make clean
  175. :open62541/build> cmake -DENABLE_AMALGAMATION=On ../
  176. :open62541/build> make
  177. [ 5%] Generating open62541.h
  178. Starting amalgamating file /open62541/build/open62541.h
  179. Integrating file '/open62541/build/src_generated/ua_config.h'...done.
  180. (...)
  181. The size of /open62541/build/open62541.h is 243350 Bytes.
  182. [ 11%] Generating open62541.c
  183. Starting amalgamating file /open62541/build/open62541.c
  184. Integrating file '/open62541/src/ua_util.h'...done.
  185. (...)
  186. Integrating file '/open62541/src/server/ua_nodestore.c'...done.
  187. The size of /open62541/build/open62541.c is 694855 Bytes.
  188. [ 27%] Built target amalgamation
  189. Scanning dependencies of target open62541-object
  190. [ 33%] Building C object CMakeFiles/open62541-object.dir/open62541.c.o
  191. [ 61%] Built target open62541-object
  192. Scanning dependencies of target open62541
  193. Linking C shared library libopen62541.so
  194. :open62541/build>
  195. Switch back to your MyServerApp directory and recompile your binary, this time embedding all open62541 functionality in one executable::
  196. :open62541/build> cd ../../myServerApp
  197. :open62541/build> cp ../open62541/build/open62541.* .
  198. :myServerApp> gcc -std=c99 -I ./ -c ./open62541.c
  199. :myServerApp> gcc -std=c99 -I ./include -o myServer myServer.c open62541.o
  200. :myServerApp> ./myServer
  201. You can now start the server and browse around as before. As you might have noticed, no shared library is required anymore. That makes the application more portable or runnable on systems without dynamic linking support and allows you to use functions that are not exported by the library (which propably means we haven't documented them as thouroughly...); on the other hand the application is also much bigger, so if you intend to also use a client with open62541, you might be inclined to overthink amalgamation.
  202. The next step is to simplify the header dependencies. Instead of picking header files one-by-one, we can use the copied amalgamated header including all the public headers dependencies.
  203. Open myServer.c and simplify it to:
  204. .. code-block:: c
  205. #include <stdio.h>
  206. #include "open62541.h"
  207. UA_Boolean running;
  208. int main(void) {
  209. UA_Server *server = UA_Server_new(UA_ServerConfig_standard);
  210. UA_Server_addNetworkLayer(server, ServerNetworkLayerTCP_new(UA_ConnectionConfig_standard, 16664));
  211. running = UA_TRUE;
  212. UA_Server_run(server, 1, &running);
  213. UA_Server_delete(server);
  214. return 0;
  215. }
  216. It can now also be compiled without the include directory, i.e., ::
  217. :myServerApp> gcc -std=c99 myServer.c open62541.c -o myServer
  218. :myServerApp> ./myServer
  219. Please note that at times the amalgamation script has... well, bugs. It might include files in the wrong order or include features even though the feature is turned off. Please report problems with amalgamation so we can improve it.
  220. **BUILD_EXAMPLECLIENT** and **BUILD_EXAMPLESERVER**
  221. If you build your stack with the above two options, you will enable the example server/client applications to be built. You can review their sources under ``examples/server.c`` and ``example/client.c``. These provide a neat reference for just about any features of open62541, as most of them are included in these examples by us (the developers) for testing and demonstration purposes.
  222. Unfortunately, these examples include just about everything the stack can do... which makes them rather bad examples for newcomers seeking an easy introduction. They are also dynamically configured by the CMake options, so they might be a bit more difficult to read. Non the less you can find any of the concepts demonstrated here in these examples as well and you can build them like so (and this is what you will see when you run them)::
  223. :open62541/build> make clean
  224. :open62541/build> cmake -BUILD_EXAMPLECLIENT=On -BUILD_EXAMPLESERVER=On ../
  225. :open62541/build> make
  226. :open62541/build> ./server &
  227. [07/28/2015 21:42:07.977.352] info/communication Listening on opc.tcp://Cassandra:16664
  228. :open62541/build> ./client
  229. Browsing nodes in objects folder:
  230. NAMESPACE NODEID BROWSE NAME DISPLAY NAME
  231. 0 61 FolderType FolderType
  232. 0 2253 Server Server
  233. 1 96 current time current time
  234. 1 the.answer the answer the answer
  235. 1 50000 Demo Demo
  236. 1 62541 ping ping
  237. Create subscription succeeded, id 1187379785
  238. Monitoring 'the.answer', id 1187379785
  239. The Answer has changed!
  240. Reading the value of node (1, "the.answer"):
  241. the value is: 42
  242. Writing a value of node (1, "the.answer"):
  243. the new value is: 43
  244. The Answer has changed!
  245. Subscription removed
  246. Method call was unsuccessfull, and 80750000 returned values available.
  247. Created 'NewReference' with numeric NodeID 12133
  248. Created 'NewObjectType' with numeric NodeID 12134
  249. Created 'NewObject' with numeric NodeID 176
  250. Created 'NewVariable' with numeric NodeID 177
  251. :open62541/build> fg
  252. ./server
  253. [07/28/2015 21:43:21.815.890] info/server Received Ctrl-C
  254. :open62541/build>
  255. **BUILD_DOCUMENTATION**
  256. If you have doxygen installed, this will produce a reference under ``/doc`` that documents functions that the shared library advertises (i.e. are available to users). We are doing our best to keep the source well commented.
  257. **CMAKE_BUILD_TYPE**
  258. There are several ways of building open62541, and all have their advantages and disadvanted. The build type mainly affects optimization flags (the more release, the heavier the optimization) and the inclusion of debugging symbols. The following are available:
  259. * Debug: Will only include debugging symbols (-g)
  260. * Release: Will run heavy optimization and *not* include debugging info (-O3 -DNBEBUG)
  261. * RelWithDebInfo: Will run mediocre optimization and include debugging symbols (-O2 -g)
  262. * MinSizeRel: Will run string optimziation and include no debugging info (-Os -DNBEBUG)
  263. **WARNING:** If you are generating namespaces (please read the following sections), the compiler will try to optimize a function with 32k lines of generated code. This will propably result in a compilation run of >60Minutes (79min; 8-Core AMD FX; 16GB RAM; 64Bit Linux). Please pick build type ``Debug`` if you intend to compile large namespaces.
  264. Conclusion
  265. ----------
  266. In this first tutorial, you hopefully have compiled your first OPC UA Server with open62541. By going through that process, you now have a good impression of what steps building the stack involves and how you can use it. You were also introduced to several build options that affect the overall behavior of the compilation process. In the following tutorials, you will be shown how to build a client application and manipulate some nodes and variables.