This commit is contained in:
Gustice committed 2026-11-01 16:46:30 +01:00
1 parent e7a9e0316e
commit 2617407d18
3 files changed
+91 -17

No files matched your search

+26
View File
@@ -60,3 +60,29 @@ RestartSec=5
[Install] [Install]
WantedBy=multi-user.target WantedBy=multi-user.target
``` ```
## WiFi Power
```sh
sudo nano /etc/systemd/system/wifi-txpower.service
# ..
sudo systemctl enable wifi-txpower.service
sudo systemctl start wifi-txpower.service
```
```sh
[Unit]
Description=Set WiFi TX Power limit to prevent overheating
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
# Wait 15 seconds after network connects so the network manager doesn't overwrite it
ExecStartPre=/bin/sleep 15
ExecStart=/sbin/iwconfig wlan0 txpower 20
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
```
+45 -17
View File
@@ -3,6 +3,7 @@ import os
import time import time
import subprocess import subprocess
import requests import requests
import sys
from datetime import datetime from datetime import datetime
# --- Configuration --- # --- Configuration ---
@@ -19,6 +20,22 @@ def ping(host):
command = ['ping', '-c', '1', host] command = ['ping', '-c', '1', host]
return subprocess.call(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0 return subprocess.call(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0
def sendSeqPayload(event):
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.")
return True
print(f"Failed to log to SEQ: HTTP {response.status_code} - {response.text}")
return False
def check_and_report_failure(): def check_and_report_failure():
"""Checks for the failure file on startup and logs to SEQ if found.""" """Checks for the failure file on startup and logs to SEQ if found."""
if os.path.exists(FAIL_FILE): if os.path.exists(FAIL_FILE):
@@ -34,26 +51,34 @@ def check_and_report_failure():
"App": "Watchdog", "App": "Watchdog",
"FailTime": fail_time "FailTime": fail_time
} }
if sendSeqPayload(event):
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) os.remove(FAIL_FILE)
else:
print(f"Failed to log to SEQ: HTTP {response.status_code} - {response.text}")
except Exception as e: except Exception as e:
print(f"Error handling the failure file or connecting to SEQ: {e}") print(f"Error handling the failure file or connecting to SEQ: {e}")
def reset_wifi():
print(f"Network error detected. Resetting wlan0...")
try:
subprocess.run(["sudo", "nmcli", "radio", "wifi", "off"], check=True)
time.sleep(2) # Give it a moment to completely power down the interface
subprocess.run(["sudo", "nmcli", "radio", "wifi", "on"], check=True)
print("WiFi reset command sent. Waiting for network to establish...")
time.sleep(20) # Wait for DHCP and connection to re-establish
event = {
"@t": datetime.now().isoformat(),
"@mt": "[{App}] Reset WiFi due to timeout",
"Level": "Information",
"App": "Watchdog"
}
sendSeqPayload(event)
except subprocess.CalledProcessError as e:
print(f"Failed to reset WiFi: {e}", file=sys.stderr)
except Exception as e:
print(f"Failed in reset Process: {e}", file=sys.stderr)
def reboot_computer(): def reboot_computer():
"""Reboot the system and report any failure.""" """Reboot the system and report any failure."""
result = subprocess.run(["/usr/sbin/reboot"], check=True) result = subprocess.run(["/usr/sbin/reboot"], check=True)
@@ -78,9 +103,12 @@ def main():
# print(f"[{datetime.now().strftime('%H:%M:%S')}] Ping successful.") # print(f"[{datetime.now().strftime('%H:%M:%S')}] Ping successful.")
else: else:
fail_count += 1 fail_count += 1
print(f"[{datetime.now().strftime('%H:%M:%S')}] Ping failed. Consecutive failures: {fail_count}/3") print(f"[{datetime.now().strftime('%H:%M:%S')}] Ping failed. Consecutive failures: {fail_count}")
if fail_count >= 3: if fail_count >= 3:
reset_wifi()
if fail_count >= 6:
fail_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") 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...") print(f"Ping failed 3 times at {fail_time}. Writing fail-file and rebooting...")
@@ -93,7 +121,7 @@ def main():
reboot_computer() reboot_computer()
break break
time.sleep(10) time.sleep(10)
if __name__ == "__main__": if __name__ == "__main__":
main() main()
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash
# IP address of your router to test connectivity
SERVER=192.168.1.1
# Only send 2 pings, waiting 2 seconds maximum
ping -c 2 -W 2 $SERVER > /dev/null 2>&1
if [ $? -ne 0 ]; then
echo "$(date) - WiFi connection lost. Restarting wlan0..." >> /var/log/wifi_watchdog.log
# For newer Pi OS (NetworkManager)
nmcli radio wifi off
sleep 2
nmcli radio wifi on
# Older Pi OS
# ip link set wlan0 down
# sleep 2
# ip link set wlan0 up
fi