can-utils源码解析cansend
前言
本文主要介绍socketCan中的发送函数cansend的源码解析.
代码

/* * cansend.c - simple command line tool to send CAN-frames via CAN_RAW sockets * * Copyright (c) 2002-2007 Volkswagen Group Electronic Research * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Volkswagen nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * Alternatively, provided that this notice is retained in full, this * software may be distributed under the terms of the GNU General * Public License ("GPL") version 2, in which case the provisions of the * GPL apply INSTEAD OF those given above. * * The provided data structures and external interfaces from this code * are not restricted to be used by modules with a GPL compatible license. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * Send feedback to <linux-can@vger.kernel.org> * */ #include <stdio.h> #include <stdlib.h> #include <string.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> #include "lib.h" int main( ) { int s; /* can raw socket */ int required_mtu; int mtu; int enable_canfd = 1; struct sockaddr_can addr; struct canfd_frame frame; struct ifreq ifr; char* input = "008#abcd1234cdef567830"; /* parse CAN frame */ required_mtu = parse_canframe(input, &frame); printf("required_mtu is %d\n", required_mtu); printf("CAN_MTU is %d\n", (long unsigned int)CAN_MTU); //printf("CANID_DELIM is %d\n", CANID_DELIM);//#-35-0x23. printf("IFNAMSIZ is %d\n", IFNAMSIZ); if (!required_mtu){ fprintf(stderr, "\nWrong CAN-frame format! Try:\n\n"); fprintf(stderr, " <can_id>#{R|data} for CAN 2.0 frames\n"); fprintf(stderr, " <can_id>##<flags>{data} for CAN FD frames\n\n"); fprintf(stderr, "<can_id> can have 3 (SFF) or 8 (EFF) hex chars\n"); fprintf(stderr, "{data} has 0..8 (0..64 CAN FD) ASCII hex-values (optionally"); fprintf(stderr, " separated by '.')\n"); fprintf(stderr, "<flags> a single ASCII Hex value (0 .. F) which defines"); fprintf(stderr, " canfd_frame.flags\n\n"); fprintf(stderr, "e.g. 5A1#11.2233.44556677.88 / 123#DEADBEEF / 5AA# / "); fprintf(stderr, "123##1 / 213##311\n 1F334455#1122334455667788 / 123#R "); fprintf(stderr, "for remote transmission request.\n\n"); return 1; } /* open socket */ if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) { perror("socket"); return 1; } const char* ifrname = "can1"; strcpy(ifr.ifr_name, ifrname); ifr.ifr_ifindex = if_nametoindex(ifr.ifr_name); if (!ifr.ifr_ifindex) { perror("if_nametoindex"); return 1; } memset(&addr, 0, sizeof(addr)); addr.can_family = AF_CAN; addr.can_ifindex = ifr.ifr_ifindex; /* if (required_mtu > CAN_MTU) { //* check if the frame fits into the CAN netdevice if (ioctl(s, SIOCGIFMTU, &ifr) < 0) { perror("SIOCGIFMTU"); return 1; } mtu = ifr.ifr_mtu; if (mtu != CANFD_MTU) { printf("CAN interface is not CAN FD capable - sorry.\n"); return 1; } //* interface is ok - try to switch the socket into CAN FD mode if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &enable_canfd, sizeof(enable_canfd))){ printf("error when enabling CAN FD support\n"); return 1; } //* ensure discrete CAN FD length values 0..8, 12, 16, 20, 24, 32, 64 frame.len = can_dlc2len(can_len2dlc(frame.len)); } */ /* disable default receive filter on this RAW socket */ /* This is obsolete as we do not read from the socket at all, but for */ /* this reason we can remove the receive list in the Kernel to save a */ /* little (really a very little!) CPU usage. */ setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0); if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind"); return 1; } /* send frame */ printf("frame.len is %d\n", frame.len); printf("frame.can_id is %x\n", frame.can_id); if (write(s, &frame, required_mtu) != required_mtu) { perror("write"); return 1; } close(s); return 0; }
解析
1.message的格式;
char* input = "008#abcd1234cdef567830";
其中‘008表示can_id,必须是三位十六进制数据,可以表示标准帧或者扩展帧;符号#“是can_id和can数据的分界符,最后的数据是报文的数据,标准帧一次最多只能发送8bits的数据,多余的数据自动丢弃;
2.parse_canframe函数,具体内容可参考lib.h和lib.c文件;
int parse_canframe(char *cs, struct canfd_frame *cf);
/* parse CAN frame */
required_mtu = parse_canframe(input, &frame);
function -- Transfers a valid ASCII string decribing a CAN frame into struct canfd_frame.
3.创建socket;
s = socket(PF_CAN, SOCK_RAW, CAN_RAW)
创建socket套接字
PF_CAN 为域位,同网络编程中的AF_INET,即ipv4协议;
SOCK_RAW使用的协议类型,SOCK_RAW表示原始套接字,报文头由自己创建;
CAN_RAW为使用的具体协议,为can总线协议;
4. 指定can口名称;
const char* ifrname = "can1";
5.设置过滤规则;发送数据则禁用过滤;
在数据接收时,系统可以根据预先设置的过滤规则,实现对报文的过滤。过滤规则使用can_filter结构体来实现,定义如下:
struct can_filter { canid_t can_id; canid_t can_mask; };
通过过滤规则可以在系统中过滤掉所有不符合规则的报文,使得应用程序不需要对无关的报文进行处理。在can_filter结构的can_id中,符号位CAN_INV_FILTER在置位时可以实现can_id在执行过滤前的位反转。用户可以为每个打开的套接字设置多条独立的过滤规则。
struct can_filter rfilter[2]; rfilter[0].can_id = 0x123; rfilter[0].can_mask = CAN_SFF_MASK; // #define CAN_SFF_MASK 0x000007FFU rfilter[1].can_id = 0x200; rfilter[1].can_mask = 0x700; setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter)); // 设置规则
在极端情况下,如果应用程序不需要接收报文,可以禁用过滤规则。这样的话,原始套接字就会忽略所有接收到的报文。在这种仅仅发送数据的应用中,可以在内核中省略接收队列,以此减少CPU资源的消耗。
setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0); //Disable filter.
6.绑定socketCan;
bind(s, (struct sockaddr *)&addr, sizeof(addr)
bind函数用于绑定套接字,即将套接字和canbus外设进行绑定;
7.发送数据;
/* send frame */ if (write(s, &frame, required_mtu) != required_mtu) { //发送数据! perror("write"); return 1; }
8.数据格式的定义;
struct can_frame { canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */ __u8 can_dlc; /* frame payload length in byte (0 .. CAN_MAX_DLEN) */ __u8 __pad; /* padding */ __u8 __res0; /* reserved / padding */ __u8 __res1; /* reserved / padding */ __u8 data[CAN_MAX_DLEN] __attribute__((aligned(8))); }; struct canfd_frame { canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */ __u8 len; /* frame payload length in byte */ __u8 flags; /* additional flags for CAN FD */ __u8 __res0; /* reserved / padding */ __u8 __res1; /* reserved / padding */ __u8 data[CANFD_MAX_DLEN] __attribute__((aligned(8))); }; #define CAN_MTU (sizeof(struct can_frame)) #define CANFD_MTU (sizeof(struct canfd_frame))
struct can_frame - basic CAN frame structure;
struct canfd_frame - CAN flexible data rate frame structure;
参考
1. linux平台can总线编程模型;
2. can-utils-git;
3. Linux Socket CAN——数据发送接收流程;
完
心正意诚,做自己该做的事情,做自己喜欢做的事情,安静做一枚有思想的技术媛。
版权声明,转载请注明出处:https://www.cnblogs.com/happyamyhope/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】