前言

本文主要介绍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;
}

View Code

解析

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.发送数据则禁止过滤;

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;

转载于:https://www.cnblogs.com/happyamyhope/p/8882568.html

can-utils源码解析cansend相关推荐

  1. Redis源码解析——前言

    今天开启Redis源码的阅读之旅.对于一些没有接触过开源代码分析的同学来说,可能这是一件很麻烦的事.但是我总觉得做一件事,不管有多大多难,我们首先要在战略上蔑视它,但是要在战术上重视它.除了一些高大上 ...

  2. dataset__getitem___PyTorch源码解析与实践(1):数据加载Dataset,Sampler与DataLoader

    献给学习PyTorch在路上或者计划较深入理解PyTorch的同行者们 写在前面 笔者一直使用tf,大势所趋决定转PyTorch,这个系列就作为我学习PyTorch的笔记与心得. 网络上PyTorch ...

  3. Android之图片加载框架Picasso源码解析

    转载请标明出处: http://blog.csdn.net/hai_qing_xu_kong/article/details/76645535 本文出自:[顾林海的博客] 个人开发的微信小程序,目前功 ...

  4. weiler-atherton多边形裁剪算法_EAST算法超详细源码解析:数据预处理与标签生成...

    作者简介 CW,广东深圳人,毕业于中山大学(SYSU)数据科学与计算机学院,毕业后就业于腾讯计算机系统有限公司技术工程与事业群(TEG)从事Devops工作,期间在AI LAB实习过,实操过道路交通元 ...

  5. Retrofit2源码解析——网络调用流程(下)

    Retrofit2源码解析系列 Retrofit2源码解析(一) Retrofit2源码解析--网络调用流程(上) 本文基于Retrofit2的2.4.0版本 implementation 'com. ...

  6. axios网络请求框架源码解析

    早期axios0.1.0版本做了对IE浏览器与包含XmlHttpRequest的浏览器的支持.并且做了对请求参数拼接.Json对象序列化等基本功能. 到0.19.0版本时,内部请求已经变为了在Node ...

  7. 【Vue.js源码解析 一】-- 响应式原理

    前言 笔记来源:拉勾教育 大前端高薪训练营 阅读建议:建议通过左侧导航栏进行阅读 课程目标 Vue.js 的静态成员和实例成员初始化过程 首次渲染的过程 数据响应式原理 – 最核心的特性之一 准备工作 ...

  8. EAST算法超详细源码解析:数据预处理与标签生成

    作者简介 CW,广东深圳人,毕业于中山大学(SYSU)数据科学与计算机学院,毕业后就业于腾讯计算机系统有限公司技术工程与事业群(TEG)从事Devops工作,期间在AI LAB实习过,实操过道路交通元 ...

  9. Kubernetes学习笔记之Calico CNI Plugin源码解析(二)

    女主宣言 今天小编继续为大家分享Kubernetes Calico CNI Plugin学习笔记,希望能对大家有所帮助. PS:丰富的一线技术.多元化的表现形式,尽在"360云计算" ...

最新文章

  1. 图像转文字(分类识别等),文字转图片,实际需要的过程
  2. 四种方法解决最大连续子序列和问题
  3. /org/gnome/Terminal/Factory0: Could not connec
  4. 命令行神器 Click 简明笔记
  5. 对一个简单汇编程序分析
  6. 【Pytorch神经网络理论篇】 26 基于空间域的图卷积GCNs(ConvGNNs):定点域+谱域+图卷积的操作步骤
  7. Kubernetes 学习总结(20)—— Kubernetes 与微服务和容器之间是什么关系?
  8. 仅用语音,AI 就能“脑补”你的脸! | 技术头条
  9. 六个角度深层区分ERP和MES的不同!
  10. tab vue 竖排_vue tab切换的几种方式
  11. 虚拟内存和swap分区的关系
  12. IntelliJ IDEA使用技巧(三)——Debug 篇
  13. 日常工作常用的几款小工具
  14. 微信朋友验证消息是什么来源_微信好友来源朋友验证消息
  15. 如何更好地读开源软件之一:ERD工具简介
  16. 计蒜客2018 ICPC SouthEastern European E. Fishermen
  17. 电阻的组成、分类及读数方法
  18. xxx.pth或者xxx.pt is a zip archive(did you mean to use torch.jit.load()?问题解决
  19. 【经典】非你莫属的名句二
  20. 互联网将如何颠覆这17个传统行业

热门文章

  1. acrobat 下拉列表 逻辑_记一次 无限列表 滚动优化
  2. .计算机自动关机或重启,电脑自动关机或者重启怎么处理
  3. 计算机专用英语词汇发音,计算机专用的英语词汇
  4. fedora java环境变量_Fedora Linux,JDK安装与配置环境变量
  5. mysql导入csvnull,MySQL Workbench从CSV导入NULL
  6. WEB入门之二十 插件
  7. Cookie和Session的区别详解
  8. Kafka的优化建议
  9. Java读取resource文件/路径的几种方式
  10. 谈谈spark.sql.shuffle.partitions和 spark.default.parallelism 的区别及spark并行度的理解