Fix state determination in tplink kasa lights.
[python_utils.git] / smart_home / lights.py
index 76b1500d5490693c939a025a49ecf886f2e38dab..64f2105ffe8a4de0864e95a14d2b05703010a2bb 100644 (file)
@@ -46,14 +46,16 @@ def tplink_light_command(command: str) -> bool:
     result = os.system(command)
     signal = result & 0xFF
     if signal != 0:
-        logger.warning(f'{command} died with signal {signal}')
-        logging_utils.hlog("%s died with signal %d" % (command, signal))
+        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:
-            logger.warning(f'{command} failed, exited {exit_value}')
-            logging_utils.hlog("%s failed, exit %d" % (command, exit_value))
+            msg = f'{command} failed, exited {exit_value}'
+            logger.warning(msg)
+            logging_utils.hlog(msg)
             return False
     logger.debug(f'{command} succeeded.')
     return True
@@ -77,6 +79,10 @@ class BaseLight(dev.Device):
         color = color.lower()
         return ansi.COLOR_NAMES_TO_RGB.get(color, None)
 
+    @abstractmethod
+    def status(self) -> str:
+        pass
+
     @abstractmethod
     def turn_on(self) -> bool:
         pass
@@ -130,6 +136,12 @@ class GoogleLight(BaseLight):
             ask_google(f"turn {self.goog_name()} off")
         )
 
+    @overrides
+    def status(self) -> str:
+        if self.is_on():
+            return 'ON'
+        return 'off'
+
     @overrides
     def is_on(self) -> bool:
         r = ask_google(f"is {self.goog_name()} on?")
@@ -211,6 +223,13 @@ class TuyaLight(BaseLight):
     def get_status(self) -> Dict[str, Any]:
         return self.bulb.status()
 
+    @overrides
+    def status(self) -> str:
+        ret = ''
+        for k, v in self.bulb.status().items():
+            ret += f'{k} = {v}\n'
+        return ret
+
     @overrides
     def turn_on(self) -> bool:
         self.bulb.turn_on()
@@ -237,12 +256,14 @@ class TuyaLight(BaseLight):
 
     @overrides
     def set_dimmer_level(self, level: int) -> bool:
+        logger.debug(f'Setting brightness to {level}')
         self.bulb.set_brightness(level)
         return True
 
     @overrides
     def make_color(self, color: str) -> bool:
         rgb = BaseLight.parse_color_string(color)
+        logger.debug(f'Light color: {color} -> {rgb}')
         if rgb is not None:
             self.bulb.set_colour(rgb[0], rgb[1], rgb[2])
             return True
@@ -299,7 +320,10 @@ class TPLinkLight(BaseLight):
 
     @overrides
     def is_on(self) -> bool:
-        return self.get_on_duration_seconds() > 0
+        self.info = self.get_info()
+        if self.info is None:
+            raise Exception('Unable to get info?')
+        return self.info.get("relay_state", 0) == 1
 
     @overrides
     def is_off(self) -> bool:
@@ -315,10 +339,12 @@ class TPLinkLight(BaseLight):
     def get_info(self) -> Optional[Dict]:
         cmd = self.get_cmdline() + "-c info"
         out = subprocess.getoutput(cmd)
+        logger.debug(f'RAW OUT> {out}')
         out = re.sub("Sent:.*\n", "", out)
         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:
@@ -328,6 +354,13 @@ class TPLinkLight(BaseLight):
             self.info_ts = None
             return None
 
+    @overrides
+    def status(self) -> str:
+        ret = ''
+        for k, v in self.get_info().items():
+            ret += f'{k} = {v}\n'
+        return ret
+
     def get_on_duration_seconds(self, child: str = None) -> int:
         self.info = self.get_info()
         if child is None: