# ir-pico: a Raspberry Pi Pico H that drives an IR transceiver, so a computer on USB
# can learn a remote's codes and send them. Wiring: wiring.md.
# Tools come from the flake: nix develop --command make test
#
# flash and install copy files to the Pico's drives, which a desktop automounts
# under /run/media/$USER (or set MEDIA=). console, listen, send, and pulses talk
# to it over USB serial: TTY=/dev/serial/by-id/usb-Raspberry_Pi_Pico_... names one
# Pico for good; the default, /dev/ttyACM0, is whichever came first.
#
#   hold BOOTSEL, plug in the Pico, then:
#   make flash install

CP_VERSION = 10.3.2
BOARD = raspberry_pi_pico
UF2 = adafruit-circuitpython-$(BOARD)-en_US-$(CP_VERSION).uf2
UF2_URL = https://downloads.circuitpython.org/bin/$(BOARD)/en_US/$(UF2)
MEDIA = /run/media/$(USER)
BOOT = $(MEDIA)/RPI-RP2
CIRCUITPY = $(MEDIA)/CIRCUITPY

IRREMOTE_VERSION = 5.0.8
IRREMOTE_URL = https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_IRRemote/$(IRREMOTE_VERSION)/adafruit_irremote.py
TTY = /dev/ttyACM0
SECONDS = 20
CODE = 20 DF 10 EF

.PHONY: help flash check install console listen send pulses test
.DELETE_ON_ERROR:

## list targets
help:
	@awk -f ../make-help.awk $(MAKEFILE_LIST)

## download the CircuitPython firmware (once; kept in cache/)
cache/$(UF2):
	mkdir -p cache
	curl -fsSL -o $@ $(UF2_URL)
	sha256sum $@

## copy CircuitPython onto the Pico in BOOTSEL mode; it reboots as CIRCUITPY
flash: cache/$(UF2)
	test -f $(BOOT)/INFO_UF2.TXT || { echo "no $(BOOT): hold BOOTSEL and plug in the Pico" >&2; exit 1; }
	cp $< $(BOOT)/ && sync

## the Pico as CircuitPython: its drive, version, and serial port
check:
	cat $(CIRCUITPY)/boot_out.txt
	ls -l /dev/serial/by-id/ | grep -i pico

## download the IR remote library (once; kept in cache/)
cache/adafruit_irremote-$(IRREMOTE_VERSION).py:
	mkdir -p cache
	curl -fsSL -o $@ $(IRREMOTE_URL)
	sha256sum $@

## copy code.py and its library onto CIRCUITPY; the Pico restarts it
install: code.py ir_commands.py cache/adafruit_irremote-$(IRREMOTE_VERSION).py
	test -d $(CIRCUITPY) || { echo "no $(CIRCUITPY)" >&2; exit 1; }
	mkdir -p $(CIRCUITPY)/lib
	cp cache/adafruit_irremote-$(IRREMOTE_VERSION).py $(CIRCUITPY)/lib/adafruit_irremote.py
	cp ir_commands.py $(CIRCUITPY)/ir_commands.py
	cp code.py $(CIRCUITPY)/code.py && sync

## talk to code.py over USB serial (needs the dialout group); quit: C-a C-x
console:
	picocom -b 115200 $(TTY)

## print the codes code.py hears for SECONDS (default 20)
listen:
	python3 -I pico_tty.py $(TTY) listen $(SECONDS)

## send CODE once (default: a Vizio TV's Power, which toggles it)
send:
	python3 -I pico_tty.py $(TTY) send $(CODE)

## count raw IR pulses on GP16 for SECONDS, decoder bypassed: is the receiver wired?
pulses:
	python3 -I pico_tty.py $(TTY) pulses $(SECONDS)

## doctests for the plain-Python parts; no Pico needed
test:
	python3 -I -m doctest ir_commands.py pico_tty.py && echo doctests pass
