# Makefile for the KE0WPC dedicated CW beacon firmware.
#
#   make -f Makefile.beacon
#
# Produces beacon.bin (raw) and beacon.packed.bin (flashable).
# Apache License 2.0.

TARGET  = uvk5-beacon

BSP_DEFINITIONS := $(wildcard hardware/*/*.def)
BSP_HEADERS     := $(patsubst hardware/%,bsp/%,$(BSP_DEFINITIONS))
BSP_HEADERS     := $(patsubst %.def,%.h,$(BSP_HEADERS))

OBJS  =
OBJS += start.o
OBJS += init.o

# Drivers - only what a transmit-only beacon actually touches.
OBJS += driver/adc.o
OBJS += driver/backlight.o
OBJS += driver/bk4819.o
OBJS += driver/eeprom.o
OBJS += driver/gpio.o
OBJS += driver/i2c.o
OBJS += driver/keyboard.o
OBJS += driver/spi.o
OBJS += driver/st7565.o
OBJS += driver/system.o
OBJS += driver/systick.o

OBJS += board.o
OBJS += font.o

OBJS += beacon/stubs.o
OBJS += beacon/morse.o
OBJS += beacon/beacon.o

ASFLAGS  = -c -mcpu=cortex-m0
CFLAGS   = -Os -Wall -Wextra -Werror -mcpu=cortex-m0 -fno-builtin -fshort-enums
CFLAGS  += -fno-delete-null-pointer-checks -std=c2x -MMD -ffunction-sections -fdata-sections
CFLAGS  += -DPRINTF_INCLUDE_CONFIG_H
LDFLAGS  = -mcpu=cortex-m0 -nostartfiles -Wl,-T,firmware.ld -Wl,--gc-sections

# The stock drivers are built with these knobs; keep them consistent so the
# shared .c files compile the same way they do in the full firmware.
CFLAGS  += -DENABLE_FEAT_F4HWN

INC  = -I ./
INC += -I ./external/CMSIS_5/CMSIS/Core/Include/
INC += -I ./external/CMSIS_5/Device/ARM/ARMCM0/Include/

CC      = arm-none-eabi-gcc
AS      = arm-none-eabi-as
LD      = arm-none-eabi-gcc
OBJCOPY = arm-none-eabi-objcopy
SIZE    = arm-none-eabi-size

DEPS = $(OBJS:.o=.d)

all: $(TARGET)
	$(OBJCOPY) -O binary $(TARGET) $(TARGET).bin
	-$(SIZE) $(TARGET)
	@python3 fw-pack.py $(TARGET).bin "KE0WPC" "BEACON 1.0" $(TARGET).packed.bin || \
	  echo "note: fw-pack.py not run; flash $(TARGET).bin with a tool that packs for you"

debug: $(TARGET)

$(TARGET): $(OBJS)
	$(LD) $(LDFLAGS) $^ -o $@

%.o: %.c | $(BSP_HEADERS)
	$(CC) $(CFLAGS) $(INC) -c $< -o $@

%.o: %.S
	$(AS) $(ASFLAGS) $(INC) $< -o $@

bsp/dp32g030/%.h: hardware/dp32g030/%.def
	@mkdir -p $(dir $@)
	@python3 utils/gen-bsp.py $< $@ 2>/dev/null || true

clean:
	rm -f $(TARGET) $(TARGET).bin $(TARGET).packed.bin $(OBJS) $(DEPS)

.PHONY: all clean debug

-include $(DEPS)
