#include "controller.hpp"

Can_socket::Can_socket()
{
    can_fd = -1;
}

Can_socket::~Can_socket()
{
    close(can_fd);
}

void Can_socket::init(const string can_name)
{
    // system(down);
    // system(command);
    // system(up); // 上面三行关闭CAN设备，设置波特率后，重新打开CAN设备

    can_fd = socket(AF_CAN, SOCK_RAW, CAN_RAW);
    if (can_fd < 0)
    {
        cout << "can初始化失败!" << endl;
        return;
    }

    // 绑定 can设备与 socket
    struct ifreq ifr; // if.h
    strcpy(ifr.ifr_name, can_name.c_str());
    ioctl(can_fd, SIOCGIFINDEX, &ifr); // 指定编号为 can_name 的设备，获取设备索引

    struct sockaddr_can addr;
    addr.can_family = AF_CAN;           // 指定协议族
    addr.can_ifindex = ifr.ifr_ifindex; // 设备索引
    // 将套接字与 can_name 绑定
    int bind_res = bind(can_fd, (struct sockaddr *)&addr, sizeof(addr));
    if (bind_res < 0)
    {
        cout << "套接字绑定失败!" << endl;
        return;
    }
}

int Can_socket::can_read(struct can_frame *frame)
{
    int n = read(can_fd, frame, sizeof(struct can_frame));
    return n;
}

int Can_socket::can_write(struct can_frame *frame)
{
    int n = write(can_fd, frame, sizeof(struct can_frame));
    return n;
}

void Can_socket::set_rfilter(canid_t can_mask, canid_t can_id1, canid_t can_id2, canid_t can_id3, canid_t can_id4)
{
    struct can_filter rfilter[4];
    rfilter[0].can_id = can_id1;
    rfilter[0].can_mask = can_mask;
    rfilter[1].can_id = can_id2;
    rfilter[1].can_mask = can_mask;
    rfilter[2].can_id = can_id3;
    rfilter[2].can_mask = can_mask;
    rfilter[3].can_id = can_id4;
    rfilter[3].can_mask = can_mask;
    // cout << "can_fd" << can_fd << endl;
    setsockopt(can_fd, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
}