diff options
Diffstat (limited to 'smart_home/tplink_utils.py')
| -rw-r--r-- | smart_home/tplink_utils.py | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/smart_home/tplink_utils.py b/smart_home/tplink_utils.py new file mode 100644 index 0000000..91cdd75 --- /dev/null +++ b/smart_home/tplink_utils.py @@ -0,0 +1,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 |
