tutorial_server_firstSteps.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 myApp
  81. :> cd myApp
  82. :myApp> mkdir include
  83. :myApp> cp ../open62541/include/* ./include
  84. :myApp> cp ../open62541/plugins/*.h ./include
  85. :myApp> cp ../open62541/build/src_generated/*.h ./include
  86. :myApp> cp ../open62541/build/*.so .
  87. :myApp> tree
  88. .
  89. ├── include
  90. │   ├── logger_stdout.h
  91. │   ├── networklayer_tcp.h
  92. │   ├── networklayer_udp.h
  93. │   ├── ua_client.h
  94. │   ├── ua_client_highlevel.h
  95. │   ├── ua_config.h
  96. │   ├── ua_config.h.in
  97. │   ├── ua_connection.h
  98. │   ├── ua_job.h
  99. │   ├── ua_log.h
  100. │   ├── ua_nodeids.h
  101. │   ├── ua_server_external_ns.h
  102. │   ├── ua_server.h
  103. │   ├── ua_constants.h
  104. │   ├── ua_transport_generated_encoding_binary.h
  105. │   ├── ua_transport_generated.h
  106. │   ├── ua_types_generated_encoding_binary.h
  107. │   ├── ua_types_generated.h
  108. │   └── ua_types.h
  109. ├── libopen62541.so
  110. └── myServer.c
  111. :myApp> touch myServer.c
  112. Open myServer.c and write/paste your minimal server application:
  113. .. code-block:: c
  114. #include <stdio.h>
  115. # include "ua_types.h"
  116. # include "ua_server.h"
  117. # include "logger_stdout.h"
  118. # include "networklayer_tcp.h"
  119. UA_Boolean running;
  120. UA_Logger logger = Logger_Stdout;
  121. int main(void) {
  122. UA_ServerConfig config = UA_ServerConfig_standard;
  123. UA_ServerNetworkLayer nl = UA_ServerNetworkLayerTCP(UA_ConnectionConfig_standard, 16664, logger);
  124. config.logger = Logger_Stdout;
  125. config.networkLayers = &nl;
  126. config.networkLayersSize = 1;
  127. UA_Server *server = UA_Server_new(config);
  128. running = true;
  129. UA_Server_run(server, &running);
  130. UA_Server_delete(server);
  131. return 0;
  132. }
  133. This is all that is needed to start your OPC UA Server. Compile the the server with GCC using the following command::
  134. :myApp> gcc -Wl,-rpath,`pwd` -I ./include -L ./ ./myServer.c -o myServer -lopen62541
  135. Some notes: You are using a dynamically linked library (libopen62541.so), which needs to be located 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).
  136. Now execute the server::
  137. :myApp> ./myServer
  138. 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.
  139. 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:
  140. .. code-block:: c
  141. #include <stdio.h>
  142. #include <signal.h>
  143. #include "ua_types.h"
  144. #include "ua_server.h"
  145. #include "logger_stdout.h"
  146. #include "networklayer_tcp.h"
  147. UA_Boolean running = true;
  148. static void stopHandler(int signal) {
  149. running = false;
  150. }
  151. int main(void) {
  152. signal(SIGINT, stopHandler);
  153. signal(SIGTERM, stopHandler);
  154. UA_ServerConfig config = UA_ServerConfig_standard;
  155. UA_ServerNetworkLayer nl = UA_ServerNetworkLayerTCP(UA_ConnectionConfig_standard, 16664, Logger_Stdout);
  156. config.logger = Logger_Stdout;
  157. config.networkLayers = &nl;
  158. config.networkLayersSize = 1;
  159. UA_Server *server = UA_Server_new(config);
  160. UA_StatusCode retval = UA_Server_run(server, &running);
  161. UA_Server_delete(server);
  162. nl.deleteMembers(&nl);
  163. return retval;
  164. }
  165. Note that this file can be found as "examples/server_firstSteps.c" in the repository.
  166. And then of course, recompile it::
  167. :myApp> gcc -Wl,-rpath=./ -L./ -I ./include -o myServer myServer.c -lopen62541
  168. You can now start and background the server, run the client, and then terminate the server like so::
  169. :myApp> ./myServer &
  170. [xx/yy/zz aa:bb:cc.dd.ee] info/communication Listening on opc.tcp://localhost:16664
  171. [1] 2114
  172. :myApp> ./myClient && killall myServer
  173. Terminated
  174. [1]+ Done ./myServer
  175. :myApp>
  176. 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``).
  177. Introduction to Configuration options (Amalgamation)
  178. ----------------------------------------------------
  179. 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.
  180. 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.
  181. 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.
  182. **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.
  183. **UA_ENABLE_AMALGAMATION**
  184. 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::
  185. :open62541/build> make clean
  186. :open62541/build> cmake -DUA_ENABLE_AMALGAMATION=On ../
  187. :open62541/build> make
  188. [ 5%] Generating open62541.h
  189. Starting amalgamating file /open62541/build/open62541.h
  190. Integrating file '/open62541/build/src_generated/ua_config.h'...done.
  191. (...)
  192. The size of /open62541/build/open62541.h is 243350 Bytes.
  193. [ 11%] Generating open62541.c
  194. Starting amalgamating file /open62541/build/open62541.c
  195. Integrating file '/open62541/src/ua_util.h'...done.
  196. (...)
  197. Integrating file '/open62541/src/server/ua_nodestore.c'...done.
  198. The size of /open62541/build/open62541.c is 694855 Bytes.
  199. [ 27%] Built target amalgamation
  200. Scanning dependencies of target open62541-object
  201. [ 33%] Building C object CMakeFiles/open62541-object.dir/open62541.c.o
  202. [ 61%] Built target open62541-object
  203. Scanning dependencies of target open62541
  204. Linking C shared library libopen62541.so
  205. :open62541/build>
  206. Switch back to your myApp directory and recompile your binary, this time embedding all open62541 functionality in one executable::
  207. :open62541/build> cd ../../myApp
  208. :open62541/build> cp ../open62541/build/open62541.* .
  209. :myApp> gcc -std=c99 -I ./ -c ./open62541.c
  210. :myApp> gcc -std=c99 -I ./include -o myServer myServer.c open62541.o
  211. :myApp> ./myServer
  212. 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.
  213. 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.
  214. Open myServer.c and simplify it to:
  215. .. code-block:: c
  216. #include <stdio.h>
  217. #include "open62541.h"
  218. UA_Boolean running;
  219. UA_Logger logger = Logger_Stdout;
  220. int main(void) {
  221. UA_ServerConfig config = UA_ServerConfig_standard;
  222. UA_ServerNetworkLayer nl = UA_ServerNetworkLayerTCP(UA_ConnectionConfig_standard, 16664, logger);
  223. config.logger = Logger_Stdout;
  224. config.networkLayers = &nl;
  225. config.networkLayersSize = 1;
  226. UA_Server *server = UA_Server_new(config);
  227. running = true;
  228. UA_Server_run(server, &running);
  229. UA_Server_delete(server);
  230. return 0;
  231. }
  232. It can now also be compiled without the include directory, i.e., ::
  233. :myApp> gcc -std=c99 myServer.c open62541.c -o myServer
  234. :myApp> ./myServer
  235. 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.
  236. **UA_BUILD_EXAMPLECLIENT** and **UA_BUILD_EXAMPLESERVER**
  237. 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.
  238. 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. Nontheless 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)::
  239. :open62541/build> make clean
  240. :open62541/build> cmake -DUA_BUILD_EXAMPLECLIENT=On -DUA_BUILD_EXAMPLESERVER=On ../
  241. :open62541/build> make
  242. :open62541/build> ./server &
  243. [07/28/2015 21:42:07.977.352] info/communication Listening on opc.tcp://Cassandra:16664
  244. :open62541/build> ./client
  245. Browsing nodes in objects folder:
  246. NAMESPACE NODEID BROWSE NAME DISPLAY NAME
  247. 0 61 FolderType FolderType
  248. 0 2253 Server Server
  249. 1 96 current time current time
  250. 1 the.answer the answer the answer
  251. 1 50000 Demo Demo
  252. 1 62541 ping ping
  253. Create subscription succeeded, id 1187379785
  254. Monitoring 'the.answer', id 1187379785
  255. The Answer has changed!
  256. Reading the value of node (1, "the.answer"):
  257. the value is: 42
  258. Writing a value of node (1, "the.answer"):
  259. the new value is: 43
  260. The Answer has changed!
  261. Subscription removed
  262. Method call was unsuccessfull, and 80750000 returned values available.
  263. Created 'NewReference' with numeric NodeID 12133
  264. Created 'NewObjectType' with numeric NodeID 12134
  265. Created 'NewObject' with numeric NodeID 176
  266. Created 'NewVariable' with numeric NodeID 177
  267. :open62541/build> fg
  268. ./server
  269. [07/28/2015 21:43:21.815.890] info/server Received Ctrl-C
  270. :open62541/build>
  271. **UA_BUILD_DOCUMENTATION**
  272. 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.
  273. **CMAKE_BUILD_TYPE**
  274. 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:
  275. * Debug: Will only include debugging symbols (-g)
  276. * Release: Will run heavy optimization and *not* include debugging info (-O3 -DNBEBUG)
  277. * RelWithDebInfo: Will run mediocre optimization and include debugging symbols (-O2 -g)
  278. * MinSizeRel: Will run string optimziation and include no debugging info (-Os -DNBEBUG)
  279. **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.
  280. Conclusion
  281. ----------
  282. 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.