5#include <boost/asio/io_service.hpp>
6#include <boost/asio/read.hpp>
7#include <boost/asio/serial_port.hpp>
8#include <boost/asio/write.hpp>
9#include <boost/bind/bind.hpp>
11std::unique_ptr<boost::asio::serial_port>
13 boost::asio::io_service &io) {
15 spdlog::info(
"Intializing serial communication");
16 auto port = std::make_unique<boost::asio::serial_port>(io);
17 port->open(serialPort);
18 port->set_option(boost::asio::serial_port_base::baud_rate(baud));
19 spdlog::info(
"Serial communication intialized");
21 }
catch (
const std::exception &e) {
22 throw std::runtime_error(
"Fatal error opening serial port: \"" +
23 std::string(e.what()) +
24 "\" Does the port exist?");
28static void asyncHandler(
const boost::system::error_code &error,
29 std::size_t bytes_transferred,
int *res) {
31 spdlog::error(
"Error in serial port async handler: {}", error.what());
34 *res +=
static_cast<int>(bytes_transferred);
38 boost::asio::io_service &io) {
39 spdlog::info(
"Testing serial connection");
42 unsigned char writeData[8] = {85, 0, 0, 128, 128, 128, 128, 8};
43 unsigned char readData[1];
44 auto writeLen =
sizeof(writeData);
45 auto readLen =
sizeof(readData);
48 boost::asio::async_write(*serialPort,
49 boost::asio::buffer(writeData, writeLen),
50 boost::bind(&asyncHandler, boost::placeholders::_1,
51 boost::placeholders::_2, &writeRes));
52 boost::asio::async_read(*serialPort, boost::asio::buffer(readData, readLen),
53 boost::bind(&asyncHandler, boost::placeholders::_1,
54 boost::placeholders::_2, &readRes));
56 io.run_for(std::chrono::milliseconds(1000));
58 if (writeRes <= 0 || readRes <= 0) {
59 throw std::runtime_error(
"Unable to establish serial connection.");
61 spdlog::info(
"Serial communication established");
void testSerialPort(std::unique_ptr< boost::asio::serial_port > &serialPort, boost::asio::io_service &io)
Definition: SerialPort.h:37
std::unique_ptr< boost::asio::serial_port > initializeSerialPort(std::string serialPort, unsigned int baud, boost::asio::io_service &io)
Definition: SerialPort.h:12