I am trying to use Boost ASIO for a serial port async read that I must continuously listen to when my program is run, additionally I am also listening to multicast udp reciever example I found in the Boost ASIO. Both UDP and serial receiver I am initializing with the same io_context. When I try to create serial port in my console app main program, I can compile and read from serial port but only once. So I thought I should make it into a separate class like in this example and maybe make use of a separate thread. However I get compilation error even when I am using the same exact syntax that I tried inside the main program which runs fine but only once. How can I continue to listen in async fashion on serial port too while I am continuously (still async) reading from the udp port data. Please advice.
I tried to look around for non-official examples, but they were really not helpful, either they were poor, outdated or just unnecessarily complicated. What I am trying to build is far more simpler like this
#pragma once
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
class SerialComm
{
public:
SerialComm(boost::asio::io_context& io_context, std::string& serial_port_name) :_serialport(io_context, serial_port_name)
{
start_receive();
}
~SerialComm()
{
}
private:
void start_receive()
{
_serialport.async_read_some(boost::asio::buffer(my_buffer, 1024),
&SerialComm::handle_receive);
}
void handle_receive(const boost::system::error_code& error,
std::size_t bytes_transferred)
{
if (!error)
{
std::cout << "Recieved:" << my_buffer << std::endl;
}
}
private:
boost::asio::serial_port _serialport;
unsigned char my_buffer[1024];
//boost::asio::buffer<char, 1024> recv_buffer_;
};
This is the error I get :
1>c:\users\alam syed\documents\someproject\boost\include\boost-root\boost\asio\serial_port.hpp(746): error C2338: ReadHandler type requirements not met 1>c:\users\alam syed\documents\someproject\public\serialcomm.h(24): note: see reference to function template instantiation 'void boost::asio::serial_port::async_read_some(const MutableBufferSequence &,ReadHandler &&)' being compiled 1> with 1> [ 1>
MutableBufferSequence=boost::asio::mutable_buffers_1, 1>
ReadHandler=void (__cdecl SerialComm::* )(const boost::system::error_code &,size_t) 1> ] 1>c:\users\alam syed\documents\someproject\boost\include\boost-root\boost\asio\use_future.hpp(138): note: see reference to class template instantiation 'boost::asio::use_future_t>::std_allocator_void' being compiled 1>c:\users\alam syed\documents\someproject\boost\include\boost-root\boost\asio\use_future.hpp(146): note: see reference to class template instantiation 'boost::asio::use_future_t>' being compiled