#include "drv_can.h" void can_recv(char cannum[], unsigned int canID[], int canIDnum, int dataLength) { struct sockaddr_can addr; struct can_frame frame; struct can_frame frame_send; int s; int nbytes; struct can_filter filters[canIDnum]; s = socket(PF_CAN, SOCK_RAW, CAN_RAW); if (s < 0) { perror("Socket creation failed"); exit(EXIT_FAILURE); } printf("创建Can_recv_Socket sucess\n"); memset(&addr, 0, sizeof(struct sockaddr_can)); addr.can_family = AF_CAN; addr.can_ifindex = if_nametoindex(cannum); // 设置can接口 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("Binding failed"); exit(EXIT_FAILURE); } printf("连接CAN设备 sucess\n"); // 设置发送帧的参数,使用传入的canID和数据长度 frame_send.can_id = 0x123456; frame_send.can_dlc = dataLength; memset(frame_send.data, 0, dataLength); frame_send.data[0] = 0x11; frame_send.data[1] = 0x22; // 设置过滤规则,只接收指定canID的帧 for(int i = 0; i < canIDnum; i++) { filters[i].can_id = canID[i]; filters[i].can_mask = 0x7FF; // 这里的掩码根据实际需求设置,0x7FF表示只匹配canID的低11位 } if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, filters, sizeof(filters)) < 0) { perror("Setting filter failed"); exit(EXIT_FAILURE); } nbytes = read(s, &frame, sizeof(struct can_frame)); if (nbytes < 0) { perror("Read failed"); exit(EXIT_FAILURE); } int match_found = 0; for (int i = 0; i < canIDnum; i++) { if ((frame.can_id & filters[i].can_mask) == filters[i].can_id) { match_found = 1; break; } } if (match_found) { printf("Received %d bytes: CAN ID 0x%X, Data: ", nbytes, frame.can_id); for (int i = 0; i < frame.can_dlc; i++) { printf("%02X ", frame.data[i]); } printf("\n"); // nbytes = write(s, &frame_send, sizeof(struct can_frame)); // if (nbytes < 0) { // perror("Send failed"); // exit(EXIT_FAILURE); // } // printf("Sent %d bytes: CAN ID 0x%X, Data: ", nbytes, frame_send.can_id); // for (int i = 0; i < frame_send.can_dlc; i++) { // printf("%02X ", frame_send.data[i]); // } // printf("\n"); } close(s); } void can_send(char cannum[], unsigned int canID, char* dataToSend, int dataLength) { struct sockaddr_can addr; struct can_frame frame_send; int s; s = socket(PF_CAN, SOCK_RAW, CAN_RAW); if (s < 0) { perror("Socket creation failed for sending"); exit(EXIT_FAILURE); } printf("create the can_send socket success!\n"); memset(&addr, 0, sizeof(struct sockaddr_can)); addr.can_family = AF_CAN; addr.can_ifindex = if_nametoindex(cannum); if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("Binding failed for sending"); exit(EXIT_FAILURE); } // 设置发送帧的参数 frame_send.can_id = canID; frame_send.can_dlc = dataLength; memset(frame_send.data, 0, dataLength); for (int i = 0; i < dataLength; i++) { frame_send.data[i] = dataToSend[i]; } int nbytes = write(s, &frame_send, sizeof(struct can_frame)); if (nbytes < 0) { perror("Send failed"); exit(EXIT_FAILURE); } printf("Sent %d bytes: CAN ID 0x%X, Data: ", nbytes, frame_send.can_id); for (int i = 0; i < frame_send.can_dlc; i++) { printf("%02X ", frame_send.data[i]); } printf("\n"); close(s); }