import signal
import sys
-import os
import json
import asyncio
-import pyinotify
+import asyncinotify
-from controlpi import run, PluginConf
+import controlpi
from typing import Dict
print(f"Shutting down on signal {sig.name}.")
for task in asyncio.all_tasks():
task.cancel()
+ global restart
+ restart = False
async def add_signal_handlers() -> None:
loop.add_signal_handler(sig, lambda s=sig: asyncio.create_task(shutdown(s)))
-def read_configuration() -> Dict[str, PluginConf]:
+def read_configuration() -> Dict[str, controlpi.PluginConf]:
"""Read configuration from JSON file."""
conf = {}
try:
return conf
-class ConfigHandler(pyinotify.ProcessEvent):
- """Handler for changes of the configuration file on disk."""
-
- def process_IN_MODIFY(self, event):
- """Cancel all tasks if configuration file changed."""
- if event.pathname == os.path.abspath(sys.argv[1]):
- print(f"Configuration file modified: {event.pathname}")
+async def watch_config() -> None:
+ """Watch the configuration file for modifications."""
+ with asyncinotify.Inotify() as inotify:
+ inotify.add_watch(sys.argv[1], asyncinotify.Mask.MODIFY)
+ async for event in inotify:
+ print("Configuration file modified.")
for task in asyncio.all_tasks():
task.cancel()
-async def add_config_change_handler() -> pyinotify.AsyncioNotifier:
- """Add handler for configuration file."""
- wm = pyinotify.WatchManager()
- loop = asyncio.get_running_loop()
- notifier = pyinotify.AsyncioNotifier(wm, loop, default_proc_fun=ConfigHandler())
- wm.add_watch(os.path.dirname(sys.argv[1]), pyinotify.ALL_EVENTS)
- return notifier
-
-
async def main() -> None:
"""Set up signal handlers, read configuration file and run system."""
await add_signal_handlers()
- notifier = await add_config_change_handler()
conf = read_configuration()
- await run(conf)
- notifier.stop()
+ await asyncio.gather(controlpi.run(conf), watch_config())
if __name__ == "__main__":
- asyncio.run(main())
+ global restart
+ restart = True
+ while restart:
+ try:
+ asyncio.run(main())
+ except asyncio.exceptions.CancelledError:
+ pass