From 97e77892f957eff47662e1a97a1e0beaeb922a68 Mon Sep 17 00:00:00 2001 From: cpu Date: Tue, 19 Dec 2023 19:31:56 +0100 Subject: [PATCH] error handling for curl --- .gitignore | 2 ++ README.md | 4 ++-- kukuc-clock.py | 44 +++++++++++++++++++++++++++----------------- 3 files changed, 31 insertions(+), 19 deletions(-) diff --git a/.gitignore b/.gitignore index bee8a64..93a3aec 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ __pycache__ +credentials.txt +presny_cas.wav diff --git a/README.md b/README.md index 6e3afbf..dbe0b6d 100644 --- a/README.md +++ b/README.md @@ -97,10 +97,10 @@ Install the systemd service file > `sudo mv kukuc-clock.service /etc/systemd/system/` Reload systemd manager configuration -> `systemctl daemon-reload` +> `sudo systemctl daemon-reload` Enable the `kukuc-clock` service at boot time and also run it -> `systemctl enable --now kukuc-clock` +> `sudo systemctl enable --now kukuc-clock` If it does not work check logs > `journalctl -f -u kukuc-clock` diff --git a/kukuc-clock.py b/kukuc-clock.py index a7dc8ab..1517ff5 100644 --- a/kukuc-clock.py +++ b/kukuc-clock.py @@ -12,6 +12,7 @@ else: TTS_API_URL = "https://tts.virtonline.eu/api/tts" BUTTON_TIMEOUT = 30 # button release timeout terminates playing +FILENAME = "presny_cas.wav" PIN = 27 # listen to changes on this GPIO pin GPIO.setmode(GPIO.BCM) # use BCM pin layout GPIO.setwarnings(False) @@ -29,8 +30,8 @@ def terminate_playing(proc): def play_presny_cas(): - print("Playing presny_cas.wav") - proc = subprocess.Popen(["aplay", "presny_cas.wav"]) + print(f"Playing {FILENAME}") + proc = subprocess.Popen(["aplay", FILENAME]) wait_for_button_release_or_timeout(PIN, BUTTON_TIMEOUT) print("GPIO went HIGH - terminating playing") terminate_playing(proc) @@ -51,23 +52,32 @@ def get_credentials(): def generate_presny_cas(): text = get_datetime_as_slovak_sentence(datetime.now()) - print(f"Generating presny_cas.wav for '{text}' using a remote API call") + print(f"Calling remote TTS API for '{text}'") username, password = get_credentials() - subprocess.call( - [ - "curl", - "--silent", - "-u", - f"{username}:{password}", - "--get", - "--data-urlencode", - f"text={text}", - TTS_API_URL, - "--output", - "presny_cas.wav", - ] + command = [ + "curl", + "-s", + "-w", + "%{http_code}", + "-u", + f"{username}:{password}", + "--get", + "--data-urlencode", + f"text={text}", + TTS_API_URL, + "--output", + FILENAME, + ] + # print(f"Executing: {' '.join(command)}") + result = subprocess.run( + command, + check=True, + capture_output=True, + text=True, ) - print("Generated presny_cas.wav") + if result.stdout != "200": + raise Exception(f"API call failed with status code {result.stdout}") + print(f"Generated {FILENAME}") def wait_for_button_release_or_timeout(pin, timeout):