// // Created by casic on 25-2-25. // #include "serial_port_wrapper.hpp" #include <iomanip> #include <iostream> void handle_data(const std::vector<uint8_t> &buffer) { const auto x = buffer[2] & 0xFFFF; const auto y = buffer[3] & 0xFFF; const auto z = buffer[4] & 0xFF; const auto w = buffer[5]; const auto result = x + y + z + w; std::cout << "methane concentration: " << result << " ppm·m" << std::endl; //http上传数据 } SerialPortWrapper::SerialPortWrapper( boost::asio::io_service &io_service, const std::string &port_name, const int baud_rate ): io_service_(io_service), port_(io_service, port_name), timer_(io_service) { port_.set_option(serial_port_base::baud_rate(baud_rate)); port_.set_option(serial_port_base::character_size(8)); port_.set_option(serial_port_base::parity(serial_port_base::parity::none)); port_.set_option(serial_port_base::stop_bits(serial_port_base::stop_bits::one)); start_timer(); } void SerialPortWrapper::start_timer() { timer_.expires_from_now(boost::posix_time::seconds(3)); timer_.async_wait([this](const boost::system::error_code &error) { if (!error) { read_from_port(); } }); } //CC 05 00 00 00 00 0D 77 void SerialPortWrapper::read_from_port() { async_read_until( port_, buffer_, 0x77, [this](const boost::system::error_code &error, const size_t bytes_transferred) mutable { if (!error) { // 获取接收到的数据 std::istream is(&buffer_); std::vector<uint8_t> received_data(static_cast<std::streamsize>(bytes_transferred)); is.read( reinterpret_cast<char *>(received_data.data()), static_cast<std::streamsize>(bytes_transferred) ); // std::cout << "received " << bytes_transferred << " bytes: "; // for (size_t i = 0; i < bytes_transferred; ++i) { // std::cout << std::hex // << std::uppercase // << std::setw(2) // << std::setfill('0') // << static_cast<int>(received_data[i]) // << " "; // } // std::cout << std::endl; handle_data(received_data); start_timer(); } else { std::cerr << "error: " << error.message() << std::endl; start_timer(); } }); }