在 Python 中,我正在尝试使用 linux 内核文档中提到的 J1939 过滤:https ://www.kernel.org/doc/html/latest/networking/j1939.html
以下代码在 setsockopt() 行(设置过滤器)失败:
import socket
import struct
def pack_J1939_filters(can_filters):
can_filter_fmt = "=" + "2Q2B2I" * len(can_filters)
filter_data = []
for can_filter in can_filters:
name = can_filter['name']
name_mask = can_filter['name_mask']
addr = can_filter['addr']
addr_mask = can_filter['addr_mask']
pgn = can_filter['pgn']
pgn_mask = can_filter['pgn_mask']
filter_data.append(name)
filter_data.append(name_mask)
filter_data.append(addr)
filter_data.append(addr_mask)
filter_data.append(pgn)
filter_data.append(pgn_mask)
return struct.pack(can_filter_fmt, *filter_data)
s = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_J1939)
interface = "vcan0"
src_name = socket.J1939_NO_NAME
src_pgn = socket.J1939_NO_PGN
src_addr = 0x81
src_sck_addr = (interface, src_name, src_pgn, src_addr)
s.bind(src_sck_addr)
filters = [{"name": 0, "name_mask":0, "addr":0, "addr_mask":0, "pgn": 0, "pgn_mask": 0}]
packed_filters = pack_J1939_filters(filters)
# socket.SOL_CAN_J1939 does not seem to exist
SOL_CAN_BASE = 100
CAN_J1939 = 7
SOL_CAN_J1939 = SOL_CAN_BASE + CAN_J1939
s.setsockopt(SOL_CAN_J1939, socket.SO_J1939_FILTER , packed_filters)
s.recvfrom(128)
s.close()
首先,内核文档提到使用 SOL_CAN_J1939 作为第一个参数。但是 socket.SOL_CAN_J1939 在 socket 包中不存在。所以查看这个位置的代码我能够理解这个 int 值应该是 107:http ://socket-can.996257.n3.nabble.com/RFC-v3-0-6-CAN-add-SAE -J1939-protocol-td7571.html
至于 setsockopt() 第三个参数,我打包过滤器以匹配 j1939_filter 结构(26 字节,如上一个链接的代码中所述)。这类似于在原始 CAN 的 can.interfaces.socketcan.utils 中所做的。
我做错了什么导致 setsockopt() 失败?