Diag-Client-Lib
Public Types | Public Member Functions | Private Types | Private Member Functions | Private Attributes | List of all members
boost_support::socket::tcp::TcpClientSocket Class Referencefinal

Class used to create a tcp socket for handling transmission and reception of tcp message from driver. More...

#include <tcp_client.h>

Public Types

enum class  TcpErrorCode : std::uint8_t { kOpenFailed , kBindingFailed , kGenericError }
 Tcp error code. More...
 
using TcpHandlerRead = std::function< void(TcpMessagePtr)>
 Tcp function template used for reception. More...
 

Public Member Functions

 TcpClientSocket (std::string_view local_ip_address, std::uint16_t local_port_num, TcpHandlerRead tcp_handler_read)
 Constructs an instance of TcpClientSocket. More...
 
 ~TcpClientSocket ()
 Destruct an instance of TcpClientSocket. More...
 
core_type::Result< void, TcpErrorCodeOpen ()
 Function to Open the socket. More...
 
core_type::Result< void, TcpErrorCodeConnectToHost (std::string_view host_ip_address, std::uint16_t host_port_num)
 Function to connect to remote ip address and port number. More...
 
core_type::Result< void, TcpErrorCodeDisconnectFromHost ()
 Function to Disconnect from host. More...
 
core_type::Result< void, TcpErrorCodeTransmit (TcpMessageConstPtr tcp_message)
 Function to trigger transmission. More...
 
core_type::Result< void, TcpErrorCodeDestroy ()
 Function to destroy the socket. More...
 

Private Types

using Tcp = boost::asio::ip::tcp
 Type alias for tcp protocol. More...
 
using TcpSocket = Tcp::socket
 Type alias for tcp socket. More...
 
using TcpIpAddress = boost::asio::ip::address
 Type alias for tcp ip address. More...
 
using TcpErrorCodeType = boost::system::error_code
 Type alias for tcp error codes. More...
 

Private Member Functions

void HandleMessage ()
 Function to handle the reception of tcp message. More...
 

Private Attributes

std::string local_ip_address_
 Store local ip address. More...
 
std::uint16_t local_port_num_
 Store local port number. More...
 
boost::asio::io_context io_context_
 boost io context More...
 
TcpSocket tcp_socket_
 Store tcp socket. More...
 
std::atomic_bool exit_request_
 Flag to terminate the thread. More...
 
std::atomic_bool running_
 Flag to start the thread. More...
 
std::condition_variable cond_var_
 Conditional variable to block the thread. More...
 
std::thread thread_
 The thread itself. More...
 
std::mutex mutex_
 mutex to lock critical section More...
 
TcpHandlerRead tcp_handler_read_
 Store the handler. More...
 

Detailed Description

Class used to create a tcp socket for handling transmission and reception of tcp message from driver.

Definition at line 26 of file tcp_client.h.

Member Typedef Documentation

◆ Tcp

using boost_support::socket::tcp::TcpClientSocket::Tcp = boost::asio::ip::tcp
private

Type alias for tcp protocol.

Definition at line 95 of file tcp_client.h.

◆ TcpErrorCodeType

using boost_support::socket::tcp::TcpClientSocket::TcpErrorCodeType = boost::system::error_code
private

Type alias for tcp error codes.

Definition at line 110 of file tcp_client.h.

◆ TcpHandlerRead

Tcp function template used for reception.

Definition at line 36 of file tcp_client.h.

◆ TcpIpAddress

using boost_support::socket::tcp::TcpClientSocket::TcpIpAddress = boost::asio::ip::address
private

Type alias for tcp ip address.

Definition at line 105 of file tcp_client.h.

◆ TcpSocket

Type alias for tcp socket.

Definition at line 100 of file tcp_client.h.

Member Enumeration Documentation

◆ TcpErrorCode

Tcp error code.

Enumerator
kOpenFailed 
kBindingFailed 
kGenericError 

Definition at line 31 of file tcp_client.h.

31 : std::uint8_t { kOpenFailed, kBindingFailed, kGenericError };

Constructor & Destructor Documentation

◆ TcpClientSocket()

boost_support::socket::tcp::TcpClientSocket::TcpClientSocket ( std::string_view  local_ip_address,
std::uint16_t  local_port_num,
TcpHandlerRead  tcp_handler_read 
)

Constructs an instance of TcpClientSocket.

Parameters
[in]local_ip_addressThe local ip address
[in]local_port_numThe local port number
[in]tcp_handler_readThe handler to send received data to user

Definition at line 19 of file tcp_client.cpp.

21  : local_ip_address_{local_ip_address},
22  local_port_num_{local_port_num},
23  io_context_{},
25  exit_request_{false},
26  running_{false},
27  cond_var_{},
28  mutex_{},
29  tcp_handler_read_{std::move(tcp_handler_read)} {
30  // Start thread to receive messages
31  thread_ = std::thread([this]() {
32  std::unique_lock<std::mutex> lck(mutex_);
33  while (!exit_request_) {
34  if (!running_) {
35  cond_var_.wait(lck, [this]() { return exit_request_ || running_; });
36  }
37  if (!exit_request_.load()) {
38  if (running_) {
39  lck.unlock();
40  HandleMessage();
41  lck.lock();
42  }
43  }
44  }
45  });
46 }
std::uint16_t local_port_num_
Store local port number.
Definition: tcp_client.h:120
std::string local_ip_address_
Store local ip address.
Definition: tcp_client.h:115
TcpSocket tcp_socket_
Store tcp socket.
Definition: tcp_client.h:130
std::mutex mutex_
mutex to lock critical section
Definition: tcp_client.h:155
TcpHandlerRead tcp_handler_read_
Store the handler.
Definition: tcp_client.h:160
boost::asio::io_context io_context_
boost io context
Definition: tcp_client.h:125
std::atomic_bool exit_request_
Flag to terminate the thread.
Definition: tcp_client.h:135
std::atomic_bool running_
Flag to start the thread.
Definition: tcp_client.h:140
std::condition_variable cond_var_
Conditional variable to block the thread.
Definition: tcp_client.h:145
void HandleMessage()
Function to handle the reception of tcp message.
Definition: tcp_client.cpp:173
std::thread thread_
The thread itself.
Definition: tcp_client.h:150

References cond_var_, exit_request_, HandleMessage(), mutex_, running_, and thread_.

Here is the call graph for this function:

◆ ~TcpClientSocket()

boost_support::socket::tcp::TcpClientSocket::~TcpClientSocket ( )

Destruct an instance of TcpClientSocket.

Definition at line 48 of file tcp_client.cpp.

48  {
49  exit_request_ = true;
50  running_ = false;
51  cond_var_.notify_all();
52  thread_.join();
53 }

References cond_var_, exit_request_, running_, and thread_.

Member Function Documentation

◆ ConnectToHost()

core_type::Result< void, TcpClientSocket::TcpErrorCode > boost_support::socket::tcp::TcpClientSocket::ConnectToHost ( std::string_view  host_ip_address,
std::uint16_t  host_port_num 
)

Function to connect to remote ip address and port number.

Parameters
[in]host_ip_addressThe host ip address
[in]host_port_numThe host port number
Returns
Empty result on success otherwise error code

Definition at line 94 of file tcp_client.cpp.

95  {
97  TcpErrorCodeType ec{};
98 
99  // connect to provided ipAddress
100  tcp_socket_.connect(Tcp::endpoint(TcpIpAddress::from_string(std::string{host_ip_address}), host_port_num), ec);
101  if (ec.value() == boost::system::errc::success) {
103  __FILE__, __LINE__, __func__, [this](std::stringstream &msg) {
104  Tcp::endpoint const endpoint_{tcp_socket_.remote_endpoint()};
105  msg << "Tcp Socket connected to host "
106  << "<" << endpoint_.address().to_string() << "," << endpoint_.port() << ">";
107  });
108  { // start reading
109  std::lock_guard<std::mutex> lock{mutex_};
110  running_ = true;
111  cond_var_.notify_all();
112  }
113  result.EmplaceValue();
114  } else {
116  __FILE__, __LINE__, __func__,
117  [ec](std::stringstream &msg) { msg << "Tcp Socket connect to host failed with error: " << ec.message(); });
118  }
119  return result;
120 }
static auto GetLibBoostLogger() noexcept -> LibBoostLogger &
Definition: logger.h:20
boost::system::error_code TcpErrorCodeType
Type alias for tcp error codes.
Definition: tcp_client.h:110
Class type to contains a value (of type ValueType), or an error (of type ErrorType)
Definition: result.h:29

References cond_var_, boost_support::common::logger::LibBoostLogger::GetLibBoostLogger(), kGenericError, mutex_, running_, and tcp_socket_.

Here is the call graph for this function:

◆ Destroy()

core_type::Result< void, TcpClientSocket::TcpErrorCode > boost_support::socket::tcp::TcpClientSocket::Destroy ( )

Function to destroy the socket.

Returns
Empty result on success otherwise error code

Definition at line 165 of file tcp_client.cpp.

165  {
167  // destroy the socket
168  tcp_socket_.close();
169  result.EmplaceValue();
170  return result;
171 }

References kGenericError, and tcp_socket_.

◆ DisconnectFromHost()

core_type::Result< void, TcpClientSocket::TcpErrorCode > boost_support::socket::tcp::TcpClientSocket::DisconnectFromHost ( )

Function to Disconnect from host.

Returns
Empty result on success otherwise error code

Definition at line 122 of file tcp_client.cpp.

122  {
124  TcpErrorCodeType ec{};
125 
126  // Graceful shutdown
127  tcp_socket_.shutdown(TcpSocket::shutdown_both, ec);
128  if (ec.value() == boost::system::errc::success) {
129  // stop reading
130  running_ = false;
131  // Socket shutdown success
132  result.EmplaceValue();
133  } else {
135  __FILE__, __LINE__, __func__, [ec](std::stringstream &msg) {
136  msg << "Tcp Socket disconnection from host failed with error: " << ec.message();
137  });
138  }
139  return result;
140 }

References boost_support::common::logger::LibBoostLogger::GetLibBoostLogger(), kGenericError, running_, and tcp_socket_.

Here is the call graph for this function:

◆ HandleMessage()

void boost_support::socket::tcp::TcpClientSocket::HandleMessage ( )
private

Function to handle the reception of tcp message.

Definition at line 173 of file tcp_client.cpp.

173  {
174  TcpErrorCodeType ec{};
175  // create and reserve the buffer
176  TcpMessage::BufferType rx_buffer{};
177  rx_buffer.resize(kDoipheadrSize);
178  // start blocking read to read Header first
179  boost::asio::read(tcp_socket_, boost::asio::buffer(&rx_buffer[0u], kDoipheadrSize), ec);
180  // Check for error
181  if (ec.value() == boost::system::errc::success) {
182  // read the next bytes to read
183  std::uint32_t const read_next_bytes = [&rx_buffer]() noexcept -> std::uint32_t {
184  return static_cast<std::uint32_t>((static_cast<std::uint32_t>(rx_buffer[4u] << 24u) & 0xFF000000) |
185  (static_cast<std::uint32_t>(rx_buffer[5u] << 16u) & 0x00FF0000) |
186  (static_cast<std::uint32_t>(rx_buffer[6u] << 8u) & 0x0000FF00) |
187  (static_cast<std::uint32_t>(rx_buffer[7u] & 0x000000FF)));
188  }();
189  // reserve the buffer
190  rx_buffer.resize(kDoipheadrSize + std::size_t(read_next_bytes));
191  boost::asio::read(tcp_socket_, boost::asio::buffer(&rx_buffer[kDoipheadrSize], read_next_bytes), ec);
192 
193  // all message received, transfer to upper layer
194  Tcp::endpoint const endpoint_{tcp_socket_.remote_endpoint()};
195  TcpMessagePtr tcp_rx_message{
196  std::make_unique<TcpMessage>(endpoint_.address().to_string(), endpoint_.port(), std::move(rx_buffer))};
198  __FILE__, __LINE__, __func__, [endpoint_](std::stringstream &msg) {
199  msg << "Tcp Message received from "
200  << "<" << endpoint_.address().to_string() << "," << endpoint_.port() << ">";
201  });
202  // notify upper layer about received message
203  tcp_handler_read_(std::move(tcp_rx_message));
204  } else if (ec.value() == boost::asio::error::eof) {
205  running_ = false;
207  __FILE__, __LINE__, __func__,
208  [ec](std::stringstream &msg) { msg << "Remote Disconnected with: " << ec.message(); });
209  } else {
210  running_ = false;
212  __FILE__, __LINE__, __func__,
213  [ec](std::stringstream &msg) { msg << "Remote Disconnected with undefined error: " << ec.message(); });
214  }
215 }
std::vector< uint8_t > BufferType
Type alias for underlying buffer.
Definition: tcp_message.h:48
constexpr std::uint8_t kDoipheadrSize
Doip HeaderSize.
Definition: tcp_message.h:182
std::unique_ptr< TcpMessage > TcpMessagePtr
The unique pointer to TcpMessage.
Definition: tcp_message.h:177

References boost_support::common::logger::LibBoostLogger::GetLibBoostLogger(), boost_support::socket::tcp::kDoipheadrSize, running_, tcp_handler_read_, and tcp_socket_.

Referenced by TcpClientSocket().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ Open()

core_type::Result< void, TcpClientSocket::TcpErrorCode > boost_support::socket::tcp::TcpClientSocket::Open ( )

Function to Open the socket.

Returns
Empty result on success otherwise error code

Definition at line 55 of file tcp_client.cpp.

55  {
57  TcpErrorCodeType ec{};
58 
59  // Open the socket
60  tcp_socket_.open(Tcp::v4(), ec);
61  if (ec.value() == boost::system::errc::success) {
62  // reuse address
63  tcp_socket_.set_option(boost::asio::socket_base::reuse_address{true});
64  // Set socket to non blocking
65  tcp_socket_.non_blocking(false);
66  // Bind to local ip address and random port
67  tcp_socket_.bind(Tcp::endpoint(TcpIpAddress::from_string(local_ip_address_), local_port_num_), ec);
68 
69  if (ec.value() == boost::system::errc::success) {
70  // Socket binding success
72  __FILE__, __LINE__, __func__, [this](std::stringstream &msg) {
73  Tcp::endpoint const endpoint_{tcp_socket_.local_endpoint()};
74  msg << "Tcp Socket opened and bound to "
75  << "<" << endpoint_.address().to_string() << "," << endpoint_.port() << ">";
76  });
77  result.EmplaceValue();
78  } else {
79  // Socket binding failed
81  __FILE__, __LINE__, __func__,
82  [ec](std::stringstream &msg) { msg << "Tcp Socket binding failed with message: " << ec.message(); });
83  result.EmplaceError(TcpErrorCode::kBindingFailed);
84  }
85  } else {
87  __FILE__, __LINE__, __func__,
88  [ec](std::stringstream &msg) { msg << "Tcp Socket opening failed with error: " << ec.message(); });
89  result.EmplaceError(TcpErrorCode::kOpenFailed);
90  }
91  return result;
92 }

References boost_support::common::logger::LibBoostLogger::GetLibBoostLogger(), kBindingFailed, kGenericError, kOpenFailed, local_ip_address_, local_port_num_, and tcp_socket_.

Here is the call graph for this function:

◆ Transmit()

core_type::Result< void, TcpClientSocket::TcpErrorCode > boost_support::socket::tcp::TcpClientSocket::Transmit ( TcpMessageConstPtr  tcp_message)

Function to trigger transmission.

Parameters
[in]tcp_messageThe tcp message to be transmitted
Returns
Empty result on success otherwise error code

Definition at line 142 of file tcp_client.cpp.

142  {
144  TcpErrorCodeType ec{};
145 
146  boost::asio::write(tcp_socket_, boost::asio::buffer(tcp_message->GetTxBuffer(), tcp_message->GetTxBuffer().size()),
147  ec);
148  // Check for error
149  if (ec.value() == boost::system::errc::success) {
151  __FILE__, __LINE__, __func__, [this](std::stringstream &msg) {
152  Tcp::endpoint const endpoint_{tcp_socket_.remote_endpoint()};
153  msg << "Tcp message sent to "
154  << "<" << endpoint_.address().to_string() << "," << endpoint_.port() << ">";
155  });
156  result.EmplaceValue();
157  } else {
159  __FILE__, __LINE__, __func__,
160  [ec](std::stringstream &msg) { msg << "Tcp message sending failed with error: " << ec.message(); });
161  }
162  return result;
163 }

References boost_support::common::logger::LibBoostLogger::GetLibBoostLogger(), kGenericError, and tcp_socket_.

Here is the call graph for this function:

Member Data Documentation

◆ cond_var_

std::condition_variable boost_support::socket::tcp::TcpClientSocket::cond_var_
private

Conditional variable to block the thread.

Definition at line 145 of file tcp_client.h.

Referenced by ConnectToHost(), TcpClientSocket(), and ~TcpClientSocket().

◆ exit_request_

std::atomic_bool boost_support::socket::tcp::TcpClientSocket::exit_request_
private

Flag to terminate the thread.

Definition at line 135 of file tcp_client.h.

Referenced by TcpClientSocket(), and ~TcpClientSocket().

◆ io_context_

boost::asio::io_context boost_support::socket::tcp::TcpClientSocket::io_context_
private

boost io context

Definition at line 125 of file tcp_client.h.

◆ local_ip_address_

std::string boost_support::socket::tcp::TcpClientSocket::local_ip_address_
private

Store local ip address.

Definition at line 115 of file tcp_client.h.

Referenced by Open().

◆ local_port_num_

std::uint16_t boost_support::socket::tcp::TcpClientSocket::local_port_num_
private

Store local port number.

Definition at line 120 of file tcp_client.h.

Referenced by Open().

◆ mutex_

std::mutex boost_support::socket::tcp::TcpClientSocket::mutex_
private

mutex to lock critical section

Definition at line 155 of file tcp_client.h.

Referenced by ConnectToHost(), and TcpClientSocket().

◆ running_

std::atomic_bool boost_support::socket::tcp::TcpClientSocket::running_
private

Flag to start the thread.

Definition at line 140 of file tcp_client.h.

Referenced by ConnectToHost(), DisconnectFromHost(), HandleMessage(), TcpClientSocket(), and ~TcpClientSocket().

◆ tcp_handler_read_

TcpHandlerRead boost_support::socket::tcp::TcpClientSocket::tcp_handler_read_
private

Store the handler.

Definition at line 160 of file tcp_client.h.

Referenced by HandleMessage().

◆ tcp_socket_

TcpSocket boost_support::socket::tcp::TcpClientSocket::tcp_socket_
private

Store tcp socket.

Definition at line 130 of file tcp_client.h.

Referenced by ConnectToHost(), Destroy(), DisconnectFromHost(), HandleMessage(), Open(), and Transmit().

◆ thread_

std::thread boost_support::socket::tcp::TcpClientSocket::thread_
private

The thread itself.

Definition at line 150 of file tcp_client.h.

Referenced by TcpClientSocket(), and ~TcpClientSocket().


The documentation for this class was generated from the following files: