54 lines
1.3 KiB
C
54 lines
1.3 KiB
C
|
|
#pragma once
|
||
|
|
|
||
|
|
#include <atomic>
|
||
|
|
#include <functional>
|
||
|
|
#include <mutex>
|
||
|
|
#include <string>
|
||
|
|
#include <thread>
|
||
|
|
#include <vector>
|
||
|
|
|
||
|
|
#include "logger.h"
|
||
|
|
|
||
|
|
class SerialPort
|
||
|
|
{
|
||
|
|
public:
|
||
|
|
using ReceiveCallback = std::function<void(const std::vector<uint8_t>&)>;
|
||
|
|
using ReceiveStringCallback = std::function<void(const std::string&)>;
|
||
|
|
|
||
|
|
SerialPort(const std::string& id, const std::string& device, int baudrate, Logger& logger, int retry_interval = 5);
|
||
|
|
~SerialPort();
|
||
|
|
|
||
|
|
void start(); // 启动串口(含自动重连)
|
||
|
|
void stop(); // 停止串口
|
||
|
|
|
||
|
|
bool is_open() const;
|
||
|
|
bool send_data(const std::vector<uint8_t>& data);
|
||
|
|
bool send_data(const std::string& data);
|
||
|
|
|
||
|
|
void set_receive_callback(ReceiveCallback cb);
|
||
|
|
void set_receive_callback(ReceiveStringCallback cb);
|
||
|
|
|
||
|
|
private:
|
||
|
|
bool open_port();
|
||
|
|
void close_port();
|
||
|
|
void reader_loop();
|
||
|
|
void reconnect_loop();
|
||
|
|
bool configure_port(int fd);
|
||
|
|
|
||
|
|
private:
|
||
|
|
std::string id_;
|
||
|
|
std::string device_;
|
||
|
|
int baudrate_;
|
||
|
|
int fd_ = -1;
|
||
|
|
|
||
|
|
std::atomic<bool> running_{false};
|
||
|
|
std::atomic<bool> stop_flag_{false};
|
||
|
|
std::thread reader_thread_;
|
||
|
|
std::thread reconnect_thread_;
|
||
|
|
std::mutex send_mutex_;
|
||
|
|
|
||
|
|
ReceiveCallback receive_callback_;
|
||
|
|
Logger& logger_;
|
||
|
|
int retry_interval_;
|
||
|
|
};
|