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. static void stopHandler(int sign) {
  7. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Received Ctrl-C");
  8. running = 0;
  9. }
  10. static void
  11. inactivityCallback (UA_Client *client) {
  12. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Server Inactivity");
  13. }
  14. int main(void) {
  15. signal(SIGINT, stopHandler); /* catches ctrl-c */
  16. UA_ClientConfig config = UA_ClientConfig_default;
  17. /* Set stateCallback */
  18. config.inactivityCallback = inactivityCallback;
  19. /* Perform a connectivity check every 2 seconds */
  20. config.connectivityCheckInterval = 2000;
  21. UA_Client *client = UA_Client_new(config);
  22. /* Endless loop runAsync */
  23. while (running) {
  24. /* if already connected, this will return GOOD and do nothing */
  25. /* if the connection is closed/errored, the connection will be reset and then reconnected */
  26. /* Alternatively you can also use UA_Client_getState to get the current state */
  27. UA_StatusCode retval = UA_Client_connect(client, "opc.tcp://localhost:4840");
  28. if(retval != UA_STATUSCODE_GOOD) {
  29. UA_LOG_ERROR(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
  30. "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. }