3 """Utilities for dealing with the smart lights."""
5 from abc import abstractmethod
13 from typing import Any, Dict, List, Optional, Tuple
15 from overrides import overrides
23 import smart_home.device as dev
24 from google_assistant import ask_google, GoogleResponse
25 from decorator_utils import timeout, memoized
27 logger = logging.getLogger(__name__)
29 args = config.add_commandline_args(
30 f"Smart Lights ({__file__})",
31 "Args related to smart lights.",
34 '--smart_lights_tplink_location',
35 default='/home/scott/bin/tplink.py',
37 help='The location of the tplink.py helper',
38 type=argparse_utils.valid_filename,
43 5.0, use_signals=False, error_message="Timed out waiting for tplink.py"
45 def tplink_light_command(command: str) -> bool:
46 result = os.system(command)
47 signal = result & 0xFF
49 logger.warning(f'{command} died with signal {signal}')
50 logging_utils.hlog("%s died with signal %d" % (command, signal))
53 exit_value = result >> 8
55 logger.warning(f'{command} failed, exited {exit_value}')
56 logging_utils.hlog("%s failed, exit %d" % (command, exit_value))
58 logger.debug(f'{command} succeeded.')
62 class BaseLight(dev.Device):
63 def __init__(self, name: str, mac: str, keywords: str = "") -> None:
64 super().__init__(name.strip(), mac.strip(), keywords)
67 def parse_color_string(color: str) -> Optional[Tuple[int, int, int]]:
69 '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])',
72 if m is not None and len(m.group) == 3:
73 red = int(m.group(0), 16)
74 green = int(m.group(1), 16)
75 blue = int(m.group(2), 16)
76 return (red, green, blue)
78 return ansi.COLOR_NAMES_TO_RGB.get(color, None)
81 def status(self) -> str:
85 def turn_on(self) -> bool:
89 def turn_off(self) -> bool:
93 def is_on(self) -> bool:
97 def is_off(self) -> bool:
101 def get_dimmer_level(self) -> Optional[int]:
105 def set_dimmer_level(self, level: int) -> bool:
109 def make_color(self, color: str) -> bool:
113 class GoogleLight(BaseLight):
114 def __init__(self, name: str, mac: str, keywords: str = "") -> None:
115 super().__init__(name, mac, keywords)
117 def goog_name(self) -> str:
118 name = self.get_name()
119 return name.replace("_", " ")
122 def parse_google_response(response: GoogleResponse) -> bool:
123 return response.success
126 def turn_on(self) -> bool:
127 return GoogleLight.parse_google_response(
128 ask_google(f"turn {self.goog_name()} on")
132 def turn_off(self) -> bool:
133 return GoogleLight.parse_google_response(
134 ask_google(f"turn {self.goog_name()} off")
138 def status(self) -> str:
144 def is_on(self) -> bool:
145 r = ask_google(f"is {self.goog_name()} on?")
148 return 'is on' in r.audio_transcription
151 def is_off(self) -> bool:
152 return not self.is_on()
155 def get_dimmer_level(self) -> Optional[int]:
156 if not self.has_keyword("dimmer"):
158 r = ask_google(f'how bright is {self.goog_name()}?')
162 # the bookcase one is set to 40% bright
163 txt = r.audio_transcription
164 m = re.search(r"(\d+)% bright", txt)
166 return int(m.group(1))
172 def set_dimmer_level(self, level: int) -> bool:
173 if not self.has_keyword("dimmer"):
175 if 0 <= level <= 100:
176 was_on = self.is_on()
177 r = ask_google(f"set {self.goog_name()} to {level} percent")
186 def make_color(self, color: str) -> bool:
187 return GoogleLight.parse_google_response(
188 ask_google(f"make {self.goog_name()} {color}")
192 class TuyaLight(BaseLight):
194 '68:C6:3A:DE:1A:94': '8844664268c63ade1a94',
195 '68:C6:3A:DE:27:1A': '8844664268c63ade271a',
196 '68:C6:3A:DE:1D:95': '8844664268c63ade1d95',
197 '68:C6:3A:DE:19:B3': '8844664268c63ade19b3',
198 '80:7D:3A:77:3B:F5': '07445340807d3a773bf5',
199 '80:7D:3A:58:37:02': '07445340807d3a583702',
202 '68:C6:3A:DE:1A:94': '237f19b1b3d49c36',
203 '68:C6:3A:DE:27:1A': '237f19b1b3d49c36',
204 '68:C6:3A:DE:1D:95': '04b90fc5cd7625d8',
205 '68:C6:3A:DE:19:B3': '2d601f2892f1aefd',
206 '80:7D:3A:77:3B:F5': '27ab921fe4633519',
207 '80:7D:3A:58:37:02': '8559b5416bfa0c05',
210 def __init__(self, name: str, mac: str, keywords: str = "") -> None:
211 super().__init__(name, mac, keywords)
213 if mac not in TuyaLight.ids_by_mac or mac not in TuyaLight.keys_by_mac:
214 raise Exception(f'{mac} is unknown; add it to ids_by_mac and keys_by_mac')
215 self.devid = TuyaLight.ids_by_mac[mac]
216 self.key = TuyaLight.keys_by_mac[mac]
217 self.arper = arper.Arper()
219 self.bulb = tt.BulbDevice(self.devid, ip, local_key=self.key)
221 def get_status(self) -> Dict[str, Any]:
222 return self.bulb.status()
225 def status(self) -> str:
227 for k, v in self.bulb.status().items():
228 ret += f'{k} = {v}\n'
232 def turn_on(self) -> bool:
237 def turn_off(self) -> bool:
242 def is_on(self) -> bool:
243 s = self.get_status()
247 def is_off(self) -> bool:
248 return not self.is_on()
251 def get_dimmer_level(self) -> Optional[int]:
252 s = self.get_status()
256 def set_dimmer_level(self, level: int) -> bool:
257 logger.debug(f'Setting brightness to {level}')
258 self.bulb.set_brightness(level)
262 def make_color(self, color: str) -> bool:
263 rgb = BaseLight.parse_color_string(color)
264 logger.debug(f'Light color: {color} -> {rgb}')
266 self.bulb.set_colour(rgb[0], rgb[1], rgb[2])
271 class TPLinkLight(BaseLight):
272 def __init__(self, name: str, mac: str, keywords: str = "") -> None:
273 super().__init__(name, mac, keywords)
274 self.children: List[str] = []
275 self.info: Optional[Dict] = None
276 self.info_ts: Optional[datetime.datetime] = None
277 if "children" in self.keywords:
278 self.info = self.get_info()
279 if self.info is not None:
280 for child in self.info["children"]:
281 self.children.append(child["id"])
284 def get_tplink_name(self) -> Optional[str]:
285 self.info = self.get_info()
286 if self.info is not None:
287 return self.info["alias"]
290 def get_cmdline(self, child: str = None) -> str:
292 f"{config.config['smart_lights_tplink_location']} -m {self.mac} "
293 f"--no_logging_console "
295 if child is not None:
296 cmd += f"-x {child} "
299 def get_children(self) -> List[str]:
303 self, cmd: str, child: str = None, extra_args: str = None
305 cmd = self.get_cmdline(child) + f"-c {cmd}"
306 if extra_args is not None:
307 cmd += f" {extra_args}"
308 logger.debug(f'About to execute {cmd}')
309 return tplink_light_command(cmd)
312 def turn_on(self, child: str = None) -> bool:
313 return self.command("on", child)
316 def turn_off(self, child: str = None) -> bool:
317 return self.command("off", child)
320 def is_on(self) -> bool:
321 self.info = self.get_info()
322 if self.info is None:
323 raise Exception('Unable to get info?')
324 return self.info.get("relay_state", "0") == "1"
327 def is_off(self) -> bool:
328 return not self.is_on()
331 def make_color(self, color: str) -> bool:
332 raise NotImplementedError
335 10.0, use_signals=False, error_message="Timed out waiting for tplink.py"
337 def get_info(self) -> Optional[Dict]:
338 cmd = self.get_cmdline() + "-c info"
339 out = subprocess.getoutput(cmd)
340 logger.debug(f'RAW OUT> {out}')
341 out = re.sub("Sent:.*\n", "", out)
342 out = re.sub("Received: *", "", out)
344 self.info = json.loads(out)["system"]["get_sysinfo"]
345 self.info_ts = datetime.datetime.now()
347 except Exception as e:
349 print(out, file=sys.stderr)
355 def status(self) -> str:
357 for k, v in self.get_info().items():
358 ret += f'{k} = {v}\n'
361 def get_on_duration_seconds(self, child: str = None) -> int:
362 self.info = self.get_info()
364 if self.info is None:
366 return int(self.info.get("on_time", "0"))
368 if self.info is None:
370 for chi in self.info.get("children", {}):
371 if chi["id"] == child:
372 return int(chi.get("on_time", "0"))
376 def get_dimmer_level(self) -> Optional[int]:
377 if not self.has_keyword("dimmer"):
379 self.info = self.get_info()
380 if self.info is None:
382 return int(self.info.get("brightness", "0"))
385 def set_dimmer_level(self, level: int) -> bool:
386 if not self.has_keyword("dimmer"):
390 + f'-j \'{{"smartlife.iot.dimmer":{{"set_brightness":{{"brightness":{level} }} }} }}\''
392 return tplink_light_command(cmd)
395 # class GoogleLightGroup(GoogleLight):
396 # def __init__(self, name: str, members: List[GoogleLight], keywords: str = "") -> None:
397 # if len(members) < 1:
398 # raise Exception("There must be at least one light in the group.")
399 # self.members = members
400 # mac = GoogleLightGroup.make_up_mac(members)
401 # super().__init__(name, mac, keywords)
404 # def make_up_mac(members: List[GoogleLight]):
405 # mac = members[0].get_mac()
407 # b[5] = int(b[5], 16) + 1
413 # def is_on(self) -> bool:
414 # r = ask_google(f"are {self.goog_name()} on?")
417 # return 'is on' in r.audio_transcription
419 # def get_dimmer_level(self) -> Optional[int]:
420 # if not self.has_keyword("dimmer"):
422 # r = ask_google(f'how bright are {self.goog_name()}?')
426 # # four lights are set to 100% brightness
427 # txt = r.audio_transcription
428 # m = re.search(r"(\d+)% bright", txt)
430 # return int(m.group(1))
431 # if "is off" in txt:
435 # def set_dimmer_level(self, level: int) -> bool:
436 # if not self.has_keyword("dimmer"):
438 # if 0 <= level <= 100:
439 # was_on = self.is_on()
440 # r = ask_google(f"set {self.goog_name()} to {level} percent")
448 # def make_color(self, color: str) -> bool:
449 # return GoogleLight.parse_google_response(
450 # ask_google(f"make {self.goog_name()} {color}")