From 5fd924627113d21f956e09f9ad039ba005dbab36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20Gro=C3=9Fklo=C3=9F?= Date: Wed, 16 Jul 2025 14:46:49 +0200 Subject: [PATCH] update sensors on file change --- compose.yaml | 2 +- main.py | 37 +++++++++++++++++++++++++++++-------- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/compose.yaml b/compose.yaml index a08f993..9ad9714 100644 --- a/compose.yaml +++ b/compose.yaml @@ -21,6 +21,6 @@ services: - PUBLISH_INTERVAL_SECONDS=300 command: > sh -c " - pip install --no-cache-dir -r requirements.txt && + pip install --no-cache-dir watchdog && python main.py " diff --git a/main.py b/main.py index 8e466d4..448572f 100644 --- a/main.py +++ b/main.py @@ -14,6 +14,20 @@ 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: @@ -261,14 +275,21 @@ class GadgetbridgeMQTTPublisher: ) as client: self.mqtt_client = client await self.setup_home_assistant_entities() - while True: - 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) + + # 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() except Exception as e: self.logger.error(f"Failed to connect to MQTT broker: {e}")