57 lines
1.3 KiB
C++
57 lines
1.3 KiB
C++
#pragma once
|
|
|
|
#include <linux/can.h>
|
|
|
|
#include <atomic>
|
|
#include <functional>
|
|
#include <mutex>
|
|
#include <set>
|
|
#include <string>
|
|
#include <thread>
|
|
|
|
#include "logger.h"
|
|
|
|
class CanBus
|
|
{
|
|
public:
|
|
using ReceiveCallback = std::function<void(const can_frame &)>;
|
|
|
|
CanBus(const std::string &id, const std::string &interface_name, Logger &logger);
|
|
~CanBus();
|
|
|
|
bool start(); // 启动 CAN 接收线程并尝试初始化,失败会自动重试
|
|
void stop();
|
|
|
|
bool send_frame(const can_frame &frame);
|
|
void set_receive_callback(ReceiveCallback cb) { receive_callback_ = cb; }
|
|
|
|
bool is_running() const { return running_; }
|
|
|
|
// 黑名单管理
|
|
void add_blacklist_id(uint32_t can_id);
|
|
void remove_blacklist_id(uint32_t can_id);
|
|
void clear_blacklist();
|
|
|
|
private:
|
|
void receive_loop();
|
|
bool init_socket();
|
|
|
|
private:
|
|
std::string id_;
|
|
std::string interface_name_;
|
|
Logger &logger_;
|
|
|
|
int sockfd_ = -1;
|
|
std::atomic<bool> running_{false};
|
|
std::thread worker_;
|
|
std::mutex send_mutex_;
|
|
ReceiveCallback receive_callback_;
|
|
|
|
std::set<uint32_t> blacklist_;
|
|
std::mutex blacklist_mutex_;
|
|
|
|
// 自动重试策略
|
|
int retry_first_ = 2; // 初次失败间隔秒
|
|
int retry_max_ = 30; // 最大间隔秒
|
|
};
|