server_mainloop.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  3. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information.
  4. */
  5. #define _BSD_SOURCE
  6. #include <signal.h>
  7. #include <unistd.h>
  8. #ifdef UA_NO_AMALGAMATION
  9. # include "ua_types.h"
  10. # include "ua_server.h"
  11. # include "logger_stdout.h"
  12. # include "networklayer_tcp.h"
  13. #else
  14. # include "open62541.h"
  15. #endif
  16. UA_Boolean running = true;
  17. UA_Logger logger = Logger_Stdout;
  18. static void stopHandler(int sign) {
  19. UA_LOG_INFO(logger, UA_LOGCATEGORY_SERVER, "received ctrl-c");
  20. running = false;
  21. }
  22. /* In this example, we integrate the server into an external "mainloop". This
  23. can be for example the event-loop used in GUI toolkits, such as Qt or GTK. */
  24. int main(int argc, char** argv) {
  25. signal(SIGINT, stopHandler); /* catches ctrl-c */
  26. UA_ServerConfig config = UA_ServerConfig_standard;
  27. UA_ServerNetworkLayer nl = UA_ServerNetworkLayerTCP(UA_ConnectionConfig_standard, 16664);
  28. config.logger = Logger_Stdout;
  29. config.networkLayers = &nl;
  30. config.networkLayersSize = 1;
  31. UA_Server *server = UA_Server_new(config);
  32. UA_StatusCode retval = UA_Server_run_startup(server);
  33. if(retval != UA_STATUSCODE_GOOD)
  34. goto cleanup;
  35. /* Should the server networklayer block (with a timeout) until a message
  36. arrives or should it return immediately? */
  37. UA_Boolean waitInternal = false;
  38. while(running) {
  39. /* timeout is the maximum possible delay (in millisec) until the next
  40. _iterate call. Otherwise, the server might miss an internal timeout
  41. or cannot react to messages with the promised responsiveness. */
  42. UA_UInt16 timeout = UA_Server_run_iterate(server, waitInternal);
  43. /* now we can use the max timeout to do something else */
  44. usleep((__useconds_t)(timeout * 1000));
  45. }
  46. retval = UA_Server_run_shutdown(server);
  47. cleanup:
  48. UA_Server_delete(server);
  49. nl.deleteMembers(&nl);
  50. return (int)retval;
  51. }