client_connectivitycheck_loop.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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_ClientConfig config = UA_ClientConfig_default;
  19. /* Set stateCallback */
  20. config.inactivityCallback = inactivityCallback;
  21. /* Perform a connectivity check every 2 seconds */
  22. config.connectivityCheckInterval = 2000;
  23. UA_Client *client = UA_Client_new(config);
  24. /* Endless loop runAsync */
  25. while (running) {
  26. /* if already connected, this will return GOOD and do nothing */
  27. /* if the connection is closed/errored, the connection will be reset and then reconnected */
  28. /* Alternatively you can also use UA_Client_getState to get the current state */
  29. UA_StatusCode retval = UA_Client_connect(client, "opc.tcp://localhost:4840");
  30. if(retval != UA_STATUSCODE_GOOD) {
  31. UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
  32. "Not connected. Retrying to connect in 1 second");
  33. /* The connect may timeout after 1 second (see above) or it may fail immediately on network errors */
  34. /* E.g. name resolution errors or unreachable network. Thus there should be a small sleep here */
  35. UA_sleep_ms(1000);
  36. continue;
  37. }
  38. UA_Client_run_iterate(client, 1000);
  39. };
  40. /* Clean up */
  41. UA_Client_delete(client); /* Disconnects the client internally */
  42. return UA_STATUSCODE_GOOD;
  43. }