From cb518c563a849f9f868342a7350b8f16cf200fd2 Mon Sep 17 00:00:00 2001 From: Javier Casas Date: Thu, 15 May 2025 09:32:51 +0200 Subject: [PATCH] parse socketcand error messages to create a CAN error frame --- can/interfaces/socketcand/socketcand.py | 32 ++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/can/interfaces/socketcand/socketcand.py b/can/interfaces/socketcand/socketcand.py index 7a2cc6fd0..6e726003a 100644 --- a/can/interfaces/socketcand/socketcand.py +++ b/can/interfaces/socketcand/socketcand.py @@ -125,10 +125,11 @@ def detect_beacon(timeout_ms: int = 3100) -> List[can.typechecking.AutoDetectedC def convert_ascii_message_to_can_message(ascii_msg: str) -> can.Message: - if not ascii_msg.startswith("< frame ") or not ascii_msg.endswith(" >"): - log.warning(f"Could not parse ascii message: {ascii_msg}") + if not ascii_msg.endswith(" >"): + log.warning(f"Missing ending character in ascii message: {ascii_msg}") return None - else: + + if ascii_msg.startswith("< frame "): # frame_string = ascii_msg.removeprefix("< frame ").removesuffix(" >") frame_string = ascii_msg[8:-2] parts = frame_string.split(" ", 3) @@ -147,6 +148,31 @@ def convert_ascii_message_to_can_message(ascii_msg: str) -> can.Message: ) return can_message + if ascii_msg.startswith("< error "): + frame_string = ascii_msg[8:-2] + parts = frame_string.split(" ", 3) + can_id, timestamp = int(parts[0], 16), float(parts[1]) + is_ext = len(parts[0]) != 3 + + # socketcand sends no data in the error message so we don't have information + # about the error details, therefore the can frame is created with one + # data byte set to zero + data = bytearray([0]) + can_dlc = len(data) + can_message = can.Message( + timestamp=timestamp, + arbitration_id=can_id & 0x1FFFFFFF, + is_error_frame=True, + data=data, + dlc=can_dlc, + is_extended_id=True, + is_rx=True, + ) + return can_message + + log.warning(f"Could not parse ascii message: {ascii_msg}") + return None + def convert_can_message_to_ascii_message(can_message: can.Message) -> str: # Note: socketcan bus adds extended flag, remote_frame_flag & error_flag to id