From 85e2e92991b5d980eb53afd1a008abd92862207f Mon Sep 17 00:00:00 2001 From: Gustice Date: Fri, 23 Oct 2026 21:41:53 +0200 Subject: [PATCH] step: Watchdog --- .gitignore | 3 +- doc/setupAutostart.md | 46 ++++++++++++---- scripts/{test.py => mTest.py} | 0 src/watchdog/watchdog.py | 99 +++++++++++++++++++++++++++++++++++ 4 files changed, 136 insertions(+), 12 deletions(-) rename scripts/{test.py => mTest.py} (100%) create mode 100755 src/watchdog/watchdog.py diff --git a/.gitignore b/.gitignore index 548c5a4..8dadd7d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ build/ .cache/ -deploy/ \ No newline at end of file +deploy/ +.venv/ \ No newline at end of file diff --git a/doc/setupAutostart.md b/doc/setupAutostart.md index ccb3c58..4339a95 100644 --- a/doc/setupAutostart.md +++ b/doc/setupAutostart.md @@ -1,20 +1,20 @@ # Autostart applications ```sh -sudo nano /etc/systemd/system/Sword.service +sudo nano /etc/systemd/system/SwordMain.service ``` -./ + ```ini [Unit] -Description=My Raspberry Pi Application +Description=IoT Service for Sword Station After=network-online.target Wants=network-online.target [Service] Type=simple -User=gustice -WorkingDirectory=/home/pi/SwordMain -ExecStart=bash start.sh +User=theUser +WorkingDirectory=/home/theUser/SwordMain +ExecStart=/home/theUser/SwordMain/run.sh Restart=on-failure RestartSec=5 @@ -23,16 +23,40 @@ WantedBy=multi-user.target ``` ```sh -chmod +x /home/pi/SwordMain/start.sh +chmod +x /home/theUser/SwordMain/start.sh # Reload systemd sudo systemctl daemon-reload # Enable the service -sudo systemctl enable Sword.service +sudo systemctl enable SwordMain.service # start immediately -sudo systemctl start Sword.service +sudo systemctl start SwordMain.service # check status -sudo systemctl status Sword.service +sudo systemctl status SwordMain.service ``` -game $(pwd)/assets -b "mqtts://excaliburs-erben.de:8883" -t "outdoor/king-arthur/sword/" -p "awesomeexodusoutdooradventures" -u "exodususer" \ No newline at end of file +game $(pwd)/assets -b "mqtts://excaliburs-erben.de:8883" -t "outdoor/king-arthur/sword/" -p "awesomeexodusoutdooradventures" -u "exodususer" + +## Watchdog + +```sh +sudo nano /etc/systemd/system/SwordWatchdog.service +``` + +```ini +[Unit] +Description=Network Watchdog for Sword +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +# user root user +WorkingDirectory=/home/theUser/SwordWatchdog +ExecStart=/home/theUser/SwordWatchdog/watchdog.py +Restart=on-failure +RestartSec=5 + +[Install] +WantedBy=multi-user.target +``` \ No newline at end of file diff --git a/scripts/test.py b/scripts/mTest.py similarity index 100% rename from scripts/test.py rename to scripts/mTest.py diff --git a/src/watchdog/watchdog.py b/src/watchdog/watchdog.py new file mode 100755 index 0000000..892d7d5 --- /dev/null +++ b/src/watchdog/watchdog.py @@ -0,0 +1,99 @@ +#!/bin/env python +import os +import time +import subprocess +import requests +from datetime import datetime + +# --- Configuration --- +SERVER_TO_PING = "8.8.8.8" # Replace with the server you want to monitor +FAIL_FILE = "ping_fail_timestamp.txt" + +# SEQ Logger Configuration +SEQ_URL = "https://log.excaliburs-erben.de/ingest/clef" +SEQ_API_KEY = "9SWjXUxmnzcgCKYfzXMI" +# --------------------- + +def ping(host): + """Returns True if host responds to a ping request.""" + command = ['ping', '-c', '1', host] + return subprocess.call(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0 + +def check_and_report_failure(): + """Checks for the failure file on startup and logs to SEQ if found.""" + if os.path.exists(FAIL_FILE): + try: + with open(FAIL_FILE, 'r') as f: + fail_time = f.read().strip() + + print(f"Found failure record from: {fail_time}. Sending to SEQ...") + event = { + "@t": datetime.now().isoformat(), + "@mt": "[{App}] Rebooted due to timeout at {FailTime}", + "Level": "Information", + "App": "Watchdog", + "FailTime": fail_time + } + + response = requests.post( + SEQ_URL, + json=event, + headers={ + "X-Seq-ApiKey": SEQ_API_KEY, + "Content-Type": "application/vnd.serilog.clef", + }, + timeout=10 + ) + + if response.status_code in (200, 201): + print("Successfully logged to SEQ.") + os.remove(FAIL_FILE) + else: + print(f"Failed to log to SEQ: HTTP {response.status_code} - {response.text}") + + except Exception as e: + print(f"Error handling the failure file or connecting to SEQ: {e}") + +def reboot_computer(): + """Reboot the system and report any failure.""" + result = subprocess.run(["/usr/sbin/reboot"], check=True) + + print(f"Reboot command exit code: {result.returncode}") + if result.stdout: + print(result.stdout) + if result.stderr: + print(result.stderr) + + return result.returncode == 0 + +def main(): + check_and_report_failure() + + print(f"Starting connection monitor. Pinging {SERVER_TO_PING} every 10 seconds...") + fail_count = 0 + + while True: + if ping(SERVER_TO_PING): + fail_count = 0 # Reset counter on success + # print(f"[{datetime.now().strftime('%H:%M:%S')}] Ping successful.") + else: + fail_count += 1 + print(f"[{datetime.now().strftime('%H:%M:%S')}] Ping failed. Consecutive failures: {fail_count}/3") + + if fail_count >= 3: + fail_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + print(f"Ping failed 3 times at {fail_time}. Writing fail-file and rebooting...") + + try: + with open(FAIL_FILE, 'w') as f: + f.write(fail_time) + except IOError as e: + print(f"Failed to write fail file: {e}") + + reboot_computer() + break + + time.sleep(10) + +if __name__ == "__main__": + main() \ No newline at end of file