update sensors on file change
This commit is contained in:
parent
506dc8a0ef
commit
5fd9246271
@ -21,6 +21,6 @@ services:
|
|||||||
- PUBLISH_INTERVAL_SECONDS=300
|
- PUBLISH_INTERVAL_SECONDS=300
|
||||||
command: >
|
command: >
|
||||||
sh -c "
|
sh -c "
|
||||||
pip install --no-cache-dir -r requirements.txt &&
|
pip install --no-cache-dir watchdog &&
|
||||||
python main.py
|
python main.py
|
||||||
"
|
"
|
||||||
|
|||||||
35
main.py
35
main.py
@ -14,6 +14,20 @@ 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:
|
||||||
@ -261,14 +275,21 @@ 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:
|
|
||||||
steps_data = self.get_steps_data()
|
# Watch for DB changes
|
||||||
if steps_data:
|
event_handler = DBChangeHandler(self)
|
||||||
await self.publish_steps_data(steps_data)
|
observer = Observer()
|
||||||
self.logger.info(
|
observer.schedule(
|
||||||
f"Sleeping for {self.publish_interval} seconds before next publish..."
|
event_handler, path=os.path.dirname(self.db_path), recursive=False
|
||||||
)
|
)
|
||||||
await asyncio.sleep(self.publish_interval)
|
observer.start()
|
||||||
|
|
||||||
|
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}")
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user