Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

python - KeyError: 392 upon trying to decode CAN message using dbc file?

I am trying to decode CAN messages from a device using the manufacturer's provided dbc file. I am using Python 3.8.5. To load/set up the dbc file, I have:

import can
import cantools

self.bus = can.interface.Bus('slcan0', bustype='socketcan',bitrate=250000)
listener = can.Listener()
listener.on_message_received = self.callback
self.dbc = cantools.database.load_file(dbc_file_path,strict=False) #need strict=False or it raises errors for overlapping signals for some reason

in the callback function I have:

def callback(self, can_msg):
    decoded = self.dbc.decode_message(can_msg.arbitration_id, can_msg.data)

The script runs, but as soon as it receives a CAN message from the device, it gives me the following error:

Traceback (most recent call last):                                                                       
  File "/home/.local/lib/python3.8/site-packages/cantools/database/can/database.py", line 385, in decode_message                                                                                            
    message = self._frame_id_to_message[frame_id_or_name]
KeyError: 392

Any idea what might be going wrong? I have googled and found similar errors on stack overflow, but they don't seem to be exactly the same, and the solutions they propose don't fix my issue.

Thanks!

question from:https://stackoverflow.com/questions/66051065/keyerror-392-upon-trying-to-decode-can-message-using-dbc-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I figured it out. The device was sending CAN messages with arbitration_ids that were not listed in the dbc file, and thus giving a Key Error. A Key Error is where you try to reference a Key in a Dictionary that does not exist. 392 was the unrecognized ID. I worked around this by adding a try/exception statement around my decoded = self.dbc.decode_message(can_msg.arbitration_id, can_msg.data) line, and then investigating why the dbc file wasn't prepared for this particular message id.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...