Commit e2e88037 authored by Pierre NARVOR's avatar Pierre NARVOR
Browse files

[driver] Added AsyncService type for background operations

parent 2ff0d99f
......@@ -6,19 +6,26 @@ message(STATUS "Boost version : ${Boost_VERSION}")
message(STATUS "Boost location : ${Boost_INCLUDE_DIRS}")
list(APPEND seatrac_driver_headers
include/seatrac_driver/AsyncService.h
include/seatrac_driver/SeatracEnums.h
include/seatrac_driver/SeatracTypes.h
include/seatrac_driver/print_utils.h
include/seatrac_driver/SeatracSerial.h
include/seatrac_driver/SeatracDriver.h
include/seatrac_driver/messages/MessageBase.h
include/seatrac_driver/messages/Messages.h
include/seatrac_driver/messages/Status.h
include/seatrac_driver/messages/SysInfo.h
)
add_library(seatrac_driver SHARED
src/AsyncService.cpp
src/SeatracSerial.cpp
src/SeatracDriver.cpp
)
set_target_properties(seatrac_driver PROPERTIES
NARVAL_PUBLIC_HEADER "${seatrac_driver_headers}"
NARVAL_PUBLIC_HEADERS "${seatrac_driver_headers}"
INSTALL_RPATH_USE_LINK_PATH True
)
target_include_directories(seatrac_driver PUBLIC
......
#ifndef _DEF_SEATRAC_DRIVER_ASYNC_SERVICE_H_
#define _DEF_SEATRAC_DRIVER_ASYNC_SERVICE_H_
#include <iostream>
#include <thread>
#include <memory>
#define BOOST_BIND_GLOBAL_PLACEHOLDERS
#include <boost/asio.hpp>
#include <boost/bind.hpp>
namespace narval { namespace seatrac {
class AsyncService
{
public:
using IoService = boost::asio::io_service;
using IoServicePtr = std::shared_ptr<IoService>;
protected:
IoServicePtr service_;
std::thread thread_;
bool isRunning_;
public:
AsyncService();
~AsyncService();
IoServicePtr io_service();
bool is_running() const;
void start();
void stop();
};
}; //namespace seatrac
}; //namespace narval
#endif //_DEF_SEATRAC_DRIVER_ASYNC_SERVICE_H_
#include <seatrac_driver/AsyncService.h>
namespace narval { namespace seatrac {
AsyncService::AsyncService() :
service_(std::make_shared<IoService>()),
isRunning_(false)
{}
AsyncService::~AsyncService()
{
this->stop();
}
AsyncService::IoServicePtr AsyncService::io_service()
{
return service_;
}
bool AsyncService::is_running() const
{
return isRunning_;
}
void AsyncService::start()
{
if(this->is_running()) return;
std::cout << "starting" << std::endl;
if(service_->stopped())
service_->reset();
thread_ = std::thread(boost::bind(&boost::asio::io_service::run, service_));
if(!thread_.joinable())
throw std::runtime_error("Failed to start AsyncService");
isRunning_ = true;
}
void AsyncService::stop()
{
if(!this->is_running()) return;
std::cout << "stopping" << std::endl;
service_->stop();
thread_.join();
if(thread_.joinable())
throw std::runtime_error("Failed to stop AsyncService");
isRunning_ = false;
std::cout << "stopped" << std::endl;
}
}; //namespace seatrac
}; //namespace narval
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment