client_connectivitycheck_loop.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  2. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
  3. /* Enable POSIX features */
  4. #if !defined(_XOPEN_SOURCE) && !defined(_WRS_KERNEL)
  5. # define _XOPEN_SOURCE 600
  6. #endif
  7. #ifndef _DEFAULT_SOURCE
  8. # define _DEFAULT_SOURCE
  9. #endif
  10. /* On older systems we need to define _BSD_SOURCE.
  11. * _DEFAULT_SOURCE is an alias for that. */
  12. #ifndef _BSD_SOURCE
  13. # define _BSD_SOURCE
  14. #endif
  15. #include "open62541.h"
  16. #include <signal.h>
  17. #ifdef _WIN32
  18. # include <windows.h>
  19. # define UA_sleep_ms(X) Sleep(X)
  20. #else
  21. # include <unistd.h>
  22. # define UA_sleep_ms(X) usleep(X * 1000)
  23. #endif
  24. UA_Boolean running = true;
  25. UA_Logger logger = UA_Log_Stdout;
  26. static void stopHandler(int sign) {
  27. UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND, "Received Ctrl-C");
  28. running = 0;
  29. }
  30. static void
  31. inactivityCallback (UA_Client *client) {
  32. UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND, "Server Inactivity");
  33. }
  34. int main(void) {
  35. signal(SIGINT, stopHandler); /* catches ctrl-c */
  36. UA_ClientConfig config = UA_ClientConfig_default;
  37. /* Set stateCallback */
  38. config.inactivityCallback = inactivityCallback;
  39. /* Perform a connectivity check every 2 seconds */
  40. config.connectivityCheckInterval = 2000;
  41. UA_Client *client = UA_Client_new(config);
  42. /* Endless loop runAsync */
  43. while (running) {
  44. /* if already connected, this will return GOOD and do nothing */
  45. /* if the connection is closed/errored, the connection will be reset and then reconnected */
  46. /* Alternatively you can also use UA_Client_getState to get the current state */
  47. UA_StatusCode retval = UA_Client_connect(client, "opc.tcp://localhost:4840");
  48. if(retval != UA_STATUSCODE_GOOD) {
  49. UA_LOG_ERROR(logger, UA_LOGCATEGORY_USERLAND, "Not connected. Retrying to connect in 1 second");
  50. /* The connect may timeout after 1 second (see above) or it may fail immediately on network errors */
  51. /* E.g. name resolution errors or unreachable network. Thus there should be a small sleep here */
  52. UA_sleep_ms(1000);
  53. continue;
  54. }
  55. UA_Client_run_iterate(client, 1000);
  56. };
  57. /* Clean up */
  58. UA_Client_delete(client); /* Disconnects the client internally */
  59. return UA_STATUSCODE_GOOD;
  60. }