关于Linux中socket can怎么使用,CSDN上已经有很多文章介绍。本文重点记录can_filter中的 CAN_INV_FILTER的使用,很多文章对此一笔带过,且很多文章翻译不全,或者原文不全,导致自己浪费了些时间,最后在看candump源码时才发现问题所在。
直接贴代码解释,以下为写的一个最简单的canId过滤函数:
宏定义
#define CAN_FILTER_PASS 0x01
#define CAN_FILTER_REJECT 0x02
函数声明
bool canRcvFiltersSet(const uint *canIdArray, const uint &arraySize, short filterType);
函数定义
bool rcvFiltersSet(const uint *canIdArray, const uint &arraySize, short filterType)
{
if(canfd <= 0)
return false;
if(NULL == canIdArray){
setsockopt(canfd, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
return true;
}
struct can_filter rfilter[arraySize];
bzero(rfilter,sizeof (rfilter));
for(uint i = 0; i < arraySize; ++i){
if(canIdArray[i]){
if(filterType & CAN_FILTER_PASS){
rfilter[i].can_id = canIdArray[i];
}
else{
rfilter[i].can_id = (canIdArray[i] | CAN_INV_FILTER);
}
rfilter[i].can_mask = CAN_EFF_MASK;
}else{
return false;
}
}
if(filterType & CAN_FILTER_REJECT){
int join_filter = 1;
setsockopt(canfd, SOL_CAN_RAW, CAN_RAW_JOIN_FILTERS, &join_filter, sizeof(join_filter));
}
setsockopt(canfd, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
return true;
}
使用示例:
* const uint can_id_reject[] = {0x123, 0x11111678, 0x282};
canRcvFiltersSet(can_id_reject, sizeof(can_id_reject)/sizeof(uint), CAN_FILTER_REJECT);
* const uint can_id_pass[] = {0x123, 0x11111678, 0x282};
canRcvFiltersSet(can_id_pass, sizeof(can_id_pass)/sizeof(uint), CAN_FILTER_PASS);
完。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)