# Koheron CTL200 -> WiFi/MQTT bridge on ESP32.
#
# All commands run PlatformIO from the project-local venv, so you never need
# `pio` on your PATH. Just `make`, `make upload`, `make monitor`.

VENV    := .venv
PIO     := $(VENV)/bin/pio
PORT    ?= /dev/ttyUSB0
ENV     := esp32dev

.PHONY: help build upload monitor flash clean detect erase venv

help:                ## Show this help
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) \
	  | awk 'BEGIN{FS=":.*?## "}{printf "  \033[36m%-10s\033[0m %s\n", $$1, $$2}'

build: $(PIO)        ## Compile firmware
	$(PIO) run -e $(ENV)

upload: $(PIO)       ## Compile + flash to the ESP32
	$(PIO) run -e $(ENV) -t upload --upload-port $(PORT)

monitor: $(PIO)      ## Open serial monitor (Ctrl-C to exit)
	$(PIO) device monitor --port $(PORT) -b 115200

flash: upload monitor ## Upload then immediately open the monitor

detect: $(PIO)       ## Identify the chip on $(PORT)
	$(VENV)/bin/python -m esptool --port $(PORT) chip_id

erase: $(PIO)        ## Erase entire flash (factory reset)
	$(VENV)/bin/python -m esptool --port $(PORT) erase_flash

clean: $(PIO)        ## Remove build artifacts
	$(PIO) run -e $(ENV) -t clean

# Recreate the venv if it is missing (e.g. fresh checkout).
venv $(PIO):
	python3 -m venv $(VENV)
	$(VENV)/bin/pip install --upgrade pip
	$(VENV)/bin/pip install platformio esptool
