restart app on config.yml change

This commit is contained in:
Stephan Leuschner
2023-11-19 19:18:37 -05:00
parent 069087c48b
commit 453537ff68
2 changed files with 45 additions and 27 deletions

View File

@@ -10,6 +10,11 @@ import yaml
from uuid import getnode as get_mac from uuid import getnode as get_mac
from panel import LovelaceUIPanel from panel import LovelaceUIPanel
import os import os
import threading
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
import signal
import sys
@@ -141,36 +146,48 @@ def setup_panels():
libs.panel_cmd.page_type( libs.panel_cmd.page_type(
settings_panel["panelSendTopic"], "pageStartup") settings_panel["panelSendTopic"], "pageStartup")
#if __name__ == '__main__': def config_watch():
# CONFIG_FILE = os.getenv('CONFIG_FILE') class ConfigChangeEventHandler(FileSystemEventHandler):
# if not CONFIG_FILE: def __init__(self, base_paths):
# CONFIG_FILE = 'config.yml' self.base_paths = base_paths
# get_config(CONFIG_FILE)
#connect()
#loop()
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler): def dispatch(self, event):
def on_modified(self, event): for base_path in self.base_paths:
print(f'event type: {event.event_type} path : {event.src_path}') if event.src_path.endswith(base_path):
def on_created(self, event): super(ConfigChangeEventHandler, self).dispatch(event)
print(f'event type: {event.event_type} path : {event.src_path}') return
def on_deleted(self, event):
print(f'event type: {event.event_type} path : {event.src_path}')
if __name__ == "__main__": def on_modified(self, event):
event_handler = MyHandler() logging.info('Modification detected. Reloading panels.')
pid = os.getpid()
os.kill(pid, signal.SIGTERM)
logging.info('Watching for changes in config file')
project_files = []
project_files.append("/share/config.yml")
handler = ConfigChangeEventHandler(project_files)
observer = Observer() observer = Observer()
observer.schedule(event_handler, path='config.yml', recursive=False) observer.schedule(handler, path='/share', recursive=True)
observer.start() observer.start()
while True:
time.sleep(1)
try: def signal_handler(signum, frame):
while True: # Handle the signal (e.g., SIGHUP) for triggering a restart
time.sleep(1) print(f"Received signal {signum}. Initiating restart...")
except KeyboardInterrupt: restart_program()
observer.stop()
observer.join()
def restart_program():
print("Restarting the program...")
python = sys.executable
os.execl(python, python, *sys.argv)
if __name__ == '__main__':
CONFIG_FILE = os.getenv('CONFIG_FILE')
if not CONFIG_FILE:
CONFIG_FILE = 'config.yml'
get_config(CONFIG_FILE)
signal.signal(signal.SIGTERM, signal_handler)
threading.Thread(target=config_watch).start()
connect()
loop()

View File

@@ -6,3 +6,4 @@ django-environ
python-dateutil python-dateutil
scheduler scheduler
babel babel
watchdog