38 #ifndef ASYNC_COMM_COMM_H 39 #define ASYNC_COMM_COMM_H 41 #include <condition_variable> 49 #include <boost/asio.hpp> 50 #include <boost/function.hpp> 107 void send_bytes(
const uint8_t * src,
size_t len);
113 inline void send_byte(uint8_t data) { send_bytes(&data, 1); }
128 void register_receive_callback(std::function<
void(
const uint8_t*,
size_t)> fun);
143 static constexpr
size_t READ_BUFFER_SIZE = 1024;
144 static constexpr
size_t WRITE_BUFFER_SIZE = 1024;
148 virtual bool is_open() = 0;
149 virtual bool do_init() = 0;
150 virtual void do_close() = 0;
151 virtual void do_async_read(
const boost::asio::mutable_buffers_1 &buffer,
152 boost::function<
void(
const boost::system::error_code&,
size_t)> handler) = 0;
153 virtual void do_async_write(
const boost::asio::const_buffers_1 &buffer,
154 boost::function<
void(
const boost::system::error_code&,
size_t)> handler) = 0;
163 uint8_t data[READ_BUFFER_SIZE];
168 assert(len <= READ_BUFFER_SIZE);
169 memcpy(data, buf, len);
175 uint8_t data[WRITE_BUFFER_SIZE];
183 assert(len <= WRITE_BUFFER_SIZE);
184 memcpy(data, buf, len);
187 const uint8_t *
dpos()
const {
return data + pos; }
189 size_t nbytes()
const {
return len - pos; }
195 void async_read_end(
const boost::system::error_code& error,
size_t bytes_transferred);
197 void async_write(
bool check_write_state);
198 void async_write_end(
const boost::system::error_code& error,
size_t bytes_transferred);
200 void process_callbacks();
205 uint8_t read_buffer_[READ_BUFFER_SIZE];
216 std::function<void(const uint8_t *, size_t)> receive_callback_ =
nullptr;
217 std::vector<std::reference_wrapper<CommListener>>
listeners_;
222 #endif // ASYNC_COMM_COMM_H std::thread callback_thread_
std::vector< std::reference_wrapper< CommListener > > listeners_
Abstract base class for getting comm events via a listener interface.
virtual void receive_callback(const uint8_t *buf, size_t size)=0
Callback for data received.
boost::asio::io_service io_service_
WriteBuffer(const uint8_t *buf, size_t len)
Abstract base class for an asynchronous communication port.
MessageHandler & message_handler_
std::lock_guard< std::recursive_mutex > mutex_lock
static DefaultMessageHandler default_message_handler_
void send_byte(uint8_t data)
Send a single byte over the port.
std::list< WriteBuffer > write_queue_
std::recursive_mutex write_mutex_
const uint8_t * dpos() const
std::condition_variable condition_variable_
Abstract base class for message handler.
ReadBuffer(const uint8_t *buf, size_t len)
Default message handler that outputs to stdout and stderr.
std::list< ReadBuffer > read_queue_
std::mutex mutex
mutex for synchronization between the main thread and callback thread
std::mutex callback_mutex_
std::condition_variable condition_variable
condition variable used to suspend main thread until all messages have been received back ...