#include <boost/asio/read.hpp>
#include <boost/asio/write.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include "framework/global.h"
#include "com.h"
COM g_com;
COM::COM() : port(io_service, "COM5") {
// Configure serial port settings (move from init() to constructor)
port.set_option(boost::asio::serial_port_base::baud_rate(9600));
port.set_option(boost::asio::serial_port_base::character_size(8));
port.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none));
port.set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one));
port.set_option(boost::asio::serial_port_base::flow_control(boost::asio::serial_port_base::flow_control::none));
}
void COM::init() {
// Create io_service object
boost::asio::io_service io_service;
// Declare a buffer to store received data
// Asynchronously read data into the buffer
boost::asio::async_read(port, buffer,
[this](boost::system::error_code error, std::size_t bytes_transferred) {
if (!error) {
// Process the received data
std::istream is(&buffer);
std::string line;
while (std::getline(is, line)) {
std::cout << line << std::endl;
}
// Asynchronously read the next fragment of data
boost::asio::async_read(port, buffer,
[this](boost::system::error_code error, std::size_t bytes_transferred) {
if (!error) {
// Process the received data
g_logger.info(stdext::format("This is my output form com: %s", boost::asio::buffer_cast<const char*>(buffer.data())));
}
else {
// Error handling
g_logger.info("Error");
}
});
}
else {
// Error handling
std::cerr << "Error reading from serial port: " << error.message() << std::endl;
}
});
// Run the event loop to process asynchronous operations
io_service.run();
}
void COM::terminate() {
g_logger.info("Bye!");
}