remove watchdog
This commit is contained in:
parent
5fd9246271
commit
65db33493a
@ -21,6 +21,11 @@ services:
|
||||
- PUBLISH_INTERVAL_SECONDS=300
|
||||
command: >
|
||||
sh -c "
|
||||
pip install --no-cache-dir watchdog &&
|
||||
pip install --no-cache-dir aiomqtt &&
|
||||
python main.py
|
||||
"
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "healthcheck.py"]
|
||||
interval: 1m
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
|
||||
@ -5,13 +5,12 @@ Health check script for Gadgetbridge MQTT integration
|
||||
|
||||
import os
|
||||
import sqlite3
|
||||
import paho.mqtt.client as mqtt
|
||||
from datetime import datetime, timedelta
|
||||
import socket
|
||||
|
||||
|
||||
def check_database():
|
||||
"""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):
|
||||
return False
|
||||
@ -20,40 +19,29 @@ def check_database():
|
||||
conn = sqlite3.connect(db_path)
|
||||
cursor = conn.cursor()
|
||||
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()
|
||||
conn.close()
|
||||
return result is not None
|
||||
except:
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
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:
|
||||
client = mqtt.Client("healthcheck")
|
||||
if os.getenv("MQTT_USERNAME"):
|
||||
client.username_pw_set(
|
||||
os.getenv("MQTT_USERNAME"), os.getenv("MQTT_PASSWORD")
|
||||
)
|
||||
|
||||
client.connect(
|
||||
os.getenv("MQTT_BROKER", "localhost"),
|
||||
int(os.getenv("MQTT_PORT", "1883")),
|
||||
10,
|
||||
)
|
||||
client.disconnect()
|
||||
with socket.create_connection((host, port), timeout=5):
|
||||
return True
|
||||
except:
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
"""Main health check"""
|
||||
db_ok = check_database()
|
||||
mqtt_ok = check_mqtt_connection()
|
||||
|
||||
if db_ok and mqtt_ok:
|
||||
print("Health check passed")
|
||||
exit(0)
|
||||
|
||||
45
main.py
45
main.py
@ -14,20 +14,6 @@ from typing import Dict, List, Optional
|
||||
import asyncio
|
||||
import aiomqtt
|
||||
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:
|
||||
@ -83,14 +69,14 @@ class GadgetbridgeMQTTPublisher:
|
||||
"""Setup Home Assistant entities via MQTT discovery"""
|
||||
device_info = {
|
||||
"identifiers": [self.device_name],
|
||||
"name": f"Gadgetbridge {self.device_name.title()}",
|
||||
"name": f"Gadgetbridge {self.device_name.replace('_', ' ').title()}",
|
||||
"model": "Fitness Tracker",
|
||||
"manufacturer": "Gadgetbridge",
|
||||
}
|
||||
|
||||
# Daily steps sensor
|
||||
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",
|
||||
"state_topic": f"gadgetbridge/{self.device_name}/steps/daily",
|
||||
"unit_of_measurement": "steps",
|
||||
@ -101,7 +87,7 @@ class GadgetbridgeMQTTPublisher:
|
||||
|
||||
# Weekly steps sensor
|
||||
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",
|
||||
"state_topic": f"gadgetbridge/{self.device_name}/steps/weekly",
|
||||
"unit_of_measurement": "steps",
|
||||
@ -112,7 +98,7 @@ class GadgetbridgeMQTTPublisher:
|
||||
|
||||
# Monthly steps sensor
|
||||
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",
|
||||
"state_topic": f"gadgetbridge/{self.device_name}/steps/monthly",
|
||||
"unit_of_measurement": "steps",
|
||||
@ -123,7 +109,7 @@ class GadgetbridgeMQTTPublisher:
|
||||
|
||||
# Last sync sensor
|
||||
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",
|
||||
"state_topic": f"gadgetbridge/{self.device_name}/last_sync",
|
||||
"icon": "mdi:sync",
|
||||
@ -275,21 +261,14 @@ class GadgetbridgeMQTTPublisher:
|
||||
) as client:
|
||||
self.mqtt_client = client
|
||||
await self.setup_home_assistant_entities()
|
||||
|
||||
# Watch for DB changes
|
||||
event_handler = DBChangeHandler(self)
|
||||
observer = Observer()
|
||||
observer.schedule(
|
||||
event_handler, path=os.path.dirname(self.db_path), recursive=False
|
||||
)
|
||||
observer.start()
|
||||
|
||||
try:
|
||||
while True:
|
||||
await asyncio.sleep(1)
|
||||
finally:
|
||||
observer.stop()
|
||||
observer.join()
|
||||
steps_data = self.get_steps_data()
|
||||
if steps_data:
|
||||
await self.publish_steps_data(steps_data)
|
||||
self.logger.info(
|
||||
f"Sleeping for {self.publish_interval} seconds before next publish..."
|
||||
)
|
||||
await asyncio.sleep(self.publish_interval)
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to connect to MQTT broker: {e}")
|
||||
|
||||
|
||||
46
setup.py
46
setup.py
@ -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()
|
||||
Loading…
Reference in New Issue
Block a user