client_connectivitycheck_loop.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. #include <ua_client.h>
  4. #include <ua_config_default.h>
  5. #include <ua_log_stdout.h>
  6. #include <signal.h>
  7. UA_Boolean running = true;
  8. static void stopHandler(int sign) {
  9. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Received Ctrl-C");
  10. running = 0;
  11. }
  12. static void
  13. inactivityCallback (UA_Client *client) {
  14. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Server Inactivity");
  15. }
  16. int main(void) {
  17. signal(SIGINT, stopHandler); /* catches ctrl-c */
  18. UA_Client *client = UA_Client_new();
  19. UA_ClientConfig *cc = UA_Client_getConfig(client);
  20. UA_ClientConfig_setDefault(cc);
  21. cc->inactivityCallback = inactivityCallback; /* Set stateCallback */
  22. cc->connectivityCheckInterval = 2000; /* Perform a connectivity check every 2 seconds */
  23. /* Endless loop runAsync */
  24. while (running) {
  25. /* if already connected, this will return GOOD and do nothing */
  26. /* if the connection is closed/errored, the connection will be reset and then reconnected */
  27. /* Alternatively you can also use UA_Client_getState to get the current state */
  28. UA_StatusCode retval = UA_Client_connect(client, "opc.tcp://localhost:4840");
  29. if(retval != UA_STATUSCODE_GOOD) {
  30. UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
  31. "Not connected. Retrying to connect in 1 second");
  32. /* The connect may timeout after 1 second (see above) or it may fail immediately on network errors */
  33. /* E.g. name resolution errors or unreachable network. Thus there should be a small sleep here */
  34. UA_sleep_ms(1000);
  35. continue;
  36. }
  37. UA_Client_run_iterate(client, 1000);
  38. };
  39. /* Clean up */
  40. UA_Client_delete(client); /* Disconnects the client internally */
  41. return UA_STATUSCODE_GOOD;
  42. }