如何在socketcan中检查总线状态

How check bus state in socketcan

我在嵌入式 linux 上使用 flexcan driver 并且我有 C 程序控制 can 消息。在我的 C 程序中,我需要检查 can 总线的状态,例如buss-offerror-active。我可以使用 linux 命令 ip -details -statistics link show can0 结果如下:

2: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 16 qdisc pfifo_fast state UP mode DEFAULT group default qlen 10
    link/can  promiscuity 0 
    can state *ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 100 
          bitrate 250000 sample-point 0.866 
          tq 266 prop-seg 6 phase-seg1 6 phase-seg2 2 sjw 1
          flexcan: tseg1 4..16 tseg2 2..8 sjw 1..4 brp 1..256 brp-inc 1
          clock 30000000
          re-started bus-errors arbit-lost error-warn error-pass bus-off
          31594      0          0          7686       25577      33258     
    RX: bytes  packets  errors  dropped overrun mcast   
    5784560    723230   0       1       0       0       
    TX: bytes  packets  errors  dropped carrier collsns 
    157896     19742    0       33269   0       0       

如何在我的 C 程序中得到 can state ERROR-ACTIVE?我还可以在 flex can driver 中看到一些寄存器可用于查看状态,但我也不知道如何在我的程序中包含这些值。 FLEXCAN_ESR_BOFF_INT 之类的寄存器包含我需要的值。

您可以将套接字设置为 return CAN 错误作为消息。

As described in Network Problem Notifications the CAN interface driver can generate so called Error Message Frames that can optionally be passed to the user application in the same way as other CAN frames. The possible errors are divided into different error classes that may be filtered using the appropriate error mask. To register for every possible error condition CAN_ERR_MASK can be used as value for the error mask. The values for the error mask are defined in linux/can/error.h

can_err_mask_t err_mask = ( CAN_ERR_TX_TIMEOUT | CAN_ERR_BUSOFF );

setsockopt(s, SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
           &err_mask, sizeof(err_mask));

有关详细信息,请参阅内核 documentation

更新

看看libsocketcan和例程can_get_state