This sample shows how to react on unexpected connection close events and how to reconnect automatically.
#include "Helper.h"
#include <atomic>
#include <chrono>
#include <iostream>
#include <thread>
using namespace wz::baos::ip;
{
try
{
std::cout << "******************************************" << std::endl;
std::cout << "ConnectionReconnect sample" << std::endl;
std::cout << "******************************************" << std::endl;
std::cout << std::endl;
setBaosLogLevel(wz::baos::LogLevel::info);
options.setDurationOptionSupported(
true);
{
return 0;
}
std::cout <<
"Connection requested for " <<
ipAddress << std::endl;
{
std::cout <<
"Connection event=" << toString(
event.type);
std::cout << std::endl;
if (
event.type == ConnectionEvent::Type::ClosedAfterError)
{
}
});
{
std::cout <<
"Received " <<
serverItems.size() <<
" server item indication(s)" << std::endl;
});
{
{
std::cout << "Press [Enter] to stop. Unplug network or restart device to trigger reconnect."
<< std::endl;
std::getchar();
});
}
else
{
std::cout <<
"Running for " <<
options.getDurationSeconds() <<
" second(s) ..." << std::endl;
}
const auto startTime = std::chrono::steady_clock::now();
{
const auto now = std::chrono::steady_clock::now();
{
break;
}
{
try
{
std::cout << "Trying to reconnect ..." << std::endl;
std::cout << "Reconnect successful" << std::endl;
}
catch (
const std::exception&
e)
{
std::cout <<
"Reconnect failed: " <<
e.what() << std::endl;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
{
}
}
catch (
const std::exception&
e)
{
std::cerr <<
"Failed: " <<
e.what() << std::endl;
return -1;
}
return 0;
}
Specialization for a TCP IP v4 BAOSConnection.
Global BAOS SDK function and options.
void setServerItemsIndCallback(ServerItemIndicationCb callback)
void close()
Close the connection to the BAOS device.
void setConnectionEventCallback(ConnectionEventCb callback)
A specialization for (connection-less) connection to the BAOS device via a TCP connection.
Definition BaosTcpConnection.h:145
A specialization for (connection oriented) connection to the BAOS device via a TCP connection.
Definition BaosTcpConnection.h:182
void reopen() override
Reopens the underlying connection, has to be implemented by derived classes.
void open(const std::string &ip4Address, std::uint16_t port=12004)
Open a connection to physical BAOS device.
Groups BAOS binary protocol specific types , defines and classes for Indications, Responses etc.
Definition Defines.h:33
std::vector< ServerItem > ServerItems
Type for a list of ServerItems.
Definition Defines.h:440
Global BAOS sdk namespace.
Definition config.h:69
BAOSLIB_EXPORT void setBaosLogLevel(wz::baos::LogLevel level)
Definition ConnectionEvent.h:37