remove watchdog

This commit is contained in:
Oliver Großkloß 2025-07-16 17:38:02 +02:00
parent 5fd9246271
commit 65db33493a
4 changed files with 29 additions and 103 deletions

View File

@ -21,6 +21,11 @@ services:
- PUBLISH_INTERVAL_SECONDS=300 - PUBLISH_INTERVAL_SECONDS=300
command: > command: >
sh -c " sh -c "
pip install --no-cache-dir watchdog && pip install --no-cache-dir aiomqtt &&
python main.py python main.py
" "
healthcheck:
test: ["CMD", "python", "healthcheck.py"]
interval: 1m
timeout: 10s
retries: 3

View File

@ -5,13 +5,12 @@ Health check script for Gadgetbridge MQTT integration
import os import os
import sqlite3 import sqlite3
import paho.mqtt.client as mqtt import socket
from datetime import datetime, timedelta
def check_database(): def check_database():
"""Check if Gadgetbridge database is accessible""" """Check if Gadgetbridge database is accessible"""
db_path = os.getenv("GADGETBRIDGE_DB_PATH", "/data/Gadgetbridge") db_path = os.getenv("GADGETBRIDGE_DB_PATH", "/data/Gadgetbridge.db")
if not os.path.exists(db_path): if not os.path.exists(db_path):
return False return False
@ -20,40 +19,29 @@ def check_database():
conn = sqlite3.connect(db_path) conn = sqlite3.connect(db_path)
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute( cursor.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name='MI_BAND_ACTIVITY_SAMPLE'" "SELECT name FROM sqlite_master WHERE type='table' AND name='XIAOMI_ACTIVITY_SAMPLE'"
) )
result = cursor.fetchone() result = cursor.fetchone()
conn.close() conn.close()
return result is not None return result is not None
except: except Exception:
return False return False
def check_mqtt_connection(): def check_mqtt_connection():
"""Check MQTT broker connectivity""" """Check MQTT broker TCP connectivity (no paho)"""
host = os.getenv("MQTT_BROKER", "localhost")
port = int(os.getenv("MQTT_PORT", "1883"))
try: try:
client = mqtt.Client("healthcheck") with socket.create_connection((host, port), timeout=5):
if os.getenv("MQTT_USERNAME"): return True
client.username_pw_set( except Exception:
os.getenv("MQTT_USERNAME"), os.getenv("MQTT_PASSWORD")
)
client.connect(
os.getenv("MQTT_BROKER", "localhost"),
int(os.getenv("MQTT_PORT", "1883")),
10,
)
client.disconnect()
return True
except:
return False return False
def main(): def main():
"""Main health check"""
db_ok = check_database() db_ok = check_database()
mqtt_ok = check_mqtt_connection() mqtt_ok = check_mqtt_connection()
if db_ok and mqtt_ok: if db_ok and mqtt_ok:
print("Health check passed") print("Health check passed")
exit(0) exit(0)

47
main.py
View File

@ -14,20 +14,6 @@ from typing import Dict, List, Optional
import asyncio import asyncio
import aiomqtt import aiomqtt
import re import re
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class DBChangeHandler(FileSystemEventHandler):
def __init__(self, publisher):
self.publisher = publisher
def on_modified(self, event):
if event.src_path == self.publisher.db_path:
asyncio.run_coroutine_threadsafe(
self.publisher.publish_steps_data(self.publisher.get_steps_data()),
asyncio.get_event_loop(),
)
class GadgetbridgeMQTTPublisher: class GadgetbridgeMQTTPublisher:
@ -83,14 +69,14 @@ class GadgetbridgeMQTTPublisher:
"""Setup Home Assistant entities via MQTT discovery""" """Setup Home Assistant entities via MQTT discovery"""
device_info = { device_info = {
"identifiers": [self.device_name], "identifiers": [self.device_name],
"name": f"Gadgetbridge {self.device_name.title()}", "name": f"Gadgetbridge {self.device_name.replace('_', ' ').title()}",
"model": "Fitness Tracker", "model": "Fitness Tracker",
"manufacturer": "Gadgetbridge", "manufacturer": "Gadgetbridge",
} }
# Daily steps sensor # Daily steps sensor
steps_config = { steps_config = {
"name": f"{self.device_name.title()} Daily Steps", "name": f"{self.device_name.replace('_', ' ').title()} Daily Steps",
"unique_id": f"{self.device_name}_daily_steps", "unique_id": f"{self.device_name}_daily_steps",
"state_topic": f"gadgetbridge/{self.device_name}/steps/daily", "state_topic": f"gadgetbridge/{self.device_name}/steps/daily",
"unit_of_measurement": "steps", "unit_of_measurement": "steps",
@ -101,7 +87,7 @@ class GadgetbridgeMQTTPublisher:
# Weekly steps sensor # Weekly steps sensor
weekly_steps_config = { weekly_steps_config = {
"name": f"{self.device_name.title()} Weekly Steps", "name": f"{self.device_name.replace('_', ' ').title()} Weekly Steps",
"unique_id": f"{self.device_name}_weekly_steps", "unique_id": f"{self.device_name}_weekly_steps",
"state_topic": f"gadgetbridge/{self.device_name}/steps/weekly", "state_topic": f"gadgetbridge/{self.device_name}/steps/weekly",
"unit_of_measurement": "steps", "unit_of_measurement": "steps",
@ -112,7 +98,7 @@ class GadgetbridgeMQTTPublisher:
# Monthly steps sensor # Monthly steps sensor
monthly_steps_config = { monthly_steps_config = {
"name": f"{self.device_name.title()} Monthly Steps", "name": f"{self.device_name.replace('_', ' ').title()} Monthly Steps",
"unique_id": f"{self.device_name}_monthly_steps", "unique_id": f"{self.device_name}_monthly_steps",
"state_topic": f"gadgetbridge/{self.device_name}/steps/monthly", "state_topic": f"gadgetbridge/{self.device_name}/steps/monthly",
"unit_of_measurement": "steps", "unit_of_measurement": "steps",
@ -123,7 +109,7 @@ class GadgetbridgeMQTTPublisher:
# Last sync sensor # Last sync sensor
last_sync_config = { last_sync_config = {
"name": f"{self.device_name.title()} Last Sync", "name": f"{self.device_name.replace('_', ' ').title()} Last Sync",
"unique_id": f"{self.device_name}_last_sync", "unique_id": f"{self.device_name}_last_sync",
"state_topic": f"gadgetbridge/{self.device_name}/last_sync", "state_topic": f"gadgetbridge/{self.device_name}/last_sync",
"icon": "mdi:sync", "icon": "mdi:sync",
@ -275,21 +261,14 @@ class GadgetbridgeMQTTPublisher:
) as client: ) as client:
self.mqtt_client = client self.mqtt_client = client
await self.setup_home_assistant_entities() await self.setup_home_assistant_entities()
while True:
# Watch for DB changes steps_data = self.get_steps_data()
event_handler = DBChangeHandler(self) if steps_data:
observer = Observer() await self.publish_steps_data(steps_data)
observer.schedule( self.logger.info(
event_handler, path=os.path.dirname(self.db_path), recursive=False f"Sleeping for {self.publish_interval} seconds before next publish..."
) )
observer.start() await asyncio.sleep(self.publish_interval)
try:
while True:
await asyncio.sleep(1)
finally:
observer.stop()
observer.join()
except Exception as e: except Exception as e:
self.logger.error(f"Failed to connect to MQTT broker: {e}") self.logger.error(f"Failed to connect to MQTT broker: {e}")

View File

@ -1,46 +0,0 @@
#!/usr/bin/env python3
"""
Setup script for Gadgetbridge MQTT integration
"""
import os
import subprocess
import logging
def setup_cron_job():
"""Setup cron job for periodic execution"""
cron_schedule = "*/15 * * * *" # Every 15 minutes
cron_command = (
f"cd /app && /usr/local/bin/python main.py >> /app/logs/cron.log 2>&1"
)
# Create cron job
with open("/tmp/gadgetbridge_cron", "w") as f:
f.write(f"{cron_schedule} {cron_command}\n")
# Install cron job
subprocess.run(["crontab", "/tmp/gadgetbridge_cron"], check=True)
# Start cron service
subprocess.run(["service", "cron", "start"], check=True)
print("Cron job setup completed - running every 15 minutes")
def create_directories():
"""Create necessary directories"""
os.makedirs("/app/logs", exist_ok=True)
print("Created log directory")
def run_initial_setup():
"""Run initial discovery setup"""
subprocess.run(["/usr/local/bin/python", "/app/main.py"], check=True)
print("Initial MQTT discovery setup completed")
if __name__ == "__main__":
create_directories()
setup_cron_job()
run_initial_setup()