# Helper tools of the App (run on the Red Pitaya from py/ and src/).
# Cross compiled from the App Makefile (`make c_tools`, part of `make all`) with the
# Linaro toolchain of ../../settings.sh (CROSS_COMPILE=arm-linux-gnueabihf-).
# On the board itself (CROSS_COMPILE empty) it uses the native gcc, as originally.

CC = $(CROSS_COMPILE)gcc
RM = rm

# Same flags as the binaries of 9c5139f (native gcc 5.4 on the board: GNU C11, -g, no -O,
# default -fstack-protector-strong). Independent of the CFLAGS exported by the App Makefile.
TOOLS_CFLAGS = -g -std=gnu11 -fstack-protector-strong $(EXTRA_CFLAGS)

TOOLS = lock osc streaming stream_tcp_osc_cmd

all: $(TOOLS)

lock: lock.c
	$(CC) -o $@ $< $(TOOLS_CFLAGS) -Wno-overflow

osc: osc.c
	$(CC) -o $@ $< $(TOOLS_CFLAGS) -Wno-overflow

streaming: streaming.c lock_offsets.h
	$(CC) -o $@ $< $(TOOLS_CFLAGS)

stream_tcp_osc_cmd: stream_tcp_osc_cmd.c lock_offsets.h
	$(CC) -o $@ $< $(TOOLS_CFLAGS)

# v2.4.3: byte offsets of the streaming registers, from the register map of lock.txt (written by
# resources/config_tool.py: name,index,...; offset = 4*index), so that they follow the register map
# of this App (they were hardcoded with the offsets of lock_in+pid_harmonic). Fails if one is missing.
STREAM_REGS = stream_ip stream_port stream_rate stream_cmd
lock_offsets.h: lock.txt
	@echo "/* Generated by c/Makefile from c/lock.txt - do not edit */" > $@.tmp
	@for r in $(STREAM_REGS); do \
	    i=$$(awk -F, -v n=$$r '$$1==n {print $$2}' lock.txt); \
	    [ -n "$$i" ] || { echo "ERROR: $$r not found in lock.txt"; rm -f $@.tmp; exit 1; }; \
	    printf '#define LOCK_%s_OFF 0x%03X\n' $$(echo $$r | tr a-z A-Z) $$((4*i)) >> $@.tmp; \
	done
	mv $@.tmp $@
	cat $@

clean:
	-$(RM) -f $(TOOLS) lock_offsets.h

.PHONY: all clean
