Skip to content

Commit 14b1906

Browse files
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
1 parent d079b09 commit 14b1906

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

python/__init__.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# python library to interface with panda
22
import os
3+
import re
34
import sys
45
import time
56
import usb1
@@ -42,6 +43,15 @@ def calculate_checksum(data):
4243
res ^= b
4344
return res
4445

46+
def _parse_c_struct(path, name):
47+
type_to_format = {"uint8_t": "B", "uint16_t": "H", "uint32_t": "I", "float": "f"}
48+
with open(path) as f:
49+
lines = [l.strip() for l in f.read().split(f"struct __attribute__((packed)) {name} {{", 1)[1].split("};", 1)[0].splitlines() if l.strip()]
50+
fields = [re.fullmatch(rf"({'|'.join(type_to_format)})\s+\w+;", l) for l in lines]
51+
if not all(fields):
52+
raise ValueError(f"unsupported {name} layout in {path}")
53+
return struct.Struct("<" + "".join(type_to_format[m[1]] for m in fields))
54+
4555
def pack_can_buffer(arr, chunk=False, fd=False):
4656
snds = [bytearray(), ]
4757
for address, dat, bus in arr:
@@ -128,7 +138,7 @@ class Panda:
128138

129139
CAN_PACKET_VERSION = compute_version_hash(os.path.join(opendbc.INCLUDE_PATH, "opendbc/safety/can.h"))
130140
HEALTH_PACKET_VERSION = compute_version_hash(os.path.join(BASEDIR, "board/health.h"))
131-
HEALTH_STRUCT = struct.Struct("<IIIIIIIIBBBBBHBBBHfBBHHHBH")
141+
HEALTH_STRUCT = _parse_c_struct(os.path.join(BASEDIR, "board/health.h"), "health_t")
132142
CAN_HEALTH_STRUCT = struct.Struct("<BIBBBBBBBBIIIIIIIHHBBBIIII")
133143

134144
H7_DEVICES = [HW_TYPE_RED_PANDA, HW_TYPE_TRES, HW_TYPE_CUATRO, HW_TYPE_BODY]

0 commit comments

Comments
 (0)