import struct import time from functools import reduce from operator import xor from pathlib import Path from panda import McuType, Panda from panda.python.base import TIMEOUT from panda.python.spi import PandaSpiException, SpiDevice FLASHER_MAGIC = b"\xde\xad\xd0\x0d" MAX_RESPONSE = 64 class LegacySpiFlasher: """Use the previous SPI framing only to identify and migrate an internal TRES Panda.""" def __init__(self, spi): self.spi = spi @staticmethod def _frame(data): return data + bytes([reduce(xor, data, 0xab)]) def _wait_ack(self, expected, fill, length, timeout=0.25): deadline = time.monotonic() + timeout while time.monotonic() < deadline: reply = self.spi.xfer(bytes([fill]) * length) if reply[0] == expected: return reply if reply[0] == 0x1f: raise PandaSpiException("Legacy SPI request was rejected") raise PandaSpiException(f"Legacy SPI acknowledgment {expected:#x} timed out") def _exchange(self, endpoint, payload, expect_disconnect=False, reply_timeout=0.25): header = struct.pack(" MAX_RESPONSE or reduce(xor, reply[:size + 4], 0xab): raise PandaSpiException("Legacy SPI response length or checksum invalid") return reply[3:size + 3] def controlRead(self, request_type, request, value, index, length): return self._exchange(0, struct.pack(" str | None: """Return the migrated TRES serial, or None if the previous SPI framing is absent.""" device = SpiDevice() with device.acquire() as spi: flasher = LegacySpiFlasher(spi) try: if not flasher.is_tres(): return None except PandaSpiException: return None serial = flasher.controlRead(Panda.REQUEST_IN, 0xc3, 0, 0, 12) if len(serial) != 12 or (expected_serial is not None and serial.hex() != expected_serial): raise PandaSpiException("Legacy TRES identity could not be verified") code = Path(filename).read_bytes() size = int.from_bytes(code[:4], "little") if size <= 8 or size + 128 != len(code) or len(code) % 4 or len(code) >= 6 * 0x20000: raise ValueError("Invalid legacy migration image layout") if not Panda.flasher_present(flasher): flasher.controlWrite(Panda.REQUEST_IN, 0xd1, 1, 0, b"", expect_disconnect=True) time.sleep(0.5) if not flasher.is_tres() or not Panda.flasher_present(flasher): raise PandaSpiException("Legacy TRES bootstub could not be verified") if flasher.controlRead(Panda.REQUEST_IN, 0xc3, 0, 0, 12) != serial: raise PandaSpiException("Legacy TRES identity changed before flashing") Panda.flash_static(flasher, code, McuType.H7) return serial.hex()