socketcan ISOTP 使用

本文介绍了一种在嵌入式系统中使用ISOTP协议的方法,具体包括通过socket编程实现CAN总线上的ISOTP协议栈。文章详细描述了如何初始化socket连接并设置ISOTP选项,以及如何发送请求消息并接收响应。
交叉编译使用arm-linux-gcc 就要拷贝isotp.h到交叉编译其的include目录下,我们这里是
/opt/armgcc/4.4.3/arm-none-linux-gnueabi/sys-root/usr/include/linux/can/


#include <errno.h>
#include <getopt.h>
#include <libgen.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <stdint.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <linux/can.h>
#include <linux/can/isotp.h>
#define PF_CAN 29
#define AF_CAN PF_CAN
int Init()
{
 if ((s = socket(PF_CAN, SOCK_DGRAM, CAN_ISOTP)) < 0) {
  perror("socket"); return 1;
 }
    __u32 force_rx_stmin = 0;
    static struct can_isotp_options opts;
    static struct can_isotp_fc_options fcopts;
    setsockopt(s, SOL_CAN_ISOTP, CAN_ISOTP_OPTS, &opts, sizeof(opts));
    setsockopt(s, SOL_CAN_ISOTP, CAN_ISOTP_RECV_FC, &fcopts, sizeof(fcopts));
    if (opts.flags & CAN_ISOTP_FORCE_RXSTMIN)
     setsockopt(s, SOL_CAN_ISOTP, CAN_ISOTP_RX_STMIN, &force_rx_stmin, sizeof(force_rx_stmin));
 addr.can_family = AF_CAN;
 strcpy(ifr.ifr_name, "can0");
 if (ioctl(s, SIOCGIFINDEX, &ifr)) {
  close(s);
  perror("ioctl"); return 1;
 }
 addr.can_ifindex = ifr.ifr_ifindex;
 
 addr.can_addr.tp.tx_id = src;
 addr.can_addr.tp.rx_id = trgt;
 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
  close(s);
  perror("bind"); return 1;
 }
 memset(buffer,0,sizeof(buffer));
 return 0;
}
int Request(unsigned char *msg)
{
 int nbytes = 0;
 memset(buffer,0,sizeof(buffer));
 fd_set read_fdst;
 struct timeval tv;
 int nfds;
  int rewrite_count = 0;
  do
  {
  FD_ZERO(&read_fdst);
  FD_SET(s,&read_fdst);
  tv.tv_sec = 0;
  tv.tv_usec = 50*1000; // 50*1000;
   write(s, msg, sizeof(msg));
  nfds = select(s+1,&read_fdst,NULL,NULL,&tv);
  switch(nfds)
  {
   case -1: printf("select err\n"); return -1;
   case 0: printf("select timeout\n");rewrite_count++; usleep(50*1000);break;
   default:
     if ((nbytes = read(s, buffer, BUFFSIZE)) < 0) {
      perror("read");
      return -1;
     }
     return nbytes;
  }
  }while(rewrite_count < 10);
 return -1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值