0

Программа должна оправлять сообщения по CAN-у с заданным интервалом и принимать их.

Вот код:

/*
Broadcast Manager Cyclic Demo

This program demonstrates sending a set of cyclic messages out on to the CAN
bus using SocketCAN's Broadcast Manager interface. The intended behavior of
this program is to send four cyclic messages out on to the CAN bus. These
messages have IDs ranging from 0x0C0 to 0x0C3. These messages will be sent out
one at a time every 1200 milliseconds. Once all messages have been sent,
transmission will begin again with message 0x0C0.
*/

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <net/if.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>

#include <linux/can.h>
#include <linux/can/bcm.h>

#define PROGNAME "socketcan-bcm-demo"
#define VERSION  "1.0.0"

#define MSGID   (0x0C0)
#define MSGLEN  (3)
#define NFRAMES (4)

#define DELAY (10000)

void start(int argc, char *argv);
static sig_atomic_t sigval;

static void onsig(int val)
{
    sigval = (sig_atomic_t)val;
}

void processFrame(const struct canfd_frame frame) {
    int len = 0;
    unsigned char data[8];

    printf("CAN ID : %d \n", frame.can_id);
    printf("frame.can_id : %03X \n", frame.can_id );
    printf("LEN : %d \n", frame.len); len = frame.len;
    printf("len = %d \n", len);
    printf("DATA : ");
    for(int i=0; i<len; i++)
        printf(" [%u] ", frame.data[i]);
    printf("\n");
    for(int i=0; i<len; i++)
        data[i] = frame.data[i];
    printf("data : ");
    for(int i=0; i<len; i++)
        printf(" [%u] ", data[i]);
    printf("\n ---------------- \n");
}

int main(int argc, char **argv)
{
    if(argc == 1){
        start(2, "can0");}
    else {
        if (argc < 2)
        {
            fputs("Too few arguments!\n", stderr);
            usage();
            return EXIT_FAILURE;
        }
        start(argc, argv);
    }
}

void start(int argc, char *argv)
{
    unsigned int i;
    int opt;
    int s;
    char *iface;
    struct sockaddr_can addr;
    struct ifreq ifr;
    printf("start %d \n", 1);
    struct can_msg
    {
        struct bcm_msg_head msg_head;
        struct can_frame frame[NFRAMES];
    } msg;
    struct canfd_frame frame;  // для приёма сообщений
    printf("start %d \n", 2);
    /* Check if at least one argument was specified */
    if (argc < 2)
    {
        fputs("Too few arguments!\n", stderr);
        usage();
        return EXIT_FAILURE;
    }
    printf("start %d \n", 3);


    printf("start %d \n", 4);
    iface = argv[0];


    printf("start %d \n", 5);
    /* Register signal handlers  можно заблокировать */
    if (signal(SIGINT, onsig)    == SIG_ERR ||
            signal(SIGTERM, onsig)   == SIG_ERR ||
            signal(SIGCHLD, SIG_IGN) == SIG_ERR)
    {
        perror(PROGNAME);
        return errno;
    }

    printf("start %d \n", 6);
    /* Open the CAN interface */
    s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
    if (s < 0)
    {
        perror(PROGNAME ": socket");
        return errno;
    }
    //    printf("start %d \n", 7);
    printf("start %d \n", 7);
    if(strlen(iface)>=IFNAMSIZ)
    {
        printf("device name is error.\n");
        return errno;
    }
    strcpy(ifr.ifr_name,iface);


    //    strncpy(ifr.ifr_name, iface, IFNAMSIZ);
    //    if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
    //    {
    //        perror(PROGNAME ": ioctl");
    //        return errno;
    //    }
    printf("start %d \n", 8);
    addr.can_family = AF_CAN;
    addr.can_ifindex = ifr.ifr_ifindex;
    if (connect(s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
    {
        perror(PROGNAME ": connect");
        return errno;
    }
    printf("start %d \n", 9);
    /* Setup code */
    sigval = 0;

    /* Set up cyclic messages. Note that both SETTIMER and STARTTIMER are
     * required as flags in order to continue transmitting.
     */
    msg.msg_head.opcode  = TX_SETUP; // TX_SEND;
    msg.msg_head.can_id  = 0;
    msg.msg_head.flags   = SETTIMER | STARTTIMER; // RX_NO_AUTOTIMER
    msg.msg_head.nframes = NFRAMES;
    msg.msg_head.count   = 0;

    //    /* Set the time interval value to 1200 ms */
    msg.msg_head.ival2.tv_sec = 1;
    msg.msg_head.ival2.tv_usec = 200000;

    /* Create the example messages */
    for (i = 0; i < NFRAMES; ++i)
    {
        struct can_frame * const frame = msg.frame + i;
        frame->can_id = MSGID + i;
        frame->can_dlc = MSGLEN;
        memset(frame->data, i, MSGLEN);
    }

    /* Register the cyclic messages. Note that all of the messages in the msg
     * struct will be sent with the same periodicity because they share the
     * same bcm_msg_head setup data.
     */
    int numBytes =  read(s, &frame, CAN_MTU);
    switch (numBytes)
    {
    case CAN_MTU:
        processFrame(frame);
        break;
    case CANFD_MTU:
        // TODO: Should make an example for CAN FD создай функцию для считывания КАН ФД сообщений
        break;
    case -1:
        // Check the signal value on interrupt проверяем значение сигнала и прерывание
        if (EINTR == errno)
            break;
        // Delay before continuing маленькое тороможение
        perror("not read");
        usleep(100);
    default:
        break;
    }


    if (write(s, &msg, sizeof(msg)) < 0)
    {
        perror(PROGNAME ": write: TX_SETUP");
        return errno;
    }
    printf("start %d \n", 10);
    printf("Cyclic messages registed with SocketCAN!\n"
           "Use a tool such as \"candump %s\" to view the messages.\n"
           "These messages will continue to transmit so long as the socket\n"
           "used to communicate with SocketCAN remains open. In other words,\n"
           "close this program with SIGINT or SIGTERM in order to gracefully\n"
           "stop transmitting.\n",
           iface);

    /* Spin forever here */
    while (0 == sigval) usleep(DELAY);

    puts("\nGoodbye!");

    /* Close the CAN interface */
    if (close(s) < 0)
    {
        perror(PROGNAME ": close");
        return errno;
    }

    return EXIT_SUCCESS;
}

Между printf(7) и printf(8) происходит Segmentation fault немогу понять почему "выпрыгивает" такая проблемма.

Все прекрасное работало пока я не добавил в код, приём сообщений.

Вот что я вставил (после чего и появилась ошибка):

     ... 
    /* Register the cyclic messages. Note that all of the messages in the msg
         * struct will be sent with the same periodicity because they share the
         * same bcm_msg_head setup data.
         */
        int numBytes =  read(s, &frame, CAN_MTU);
        switch (numBytes)
        {
        case CAN_MTU:
            processFrame(frame);
            break;
        case CANFD_MTU:
            // TODO: Should make an example for CAN FD создай функцию для считывания КАН ФД сообщений
            break;
        case -1:
            // Check the signal value on interrupt проверяем значение сигнала и прерывание
            if (EINTR == errno)
                break;
            // Delay before continuing маленькое тороможение
            perror("not read");
            usleep(100);
        default:
            break;
        }

   ...

void processFrame(const struct canfd_frame frame) {
    int len = 0;
    unsigned char data[8];

    printf("CAN ID : %d \n", frame.can_id);
    printf("frame.can_id : %03X \n", frame.can_id );
    printf("LEN : %d \n", frame.len); len = frame.len;
    printf("len = %d \n", len);
    printf("DATA : ");
    for(int i=0; i<len; i++)
        printf(" [%u] ", frame.data[i]);
    printf("\n");
    for(int i=0; i<len; i++)
        data[i] = frame.data[i];
    printf("data : ");
    for(int i=0; i<len; i++)
        printf(" [%u] ", data[i]);
    printf("\n ---------------- \n");
}

вот структура для приёма сообщений struct canfd_frame frame;

её обьявление в файле can.h :

/**
 * struct canfd_frame - CAN flexible data rate frame structure
 * @can_id: CAN ID of the frame and CAN_*_FLAG flags, see canid_t definition
 * @len:    frame payload length in byte (0 .. CANFD_MAX_DLEN)
 * @flags:  additional flags for CAN FD
 * @__res0: reserved / padding
 * @__res1: reserved / padding
 * @data:   CAN FD frame payload (up to CANFD_MAX_DLEN byte)
 */
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)));
};

вот структура для отправки сообщений :

struct can_msg
{
    struct bcm_msg_head msg_head;
    struct can_frame frame[NFRAMES];
} msg;  

вот объявление bcm_msg_head в файле bcm.h :

/**
 * struct bcm_msg_head - head of messages to/from the broadcast manager
 * @opcode:    opcode, see enum below.
 * @flags:     special flags, see below.
 * @count:     number of frames to send before changing interval.
 * @ival1:     interval for the first @count frames.
 * @ival2:     interval for the following frames.
 * @can_id:    CAN ID of frames to be sent or received.
 * @nframes:   number of frames appended to the message head.
 * @frames:    array of CAN frames.
 */
struct bcm_msg_head {
    __u32 opcode;
    __u32 flags;
    __u32 count;
    struct bcm_timeval ival1, ival2;
    canid_t can_id;
    __u32 nframes;
    struct can_frame frames[0];
};

вот объявление can_frame в файле can.h :

/**
 * struct can_frame - basic CAN frame structure
 * @can_id:  CAN ID of the frame and CAN_*_FLAG flags, see canid_t definition
 * @can_dlc: frame payload length in byte (0 .. 8) aka data length code
 *           N.B. the DLC field from ISO 11898-1 Chapter 8.4.2.3 has a 1:1
 *           mapping of the 'data length code' to the real payload length
 * @__pad:   padding
 * @__res0:  reserved / padding
 * @__res1:  reserved / padding
 * @data:    CAN frame payload (up to 8 byte)
 */
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)));
};
4
  • int numBytes = read(s, &frame, CAN_MTU); Здесь CAN_MTU == size_of(frame)? 21 июн 2019 в 12:33
  • @AntonShchyrov CAN_MTU определен в файле can.hи выглядит так #define CAN_MTU (sizeof(struct can_frame))
    – timob256
    21 июн 2019 в 12:42
  • А frame здесь у вас имеет тип canfd_frame. Они имеют разные размеры или одинаковые? 21 июн 2019 в 12:48
  • @AntonShchyrov обновил вопрос , флаг ` CAN FD ` не включён . Так что предположу что одинаковый , притом замечу что по сути в linux-е при передачи КАН кадров, используется стандартный изернетовский кадр (если работаем через стандартную сетевую библиотеку ).
    – timob256
    21 июн 2019 в 13:04

1 ответ 1

0

Предполагаю не работу кода именно с тем на что ссылался @AntonShchyrov на разницу структур (void processFrame(const struct canfd_frame frame), struct can_frame * const frame = msg.frame + i; ), на сейчашний момент также предполагаю проблему именно в разнице отправляемых и принимаемых структур ( после прочтения определенного количества теории)


В общем вот код. По цели выполняет то что я и задумал (принимает и отправляет сообщения).

НО по исполнению заметил есть отлития. Хоть использую такие-же механизмы в коде не используется некоторые структуры такие как отправка по времени, а также механизм сигналов, код несколько упрощен в сравнение с "кодом с верху".

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <net/if.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>

#include <linux/can.h>
#include <linux/can/bcm.h>


void processFrame(struct can_frame frame) {
    int len = 0;
    unsigned char data[8];

    printf("CAN ID : %d \n", frame.can_id);
    printf("frame.can_id : %03X \n", frame.can_id );
    printf("LEN : %d \n", frame.can_dlc); len = frame.can_dlc;
    printf("len = %d \n", len);
    printf("DATA : ");
    for(int i=0; i<len; i++)
        printf(" [%u] ", frame.data[i]);
    printf("\n");
    for(int i=0; i<len; i++)
        data[i] = frame.data[i];
    printf("data : ");
    for(int i=0; i<len; i++)
        printf(" [%u] ", data[i]);
    printf("\n ---------------- \n");
    //     for (int i = 0; i < frame.len; ++i)
    //        {
    //            printf(" %02X", frame.data[i]);
    //        }
    //---//
}

/* omitted vital #includes and error checking */

int main(int argc, char **argv)
{
    struct ifreq ifr;
    struct sockaddr_can addr;
    struct can_frame frame;
    struct can_frame frame1;

    int s;

    memset(&ifr, 0x0, sizeof(ifr));
    memset(&addr, 0x0, sizeof(addr));
    memset(&frame, 0x0, sizeof(frame));
    memset(&frame1, 0x0, sizeof(frame));


    /* open CAN_RAW socket */
    s = socket(PF_CAN, SOCK_RAW, CAN_RAW);

    /* convert interface sting "can0" into interface index */
    strcpy(ifr.ifr_name, "can0");
    ioctl(s, SIOCGIFINDEX, &ifr);

    /* setup address for bind */
    addr.can_ifindex = ifr.ifr_ifindex;
    addr.can_family = PF_CAN;

    /* bind socket to the can0 interface */
    bind(s, (struct sockaddr *)&addr, sizeof(addr));

    while(1){
        /* first fill, then send the CAN frame */
        frame.can_id = 0x23;
        strcpy((char *)frame.data, "hello");
        frame.can_dlc = 5;
        write(s, &frame, sizeof(frame));

        /* first fill, then send the CAN frame */
        frame.can_id = 0x23;
        strcpy((char *)frame.data, "iCC2012");
        frame.can_dlc = 7;
        write(s, &frame, sizeof(frame));

        int numBytes =  read(s, &frame1, CAN_MTU);
        switch (numBytes)
        {
        case CAN_MTU:
            processFrame(frame1);
            break;
        case CANFD_MTU:
            // TODO: Should make an example for CAN FD создай функцию для считывания КАН ФД сообщений
            break;
        case -1:
            // Check the signal value on interrupt проверяем значение сигнала и прерывание
            if (EINTR == errno)
                break;
            // Delay before continuing маленькое тороможение
            perror("not read");
            usleep(100);
        default:
            break;
        }
    }
    close(s);

    return 0;
}

вот результат :3

введите сюда описание изображения

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.