diff options
Diffstat (limited to 'src/home/mqtt/util.py')
-rw-r--r-- | src/home/mqtt/util.py | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/src/home/mqtt/util.py b/src/home/mqtt/util.py index f71ffd8..91b6baf 100644 --- a/src/home/mqtt/util.py +++ b/src/home/mqtt/util.py @@ -1,4 +1,11 @@ import time +import os +import re +import importlib + +from ._node import MqttNode +from . import MqttModule +from typing import List def poll_tick(freq): @@ -6,3 +13,26 @@ def poll_tick(freq): while True: t += freq yield max(t - time.time(), 0) + + +def get_modules() -> List[str]: + modules = [] + for name in os.listdir(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'module')): + name = re.sub(r'\.py$', '', name) + modules.append(name) + return modules + + +def import_module(module: str): + return importlib.import_module( + f'..module.{module}', __name__) + + +def add_module(mqtt_node: MqttNode, module: str) -> MqttModule: + module = import_module(module) + if not hasattr(module, 'MODULE_NAME'): + raise RuntimeError(f'MODULE_NAME not found in module {module}') + cl = getattr(module, getattr(module, 'MODULE_NAME')) + instance = cl() + mqtt_node.add_module(instance) + return instance
\ No newline at end of file |