client_connectivitycheck_loop.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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/client.h>
  4. #include <open62541/client_config_default.h>
  5. #include <open62541/plugin/log_stdout.h>
  6. #include <signal.h>
  7. #include <stdlib.h>
  8. UA_Boolean running = true;
  9. static void stopHandler(int sign) {
  10. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Received Ctrl-C");
  11. running = 0;
  12. }
  13. static void
  14. inactivityCallback (UA_Client *client) {
  15. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_USERLAND, "Server Inactivity");
  16. }
  17. int main(void) {
  18. signal(SIGINT, stopHandler); /* catches ctrl-c */
  19. UA_Client *client = UA_Client_new();
  20. UA_ClientConfig *cc = UA_Client_getConfig(client);
  21. UA_ClientConfig_setDefault(cc);
  22. cc->inactivityCallback = inactivityCallback; /* Set stateCallback */
  23. cc->connectivityCheckInterval = 2000; /* Perform a connectivity check every 2 seconds */
  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 EXIT_SUCCESS;
  43. }