From 14b1906563a0f9104c5418a6cab871130aff3a05 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Sun, 29 Mar 2026 14:47:16 -0700 Subject: [PATCH] Parse health packet layout from health.h (#2378) * Parse health packet layout from health.h * Fail closed on unexpected health.h layouts * cleanup * define once --- python/__init__.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/python/__init__.py b/python/__init__.py index 309c0b85e7..4c954b2395 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -1,5 +1,6 @@ # python library to interface with panda import os +import re import sys import time import usb1 @@ -42,6 +43,15 @@ def calculate_checksum(data): res ^= b return res +def _parse_c_struct(path, name): + type_to_format = {"uint8_t": "B", "uint16_t": "H", "uint32_t": "I", "float": "f"} + with open(path) as f: + lines = [l.strip() for l in f.read().split(f"struct __attribute__((packed)) {name} {{", 1)[1].split("};", 1)[0].splitlines() if l.strip()] + fields = [re.fullmatch(rf"({'|'.join(type_to_format)})\s+\w+;", l) for l in lines] + if not all(fields): + raise ValueError(f"unsupported {name} layout in {path}") + return struct.Struct("<" + "".join(type_to_format[m[1]] for m in fields)) + def pack_can_buffer(arr, chunk=False, fd=False): snds = [bytearray(), ] for address, dat, bus in arr: @@ -128,7 +138,7 @@ class Panda: CAN_PACKET_VERSION = compute_version_hash(os.path.join(opendbc.INCLUDE_PATH, "opendbc/safety/can.h")) HEALTH_PACKET_VERSION = compute_version_hash(os.path.join(BASEDIR, "board/health.h")) - HEALTH_STRUCT = struct.Struct("