import RPi.GPIO as GPIO import time from datetime import datetime import subprocess import sys from slovak_datetime_formatter import get_datetime_as_slovak_sentence BUTTON_TIMEOUT = 30 # pressing and holding the button longer then e.g. 2 seconds terminates playing PIN = 17 # listen to changes on this GPIO GPIO.setmode(GPIO.BCM) # use BCM pin layout GPIO.setwarnings(False) def setup_pin(): GPIO.setup(PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) def terminate_playing(proc): print("Terminating playing...") proc.terminate() proc.wait(timeout=5) print("Terminated") def play_presny_cas(): print("Playing presny_cas.wav") proc = subprocess.Popen(["aplay", "presny_cas.wav"]) wait_for_button_release_or_timeout(PIN, BUTTON_TIMEOUT) print("GPIO went HIGH - terminating playing") terminate_playing(proc) def play_beep(): print("Playing beep.wav") subprocess.call(["aplay", "beep.wav"]) def generate_presny_cas(): text = get_datetime_as_slovak_sentence(datetime.now()) print(f"Generating presny_cas.wav for '{text}'") subprocess.call( [ "curl", "--silent", "--get", "--data-urlencode", f"text={text}", "https://tts.virtonline.eu/api/tts", "--output", "presny_cas.wav", ] ) print("Generated presny_cas.wav") def wait_for_button_release_or_timeout(pin, timeout): timeout_start = time.time() while time.time() < timeout_start + timeout: if GPIO.input(pin) == GPIO.HIGH: break time.sleep(0.05) def handle_pin(pin): print(f"GPIO {pin} LOW - event triggered") generate_presny_cas() play_presny_cas() try: setup_pin() play_beep() play_beep() GPIO.add_event_detect(PIN, GPIO.FALLING, callback=handle_pin, bouncetime=1000) print(f"Waiting for the GPIO {PIN} to go LOW...") while True: time.sleep(0.01) except Exception: print("Cought exception...") sys.exit() finally: GPIO.cleanup()