update sensors on file change
This commit is contained in:
parent
506dc8a0ef
commit
5fd9246271
@ -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
|
||||
"
|
||||
|
||||
37
main.py
37
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}")
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user