# SPDX-License-Identifier: MIT
# Atelier de l'autonomie — bouton USB, version 1.0, 2026-10-03
# Raspberry Pi Pico / Pico H RP2040, CircuitPython 10.x + adafruit_hid.
# Contact normalement ouvert entre GP15 (broche 20) et GND (broche 18).


class DebouncedPress:
    """Un evenement par appui, apres relachement stable au demarrage."""

    def __init__(self, pressed, now, delay=0.035):
        if delay <= 0:
            raise ValueError("Le delai doit etre positif")
        self.delay = delay
        self._raw = bool(pressed)
        self.pressed = bool(pressed)
        self._changed_at = now
        self._armed = False

    def update(self, pressed, now):
        pressed = bool(pressed)
        if pressed != self._raw:
            self._raw = pressed
            self._changed_at = now

        if now - self._changed_at < self.delay:
            return False

        if not pressed:
            self._armed = True

        if pressed != self.pressed:
            self.pressed = pressed
            if pressed and self._armed:
                self._armed = False
                return True
        return False


def main():
    import time
    import board
    import digitalio
    import usb_hid
    from adafruit_hid.keyboard import Keyboard
    from adafruit_hid.keycode import Keycode

    switch = digitalio.DigitalInOut(board.GP15)
    switch.switch_to_input(pull=digitalio.Pull.UP)
    led = digitalio.DigitalInOut(board.LED)
    led.switch_to_output(value=False)
    keyboard = Keyboard(usb_hid.devices)
    debounce = DebouncedPress(not switch.value, time.monotonic())

    # SPACE produit une frappe courte, pas une touche maintenue.
    # Remplacer par Keycode.ENTER ou Keycode.F13 seulement apres verification
    # du raccourci dans l'application cible.
    key = Keycode.SPACE

    try:
        while True:
            if debounce.update(not switch.value, time.monotonic()):
                keyboard.send(key)
            led.value = debounce.pressed
            time.sleep(0.005)
    finally:
        keyboard.release_all()
        led.value = False
        switch.deinit()
        led.deinit()


if __name__ == "__main__":
    main()
