# Watchdog dla ibsystem2mqtt
HEALTH_URL="http://127.0.0.1:8080/health"
LOG_FILE="/tmp/ibsystem2mqtt_watchdog.log"
MAX_FAILURES=3
FAILURE_COUNT_FILE="/tmp/ibsystem2mqtt_failures"
log() { echo "$(date '+%Y-%m-%d %H:%M:%S') $1" >> "$LOG_FILE"; }
check_health() {
response=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "$HEALTH_URL" 2>/dev/null)
[ "$response" = "200" ]
}
reset_failures() { echo "0" > "$FAILURE_COUNT_FILE"; }
increment_failures() {
[ -f "$FAILURE_COUNT_FILE" ] && count=$(cat "$FAILURE_COUNT_FILE") || count=0
count=$((count + 1))
echo "$count" > "$FAILURE_COUNT_FILE"
echo "$count"
}
if check_health; then
reset_failures
exit 0
fi
failures=$(increment_failures)
log "Health check failed ($failures/$MAX_FAILURES)"
if [ "$failures" -ge "$MAX_FAILURES" ]; then
log "Max failures reached, restarting"
pid=$(pgrep -f 'ibsystem2mqtt' | head -1)
[ -n "$pid" ] && kill "$pid" 2>/dev/null && sleep 3
cd /ibsystem
nohup python3 ibsystem2mqtt_v5.py -c config.yaml >> /tmp/ibsystem2mqtt_stdout.log 2>&1 &
log "Restarted (new PID: $!)"
reset_failures
fi