diff options
author | Evgeny Zinoviev <me@ch1p.io> | 2023-05-31 09:22:00 +0300 |
---|---|---|
committer | Evgeny Zinoviev <me@ch1p.io> | 2023-05-31 09:22:00 +0300 |
commit | c976495222858c4921454c9294ff73794ae56277 (patch) | |
tree | ea605604f2e8fb2108e01074a1bfb9de93f1e93f /src/mqtt_node_util.py | |
parent | b02a9c5473267da88a9182a5b06753f62b689042 (diff) |
wip
Diffstat (limited to 'src/mqtt_node_util.py')
-rwxr-xr-x | src/mqtt_node_util.py | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/src/mqtt_node_util.py b/src/mqtt_node_util.py new file mode 100755 index 0000000..674b60c --- /dev/null +++ b/src/mqtt_node_util.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +from typing import Optional +from argparse import ArgumentParser, ArgumentError + +from home.config import config +from home.mqtt import MqttNode, get_mqtt_modules, import_mqtt_module, MqttModule + +mqtt: Optional[MqttNode] = None + + +def add_module(module: str) -> MqttModule: + module = import_mqtt_module(module) + if not hasattr(module, 'MODULE_NAME'): + raise RuntimeError(f'MODULE_NAME not found in module {m}') + cl = getattr(module, getattr(module, 'MODULE_NAME')) + instance = cl() + mqtt.add_module(instance) + return instance + + +if __name__ == '__main__': + parser = ArgumentParser() + parser.add_argument('--node-id', type=str, required=True) + parser.add_argument('--modules', type=str, choices=get_mqtt_modules(), nargs='*', + help='mqtt modules to include') + parser.add_argument('--switch-relay', choices=[0, 1], type=int, + help='send relay state') + parser.add_argument('--switch-relay-secret', type=str, + help='secret password to switch relay') + + config.load('mqtt_util', parser=parser) + arg = parser.parse_args() + + if (arg.switch_relay is not None or arg.switch_relay_secret is not None) and 'relay' not in arg.modules: + raise ArgumentError(None, '--relay is only allowed when \'relay\' module included in --modules') + + if (arg.switch_relay is not None and arg.switch_relay_secret is None) or (arg.switch_relay is None and arg.switch_relay_secret is not None): + raise ArgumentError(None, 'both --switch-relay and --switch-relay-secret are required') + + mqtt = MqttNode(node_id=arg.node_id) + + # must-have modules + add_module('ota') + add_module('diagnostics') + + if arg.modules: + for m in arg.modules: + module_instance = add_module(m) + if m == 'relay' and arg.switch_relay is not None: + module_instance.switchpower(mqtt, + arg.switch_relay == 1, + arg.switch_relay_secret) + + mqtt.configure_tls() + try: + mqtt.connect_and_loop() + except KeyboardInterrupt: + mqtt.disconnect() |