summaryrefslogtreecommitdiff
path: root/src/home/mqtt/util.py
blob: 91b6bafa83b4829f5e577fca45f4a5c516d726a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import time
import os
import re
import importlib

from ._node import MqttNode
from . import MqttModule
from typing import List


def poll_tick(freq):
    t = time.time()
    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