summaryrefslogtreecommitdiff
path: root/smart_home/tplink_utils.py
blob: 91cdd755903670d0013d5de7e19353c8cc119b70 (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
#!/usr/bin/env python3

"""Wrapper functions for calling tplink.py"""

import json
import logging
import os
import re
import subprocess
import sys
from typing import Dict, Optional

import logging_utils
from decorator_utils import timeout

logger = logging.getLogger(__name__)


@timeout(10.0, use_signals=False, error_message="Timed out waiting for tplink.py")
def tplink_command(command: str) -> bool:
    result = os.system(command)
    signal = result & 0xFF
    if signal != 0:
        msg = f'{command} died with signal {signal}'
        logger.warning(msg)
        logging_utils.hlog(msg)
        return False
    else:
        exit_value = result >> 8
        if exit_value != 0:
            msg = f'{command} failed, exited {exit_value}'
            logger.warning(msg)
            logging_utils.hlog(msg)
            return False
    logger.debug('%s succeeded.', command)
    return True


@timeout(10.0, use_signals=False, error_message="Timed out waiting for tplink.py")
def tplink_get_info(cmd: str) -> Optional[Dict]:
    logger.debug('Getting tplink device status via "%s"', cmd)
    try:
        out = subprocess.getoutput(cmd)
        logger.debug('RAW OUT> %s', out)
        out = re.sub("Sent:.*\n", "", out)
        out = re.sub("Received: *", "", out)
        info = json.loads(out)["system"]["get_sysinfo"]
        logger.debug("%s", json.dumps(info, indent=4, sort_keys=True))
        return info
    except Exception as e:
        logger.exception(e)
        print(out, file=sys.stderr)
        return None