I am planning on using Boost Asio library for targeting serial ports. I am not entirely sure how to use it, however.
As I understand it, asio needs to be built. In theory there is a ham build... script? - that is already configured for use in this case. However, I do not seem to have the building .exe. Apparently it can be obtained by building Boost.Build. However, running that build script also failed.
I have run bootstrap.bat, it failed citing that it cannot find "cl". The build script is the same.
I feel the answer is simple, but I am not certain. I tried an answer I saw here, but that also failed.
EDIT:
Built, successfully as far as I know. As I understand it, asio is a header-only library, but system is not. My configuration is for multithreaded static debug. I, using a bit of trial and error, and a boost doc page, found one that builds my code. However, it throws exceptions, and I am not sure if it is somehow a library mismatch or bad build - as this is the first line of code that would rely on whether or not it linked - or if my code is just bad and boost works fine.
Here is the code:
//SimpleSerial.h
#include <boost/asio.hpp>
class SimpleSerial
{
public:
/**
* Constructor.
* \param port device name, example "/dev/ttyUSB0" or "COM4"
* \param baud_rate communication speed, example 9600 or 115200
* \throws boost::system::system_error if cannot open the
* serial device
*/
SimpleSerial(std::string port, unsigned int baud_rate)
: io(), serial(io,port)
{
serial.set_option(boost::asio::serial_port_base::baud_rate(baud_rate));
}
/**
* Write a string to the serial device.
* \param s string to write
* \throws boost::system::system_error on failure
*/
void writeString(std::string s)
{
boost::asio::write(serial,boost::asio::buffer(s.c_str(),s.size()));
}
/**
* Blocks until a line is received from the serial device.
* Eventual '\n' or '\r\n' characters at the end of the string are removed.
* \return a string containing the received line
* \throws boost::system::system_error on failure
*/
std::string readLine()
{
//Reading data char by char, code is optimized for simplicity, not speed
using namespace boost;
char c;
std::string result;
for(;;)
{
asio::read(serial,asio::buffer(&c,1));
switch(c)
{
case '\r':
break;
case '\n':
return result;
default:
result+=c;
}
}
}
private:
boost::asio::io_service io;
boost::asio::serial_port serial;
};
//end SimpleSerial.h
//main.cpp
#include <iostream>
#include "SimpleSerial.h"
using namespace std;
using namespace boost;
int main(int argc, char* argv[])
{
try {
SimpleSerial serial("COM1",115200);
serial.writeString("Hello world\n");
cout<<serial.readLine()<<endl;
} catch(boost::system::system_error& e)
{
cout<<"Error: "<<e.what()<<endl;
return 1;
}
}
//end main.cpp
Exception throw on the SimpleSerial serial("COM1",115200); line. Error:
boost::exception_detail::clone_impl > at memory location 0x006DF470.