xiiregexbuilder

FPGA-Accelerated Regular Expression Matching Engine

processor/src/prog_fpga.py (1805B)


 1import serial
 2import time
 3import sys
 4import serial.tools.list_ports
 5
 6
 7def find_fpga_port():
 8    ports = serial.tools.list_ports.comports()
 9    for port in ports:
10        if "COM14" in port.device:
11            return port.device
12    ports.sort(
13        key=lambda x: int(x.device.replace("COM", "") if "COM" in x.device else 0),
14        reverse=True,
15    )
16    for port in ports:
17        desc = port.description.lower()
18        if any(
19            x in desc
20            for x in ["usb", "uart", "nexys", "digilent", "cp210x", "ch340", "serial"]
21        ):
22            return port.device
23    return None
24
25
26def main():
27    hex_file = "imem.hex"
28    if len(sys.argv) > 1:
29        hex_file = sys.argv[1]
30
31    port = find_fpga_port()
32    if not port:
33        print("Error: FPGA Port not found.")
34        sys.exit(1)
35
36    print(f"Connecting to {port}...")
37    try:
38        ser = serial.Serial(port, 115200, timeout=1)
39    except Exception as e:
40        print(f"Error: Could not open serial port {port}: {e}")
41        sys.exit(1)
42
43    print(f"Programming {hex_file} to FPGA imem...")
44
45    with open(hex_file, "r") as f:
46        lines = f.readlines()
47
48    for addr, line in enumerate(lines):
49        line = line.strip()
50        if not line:
51            continue
52
53        data = int(line, 16)
54
55        # Protocol: 0x02 | Addr | Data[31:24] | Data[23:16] | Data[15:8] | Data[7:0]
56        packet = bytearray(
57            [
58                0x02,
59                addr & 0xFF,
60                (data >> 24) & 0xFF,
61                (data >> 16) & 0xFF,
62                (data >> 8) & 0xFF,
63                data & 0xFF,
64            ]
65        )
66
67        ser.write(packet)
68        time.sleep(0.001)  # Small delay for FPGA to process
69
70    ser.close()
71    print("Programming Complete!")
72
73
74if __name__ == "__main__":
75    main()