p26001-store-acs-soc-fw-app/network/TCPClient.cpp
2026-09-28 21:33:04 +08:00

148 lines
3 KiB
C++

/*
*******************************************************************************
* INCLUDE
*******************************************************************************
*/
#include "TCPClient.h"
#include <Poco/Net/NetException.h>
namespace Network
{
TCPClient::TCPClient(std::string host, int port, Poco::Timespan timeout, uint32_t sz)
: Poco::Task("TCPClient"), _address(host, port), _timeout(timeout), _bufsz(sz), _pBuffer(new uint8_t[sz])
{
}
TCPClient::~TCPClient()
{
}
int TCPClient::send(const uint8_t* data, uint32_t len)
{
try
{
int rc = _socket.sendBytes(data, len);
return rc;
}
catch (const std::exception& e)
{
}
return 0;
}
void TCPClient::start()
{
if (!_thread.isRunning())
_thread.start(*this);
}
void TCPClient::stop()
{
if (_thread.isRunning())
{
cancel();
_thread.join();
}
}
void TCPClient::setStateChangedCallback(const StateChangedCallback& callback)
{
_stateChanged = std::move(callback);
}
void TCPClient::setDataIncomingCallback(const DataIncomingCallback& callback)
{
_dataIncoming = std::move(callback);
}
bool TCPClient::connect()
{
try
{
_socket.connect(_address, _timeout);
_socket.setReceiveTimeout(Poco::Timespan(1000));
setState(State::CONNECTED, "Connected");
return true;
}
catch (Poco::TimeoutException& e)
{
setState(State::CONNECT_TIMEOUT, e.displayText());
}
catch (Poco::Net::ConnectionRefusedException& e)
{
setState(State::CONNECT_REFUSED, e.displayText());
}
catch (Poco::Exception& e)
{
setState(State::CONNECT_REFUSED, e.displayText());
}
return false;
}
void TCPClient::runTask()
{
while (!isCancelled())
{
while (!isCancelled())
{
setState(State::CONNECTING, "Connecting");
if (connect())
break;
Poco::Thread::sleep(1000);
}
while (!isCancelled())
{
try
{
int rc = _socket.receiveBytes(_pBuffer, _bufsz);
if (rc <= 0)
{
setState(State::DISCONNECTED, "Connection lost");
_socket.close();
break;
}
receive(_pBuffer, rc);
}
catch (Poco::TimeoutException& e)
{
}
catch (Poco::Exception& e)
{
setState(State::DISCONNECTED, "Connection lost");
_socket.close();
break;
}
}
Poco::Thread::sleep(1000);
}
try
{
_socket.close();
}
catch (...)
{
}
}
void TCPClient::setState(State state, const std::string& desc)
{
if (_stateChanged)
_stateChanged(state, desc);
}
void TCPClient::receive(const uint8_t* data, uint32_t len)
{
if (_dataIncoming)
_dataIncoming(data, len);
}
}