# Makefile -- KVP (Lola-2-Kern) auf dem Digilent Arty S7 (Spartan-7)
#
#   make                    Bitstrom mit Vivado (Arty S7-50)
#   make BOARD=s7-25        fuer das Arty S7-25
#   make PROG=datei.asm     anderes Programm (max. 4096 Codewoerter)
#   make sim                ganzen Board-Entwurf simulieren (Icarus Verilog)
#   make sim INPUT=abc      dazu Zeichen ueber die UART einspeisen
#   make yosys              Probesynthese mit Yosys (synth_xilinx), ohne Vivado
#   make program            Bitstrom per JTAG laden (Vivado, fluechtig)
#   make program-ofl        dasselbe mit openFPGALoader
#   make flash-ofl          in den SPI-Flash schreiben (openFPGALoader, dauerhaft)
#   make console            Konsole 115200 8N1
#   make clean

BOARD  ?= s7-50
LOLAC  ?= Lolac
VIVADO ?= vivado
YOSYS  ?= yosys
PROG   ?= ../../cosim/tests/str.asm
TTY    ?= /dev/ttyUSB1

ifeq ($(BOARD),s7-50)
  PART      = xc7s50csga324-1
  DS_BITS   = 16
  OFL_BOARD = arty_s7_50
else ifeq ($(BOARD),s7-25)
  PART      = xc7s25csga324-1
  DS_BITS   = 15
  OFL_BOARD = arty_s7_25
else
  $(error BOARD=s7-50 oder BOARD=s7-25)
endif

OUT = build-$(BOARD)
BIT = $(OUT)/kvp_arty_s7.bit
SRC = KVP.v mem_s7.v uart.v kvp_arty_s7.v

all: $(BIT)

KVP.v: ../KVP.Lola
	$(LOLAC) ../KVP.Lola KVP.v > lolac.log 2>&1
	@grep -q "translating to" lolac.log || (cat lolac.log; rm -f KVP.v; false)

prog.mem: FORCE
	python3 mkprog.py $(PROG) prog.mem 4096

$(BIT): $(SRC) prog.mem arty_s7.xdc build.tcl
	@mkdir -p $(OUT)
	$(VIVADO) -mode batch -nojournal -log $(OUT)/vivado.log \
	    -source build.tcl -tclargs $(PART) $(DS_BITS) $(OUT)
	@grep -A8 '^| Slice LUTs\|^| Block RAM Tile' $(OUT)/utilization.txt | grep -E '^\| (Slice LUTs|Slice Registers|Block RAM Tile) ' || true

sim: KVP.v prog.mem
	iverilog -g2005 -DSIM -DDS_BITS=$(DS_BITS) -o tb_arty.vvp tb_arty.v $(SRC)
	vvp -n tb_arty.vvp $(if $(INPUT),+INPUT=$(INPUT)) | grep -E 'UART_OUT|HALT|TIMEOUT' | \
	    python3 -c "import sys; l=sys.stdin.read().split(chr(10)); \
	    print('Ausgabe:', repr(''.join(chr(int(x.split()[1],16)) for x in l if x.startswith('UART_OUT')))); \
	    [print(x) for x in l if x.startswith(('HALT','TIMEOUT'))]"

yosys: KVP.v prog.mem
	$(YOSYS) -q -l yosys.log -p "read_verilog -DDS_BITS=$(DS_BITS) $(SRC); \
	    synth_xilinx -family xc7 -top kvp_arty_s7; tee -o yosys_stat.txt stat"
	@grep -E 'LUT[1-6] |FD[A-Z]* |RAMB36E1|RAMB18E1|CARRY4|MMCME2_BASE' yosys_stat.txt | sort -u

program: $(BIT)
	$(VIVADO) -mode batch -nojournal -nolog -source program.tcl -tclargs $(BIT)

program-ofl: $(BIT)
	openFPGALoader -b $(OFL_BOARD) $(BIT)

flash-ofl: $(BIT)
	openFPGALoader -b $(OFL_BOARD) -f $(BIT)

console:
	picocom -b 115200 $(TTY)

clean:
	rm -rf build-s7-50 build-s7-25 KVP.v lolac.log prog.mem tb_arty.vvp \
	       yosys.log yosys_stat.txt .Xil usage_statistics_webtalk.* vivado*.jou

FORCE:
.PHONY: all sim yosys program program-ofl flash-ofl console clean FORCE
