118 lines
2.7 KiB
C
118 lines
2.7 KiB
C
#include <stdio.h>
|
||
#include <stdint.h>
|
||
#include <string.h>
|
||
#include <stdlib.h>
|
||
#include <unistd.h>
|
||
#include <net/if.h>
|
||
#include <sys/ioctl.h>
|
||
#include <sys/socket.h>
|
||
#include <linux/can.h>
|
||
#include <linux/can/raw.h>
|
||
|
||
int sockfd_can0;
|
||
|
||
int socket_can_init(char* can_dev)
|
||
{
|
||
int sockfd_can;
|
||
struct ifreq ifr;
|
||
struct sockaddr_can addr;
|
||
|
||
sockfd_can = socket(PF_CAN, SOCK_RAW, CAN_RAW);
|
||
if (sockfd_can < 0) {
|
||
perror("Error while opening socket");
|
||
return -1;
|
||
}
|
||
|
||
strcpy(ifr.ifr_name, can_dev);
|
||
ioctl(sockfd_can, SIOCGIFINDEX, &ifr);
|
||
|
||
// 绑定 CAN 套接字到接口
|
||
addr.can_family = AF_CAN;
|
||
addr.can_ifindex = ifr.ifr_ifindex;
|
||
if (bind(sockfd_can, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
|
||
perror("Error in socket bind");
|
||
return -2;
|
||
}
|
||
|
||
return sockfd_can;
|
||
}
|
||
|
||
int socket_can_send(int sockfd,uint32_t can_id,uint8_t data[8])
|
||
{
|
||
struct can_frame frame;
|
||
// 准备发送的 CAN 帧
|
||
frame.can_id = can_id; // 11位标准帧ID
|
||
frame.can_dlc = 8; // 数据长度为8字节
|
||
|
||
// 使用循环赋值 CAN 数据帧
|
||
for (int i = 0; i < frame.can_dlc; i++)
|
||
{
|
||
frame.data[i] = data[i]; // 将数据从0x01到0x08依次赋值
|
||
}
|
||
|
||
if (write(sockfd, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) {
|
||
perror("Write error");
|
||
return -3;
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
int socket_can_close(int sockfd)
|
||
{
|
||
// 关闭套接字
|
||
close(sockfd);
|
||
return -1;
|
||
}
|
||
|
||
|
||
int test() {
|
||
int sockfd;
|
||
struct sockaddr_can addr;
|
||
struct ifreq ifr;
|
||
struct can_frame frame;
|
||
|
||
// 创建 CAN 套接字
|
||
sockfd = socket(PF_CAN, SOCK_RAW, CAN_RAW);
|
||
if (sockfd < 0) {
|
||
perror("Error while opening socket");
|
||
return -1;
|
||
}
|
||
|
||
// 指定 CAN 接口(假设为 can0)
|
||
strcpy(ifr.ifr_name, "can0");
|
||
ioctl(sockfd, SIOCGIFINDEX, &ifr);
|
||
|
||
// 绑定 CAN 套接字到接口
|
||
addr.can_family = AF_CAN;
|
||
addr.can_ifindex = ifr.ifr_ifindex;
|
||
if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
|
||
perror("Error in socket bind");
|
||
return -2;
|
||
}
|
||
|
||
// 准备发送的 CAN 帧
|
||
frame.can_id = 0x123; // 11位标准帧ID
|
||
frame.can_dlc = 8; // 数据长度为8字节
|
||
// 使用循环赋值 CAN 数据帧
|
||
for (int i = 0; i < frame.can_dlc; i++)
|
||
{
|
||
frame.data[i] = i + 1; // 将数据从0x01到0x08依次赋值
|
||
}
|
||
|
||
|
||
// 发送 CAN 帧
|
||
for(int i=0;i<3;i++)
|
||
{
|
||
if (write(sockfd, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) {
|
||
perror("Write error");
|
||
return -3;
|
||
}
|
||
|
||
}
|
||
|
||
printf("CAN message sent on can0\n");
|
||
// 关闭套接字
|
||
close(sockfd);
|
||
|
||
return 0;
|
||
} |