import sys
def fix_lattice_bitstream(input_file, output_file):
# This is exactly how the preamble chunk looks in your file byte-by-byte
# (LSC_PROG_CNT command 0x80 followed by the file's raw preamble bytes)
TARGET_SIGNATURE = b'\x80\x00\x82\x91\x00\x20'
with open(input_file, 'rb') as f:
content = f.read()
idx = content.find(TARGET_SIGNATURE)
if idx == -1:
print("Error: Target preamble signature not found in this specific .bit file!")
sys.exit(1)
# Include the 0x80 command and preamble into the execution payload
bitstream = content[idx:]
print(f"Preamble block detected at offset {idx}. Extracting configuration payload...")
# Perform the mandatory hardware Byte Bit-Mirroring for Lattice Slave I2C port
fixed_bytes = bytearray()
for byte in bitstream:
flipped = int('{:08b}'.format(byte)[::-1], 2)
fixed_bytes.append(flipped)
with open(output_file, 'wb') as f:
f.write(fixed_bytes)
print(f"Success! Generated clean I2C binary: {output_file}")
if __name__ == '__main__':
if len(sys.argv) < 3:
print("Usage: python3 lpc_convert.py <input.bit> <output.bin>")
sys.exit(1)
# ИСПРАВЛЕНО: Передаем конкретные элементы списка (индексы 1 и 2), а не весь список целиком!
fix_lattice_bitstream(sys.argv[1], sys.argv[2])