# AshLight firmware
#   make test      host unit tests (any C compiler)
#   make trace     reference traces for the web simulator parity check
#   make rp2040    RP2040 build -> build/rp2040-<board>/ashlight.uf2 (Pico SDK + arm-none-eabi-gcc)
#   make flash     load it over USB-C with picotool (no buttons needed)
CC      ?= cc
CFLAGS  := -std=c11 -Wall -Wextra -Werror -pedantic -O2 -Iinclude
CORE    := src/ashlight_core.c src/settings.c
HDRS    := include/ashlight_core.h include/settings.h
PICO_SDK_PATH ?= $(HOME)/code/AshLight-deps/pico-sdk
ARM_TOOLCHAIN ?= $(firstword $(wildcard $(HOME)/code/AshLight-deps/arm-gnu-toolchain-*) /opt/homebrew)
BOARD   ?= ashlight_revb
.PHONY: all test trace rp2040 flash clean
all: test rp2040

build:
	mkdir -p build

build/test_core: $(CORE) tests/test_core.c $(HDRS) | build
	$(CC) $(CFLAGS) $(CORE) tests/test_core.c -lm -o $@
test: build/test_core
	./build/test_core

build/trace: $(CORE) tests/trace.c $(HDRS) | build
	$(CC) $(CFLAGS) $(CORE) tests/trace.c -o $@
trace: build/trace
	./build/trace > ../site/sim/reference-trace.json
	@echo "wrote ../site/sim/reference-trace.json"

# RP2040 build via the Pico SDK. BOARD=ashlight_revb (custom PCB) or BOARD=pico_proto (Rev A0 breadboard).
rp2040:
	cmake -S rp2040 -B build/rp2040-$(BOARD) -G Ninja -DPICO_SDK_PATH=$(PICO_SDK_PATH) \
	      -DPICO_TOOLCHAIN_PATH=$(ARM_TOOLCHAIN) -DPICO_NO_PICOTOOL=1 -DASHLIGHT_BOARD=$(BOARD) -DCMAKE_BUILD_TYPE=MinSizeRel
	cmake --build build/rp2040-$(BOARD)
	python3 ../tools/bin2uf2.py build/rp2040-$(BOARD)/ashlight.bin build/rp2040-$(BOARD)/ashlight-$(BOARD).uf2

# Flash over USB-C. picotool reboots a running lamp into its bootloader by itself.
flash: rp2040
	picotool load -f -x build/rp2040-$(BOARD)/ashlight-$(BOARD).uf2

clean:
	rm -rf build
