AsyncUDPClient.cpp
Go to the documentation of this file.
00001 // this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
00002 
00003 // -- BEGIN LICENSE BLOCK ----------------------------------------------
00004 
00024 // -- END LICENSE BLOCK ------------------------------------------------
00025 
00026 //----------------------------------------------------------------------
00033 //----------------------------------------------------------------------
00034 
00035 
00036 #include <sick_safetyscanners/communication/AsyncUDPClient.h>
00037 
00038 namespace sick {
00039 namespace communication {
00040 AsyncUDPClient::AsyncUDPClient(PacketHandler packet_handler,
00041                                boost::asio::io_service& io_service,
00042                                const uint16_t& local_port)
00043   : m_packet_handler(packet_handler)
00044   , m_io_work_ptr()
00045   , m_io_service(io_service)
00046 {
00047   // Keep io_service busy
00048   m_io_work_ptr = std::make_shared<boost::asio::io_service::work>(boost::ref(m_io_service));
00049   try
00050   {
00051     m_socket_ptr = std::make_shared<boost::asio::ip::udp::socket>(
00052       boost::ref(m_io_service),
00053       boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), local_port));
00054   }
00055   catch (std::exception& e)
00056   {
00057     ROS_ERROR("Exception while creating socket: %s", e.what());
00058   }
00059   ROS_INFO("UDP client is setup");
00060 }
00061 
00062 AsyncUDPClient::~AsyncUDPClient()
00063 {
00064   m_io_service.stop();
00065 }
00066 
00067 void AsyncUDPClient::startReceive()
00068 {
00069   m_socket_ptr->async_receive_from(boost::asio::buffer(m_recv_buffer),
00070                                    m_remote_endpoint,
00071                                    [this](boost::system::error_code ec, std::size_t bytes_recvd) {
00072                                      this->handleReceive(ec, bytes_recvd);
00073                                    });
00074 }
00075 
00076 void AsyncUDPClient::handleReceive(const boost::system::error_code& error,
00077                                    const std::size_t& bytes_transferred)
00078 {
00079   if (!error)
00080   {
00081     sick::datastructure::PacketBuffer packet_buffer(m_recv_buffer, bytes_transferred);
00082     m_packet_handler(packet_buffer);
00083   }
00084   else
00085   {
00086     ROS_ERROR("Error in UDP handle receive: %i", error.value());
00087   }
00088   startReceive();
00089 }
00090 
00091 
00092 void AsyncUDPClient::runService()
00093 {
00094   startReceive();
00095 }
00096 
00097 unsigned short AsyncUDPClient::get_local_port()
00098 {
00099   if (m_socket_ptr)
00100   {
00101     return m_socket_ptr->local_endpoint().port();
00102   }
00103   return 0;
00104 }
00105 
00106 } // namespace communication
00107 } // namespace sick


sick_safetyscanners
Author(s): Lennart Puck
autogenerated on Tue May 7 2019 03:27:36