summaryrefslogtreecommitdiff
path: root/src/mqtt_node_util.py
blob: d7ee1271b31624d022015757c8950b2e4b63d006 (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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python3
import os.path
from time import sleep
from typing import Optional
from argparse import ArgumentParser, ArgumentError

from home.config import config
from home.mqtt import MqttNode, MqttModule, MqttWrapper, get_mqtt_modules

mqtt_node: Optional[MqttNode] = None
mqtt: Optional[MqttWrapper] = None


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('--push-ota', type=str, metavar='OTA_FILENAME',
                        help='push ota, argument receives filename')
    parser.add_argument('--node-secret', type=str,
                        help='node admin password')

    config.load('mqtt_util', parser=parser)
    arg = parser.parse_args()

    if (arg.switch_relay is not None or arg.node_secret is not None) and 'relay' not in arg.modules:
        raise ArgumentError(None, '--relay is only allowed when \'relay\' module included in --modules')

    mqtt = MqttWrapper(randomize_client_id=True)
    mqtt_node = MqttNode(node_id=arg.node_id)

    mqtt.add_node(mqtt_node)

    # must-have modules
    ota_module = mqtt_node.load_module('ota')
    mqtt_node.load_module('diagnostics')

    if arg.modules:
        for m in arg.modules:
            module_instance = mqtt_node.load_module(m)
            if m == 'relay' and arg.switch_relay is not None:
                if not arg.node_secret:
                    raise ArgumentError(None, '--switch-relay requires --node-secret')
                module_instance.switchpower(mqtt_node,
                                            arg.switch_relay == 1,
                                            arg.node_secret)

    mqtt.configure_tls()
    try:
        mqtt.connect_and_loop(loop_forever=False)

        if arg.push_ota:
            if not os.path.exists(arg.push_ota):
                raise OSError(f'--push-ota: file \"{arg.push_ota}\" does not exists')
            if not arg.node_secret:
                raise ArgumentError(None, 'pushing OTA requires --node-secret')

            ota_module.push_ota(arg.node_secret, arg.push_ota, 1)

        while True:
            sleep(0.1)

    except KeyboardInterrupt:
        mqtt.disconnect()