问题描述
我想知道是否有办法使用 socket can 的广播管理器来修改循环任务。我正在编写一段从缓冲区读取数据的代码,然后将其写入虚拟罐接口。因此,我想创建一个循环任务,但数据框的内容可能随时更改。我能够创建循环任务,但希望能够在运行时修改结构的数据字段。这是我当前代码的示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <net/if.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/can.h>
#include <linux/can/raw.h>
#include <linux/can/bcm.h>
int main(void)
{
struct sockaddr_can addr;
struct ifreq ifr;
const char *ifname = "vcan0";
int s;
if((s = socket(PF_CAN,SOCK_DGRAM,CAN_BCM)) == -1) {
perror("Error while opening socket");
return -1;
}
strcpy(ifr.ifr_name,ifname);
ioctl(s,SIocgIFINDEX,&ifr);
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
printf("%s at index %d\n",ifname,ifr.ifr_ifindex);
if(connect(s,(struct sockaddr *)&addr,sizeof(addr)) == -1) {
perror("Error in socket bind");
return -2;
}
struct {
struct bcm_msg_head bc_manager;
struct can_frame frame;
} msg;
// Transmit data
msg.bc_manager.opcode= TX_SETUP;
// Start timer| Frame id is the same as CAN id
msg.bc_manager.flags= SETTIMER|STARTTIMER|TX_CP_CAN_ID;
msg.bc_manager.ival2.tv_usec = 1000000;
msg.bc_manager.ival2.tv_sec = 0;
msg.bc_manager.can_id = 0x123;
msg.bc_manager.nframes = 1;
// Number of send iterations
msg.bc_manager.count = 0;
msg.frame.can_dlc=8;
__u8 data_temp[8] = {0x00,0x28,0xFF,0x00,0x01,0x00};
memcpy(msg.frame.data,data_temp,8);
int nbytes = write(s,&msg,sizeof(msg));
printf("Wrote %d bytes\n",nbytes);
while(1)
{
__u8 new_data_temp[8] = {0x00,0x18,0x3F,0x00};
memcpy(msg.frame.data,new_data_temp,8);
usleep(3000000);
}
return 0;
}
当我使用 candump 查看虚拟罐上写的内容时,而不是在第一次发送后看到数据字段发生变化:
vcan0 123 [8] 00 28 FF 00 00 01 FF 00
vcan0 123 [8] 00 28 FF 00 00 01 FF 00
vcan0 123 [8] 00 28 FF 00 00 01 FF 00
vcan0 123 [8] 00 28 FF 00 00 01 FF 00
vcan0 123 [8] 00 28 FF 00 00 01 FF 00
vcan0 123 [8] 00 28 FF 00 00 01 FF 00
vcan0 123 [8] 00 28 FF 00 00 01 FF 00
vcan0 123 [8] 00 28 FF 00 00 01 FF 00
vcan0 123 [8] 00 28 FF 00 00 01 FF 00
vcan0 123 [8] 00 28 FF 00 00 01 FF 00
...
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)