# AP Design Labs - "Name it" reset logger
# Records WHY the board restarted, every time it boots.
# MicroPython, save as boot.py with Thonny. Pico or ESP32.
import machine

# Look up the reset causes this board's firmware knows about
CAUSES = {}
for name in ("PWRON_RESET", "HARD_RESET", "WDT_RESET",
             "DEEPSLEEP_RESET", "SOFT_RESET"):
    if hasattr(machine, name):
        CAUSES[getattr(machine, name)] = name

code = machine.reset_cause()
label = CAUSES.get(code, "UNKNOWN_" + str(code))

# Count earlier boots so each entry gets a number
try:
    with open("resets.log") as f:
        boots = len(f.readlines())
except OSError:
    boots = 0

with open("resets.log", "a") as f:
    f.write("boot {}: {}\n".format(boots + 1, label))

print("Boot", boots + 1, "- last reset:", label)
