Newer
Older
casic_unitree_dog / src / serial_port_wrapper.cpp
//
// 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, std::chrono::seconds(3)) {
    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));
}

//CC 05 00 00 00 00 0D 77
void SerialPortWrapper::read_from_port(boost::asio::streambuf &buffer) {
    async_read_until(
        port_, buffer, 0x77, //结束位,一定要匹配
        [this,&buffer](const boost::system::error_code &error, const size_t bytes_transferred) {
            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);

                // 递归调用以继续读取数据
                read_from_port(buffer);
            } else {
                std::cerr << "error: " << error.message() << std::endl;
            }
        }
    );
}