Stop spamming the log from bg.
[python_utils.git] / smart_home / lights.py
index 44b3634cd5fb9f5c84620762701f120db8bd3977..240e7da84412f089702b7b50bd4ce5b5080ca0eb 100644 (file)
@@ -2,7 +2,6 @@
 
 """Utilities for dealing with the smart lights."""
 
-from abc import abstractmethod
 import datetime
 import json
 import logging
@@ -10,11 +9,11 @@ import os
 import re
 import subprocess
 import sys
+from abc import abstractmethod
 from typing import Any, Dict, List, Optional, Tuple
-import warnings
 
-from overrides import overrides
 import tinytuya as tt
+from overrides import overrides
 
 import ansi
 import argparse_utils
@@ -22,8 +21,8 @@ import arper
 import config
 import logging_utils
 import smart_home.device as dev
-from google_assistant import ask_google, GoogleResponse
-from decorator_utils import timeout, memoized
+from decorator_utils import memoized, timeout
+from google_assistant import GoogleResponse, ask_google
 
 logger = logging.getLogger(__name__)
 
@@ -40,16 +39,13 @@ args.add_argument(
 )
 
 
-@timeout(
-    5.0, use_signals=False, error_message="Timed out waiting for tplink.py"
-)
+@timeout(5.0, use_signals=False, error_message="Timed out waiting for tplink.py")
 def tplink_light_command(command: str) -> bool:
     result = os.system(command)
     signal = result & 0xFF
     if signal != 0:
         msg = f'{command} died with signal {signal}'
         logger.warning(msg)
-        warnings.warn(msg)
         logging_utils.hlog(msg)
         return False
     else:
@@ -57,7 +53,6 @@ def tplink_light_command(command: str) -> bool:
         if exit_value != 0:
             msg = f'{command} failed, exited {exit_value}'
             logger.warning(msg)
-            warnings.warn(msg)
             logging_utils.hlog(msg)
             return False
     logger.debug(f'{command} succeeded.')
@@ -72,9 +67,9 @@ class BaseLight(dev.Device):
     def parse_color_string(color: str) -> Optional[Tuple[int, int, int]]:
         m = re.match(
             'r#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])',
-            color
+            color,
         )
-        if m is not None and len(m.group) == 3:
+        if m is not None and len(m.groups()) == 3:
             red = int(m.group(0), 16)
             green = int(m.group(1), 16)
             blue = int(m.group(2), 16)
@@ -150,7 +145,9 @@ class GoogleLight(BaseLight):
         r = ask_google(f"is {self.goog_name()} on?")
         if not r.success:
             return False
-        return 'is on' in r.audio_transcription
+        if r.audio_transcription is not None:
+            return 'is on' in r.audio_transcription
+        raise Exception("Can't reach Google?!")
 
     @overrides
     def is_off(self) -> bool:
@@ -166,11 +163,12 @@ class GoogleLight(BaseLight):
 
         # the bookcase one is set to 40% bright
         txt = r.audio_transcription
-        m = re.search(r"(\d+)% bright", txt)
-        if m is not None:
-            return int(m.group(1))
-        if "is off" in txt:
-            return 0
+        if txt is not None:
+            m = re.search(r"(\d+)% bright", txt)
+            if m is not None:
+                return int(m.group(1))
+            if "is off" in txt:
+                return 0
         return None
 
     @overrides
@@ -304,9 +302,7 @@ class TPLinkLight(BaseLight):
     def get_children(self) -> List[str]:
         return self.children
 
-    def command(
-        self, cmd: str, child: str = None, extra_args: str = None
-    ) -> bool:
+    def command(self, cmd: str, child: str = None, extra_args: str = None) -> bool:
         cmd = self.get_cmdline(child) + f"-c {cmd}"
         if extra_args is not None:
             cmd += f" {extra_args}"
@@ -326,7 +322,7 @@ class TPLinkLight(BaseLight):
         self.info = self.get_info()
         if self.info is None:
             raise Exception('Unable to get info?')
-        return self.info.get("relay_state", "0") == "1"
+        return self.info.get("relay_state", 0) == 1
 
     @overrides
     def is_off(self) -> bool:
@@ -336,9 +332,7 @@ class TPLinkLight(BaseLight):
     def make_color(self, color: str) -> bool:
         raise NotImplementedError
 
-    @timeout(
-        10.0, use_signals=False, error_message="Timed out waiting for tplink.py"
-    )
+    @timeout(10.0, use_signals=False, error_message="Timed out waiting for tplink.py")
     def get_info(self) -> Optional[Dict]:
         cmd = self.get_cmdline() + "-c info"
         out = subprocess.getoutput(cmd)
@@ -347,6 +341,7 @@ class TPLinkLight(BaseLight):
         out = re.sub("Received: *", "", out)
         try:
             self.info = json.loads(out)["system"]["get_sysinfo"]
+            logger.debug(json.dumps(self.info, indent=4, sort_keys=True))
             self.info_ts = datetime.datetime.now()
             return self.info
         except Exception as e: