client_connectivitycheck_loop.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 "open62541.h"
  4. #include <signal.h>
  5. UA_Boolean running = true;
  6. UA_Logger logger = UA_Log_Stdout;
  7. static void stopHandler(int sign) {
  8. UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND, "Received Ctrl-C");
  9. running = 0;
  10. }
  11. static void
  12. inactivityCallback (UA_Client *client) {
  13. UA_LOG_INFO(logger, UA_LOGCATEGORY_USERLAND, "Server Inactivity");
  14. }
  15. int main(void) {
  16. signal(SIGINT, stopHandler); /* catches ctrl-c */
  17. UA_ClientConfig config = UA_ClientConfig_default;
  18. /* Set stateCallback */
  19. config.inactivityCallback = inactivityCallback;
  20. /* Perform a connectivity check every 2 seconds */
  21. config.connectivityCheckInterval = 2000;
  22. UA_Client *client = UA_Client_new(config);
  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(logger, UA_LOGCATEGORY_USERLAND, "Not connected. Retrying to connect in 1 second");
  31. /* The connect may timeout after 1 second (see above) or it may fail immediately on network errors */
  32. /* E.g. name resolution errors or unreachable network. Thus there should be a small sleep here */
  33. UA_sleep_ms(1000);
  34. continue;
  35. }
  36. UA_Client_run_iterate(client, 1000);
  37. };
  38. /* Clean up */
  39. UA_Client_delete(client); /* Disconnects the client internally */
  40. return UA_STATUSCODE_GOOD;
  41. }