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 msg = f'{command} died with signal {signal}'
51 logging_utils.hlog(msg)
54 exit_value = result >> 8
56 msg = f'{command} failed, exited {exit_value}'
58 logging_utils.hlog(msg)
60 logger.debug(f'{command} succeeded.')
64 class BaseLight(dev.Device):
65 def __init__(self, name: str, mac: str, keywords: str = "") -> None:
66 super().__init__(name.strip(), mac.strip(), keywords)
69 def parse_color_string(color: str) -> Optional[Tuple[int, int, int]]:
71 '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])',
74 if m is not None and len(m.group) == 3:
75 red = int(m.group(0), 16)
76 green = int(m.group(1), 16)
77 blue = int(m.group(2), 16)
78 return (red, green, blue)
80 return ansi.COLOR_NAMES_TO_RGB.get(color, None)
83 def status(self) -> str:
87 def turn_on(self) -> bool:
91 def turn_off(self) -> bool:
95 def is_on(self) -> bool:
99 def is_off(self) -> bool:
103 def get_dimmer_level(self) -> Optional[int]:
107 def set_dimmer_level(self, level: int) -> bool:
111 def make_color(self, color: str) -> bool:
115 class GoogleLight(BaseLight):
116 def __init__(self, name: str, mac: str, keywords: str = "") -> None:
117 super().__init__(name, mac, keywords)
119 def goog_name(self) -> str:
120 name = self.get_name()
121 return name.replace("_", " ")
124 def parse_google_response(response: GoogleResponse) -> bool:
125 return response.success
128 def turn_on(self) -> bool:
129 return GoogleLight.parse_google_response(
130 ask_google(f"turn {self.goog_name()} on")
134 def turn_off(self) -> bool:
135 return GoogleLight.parse_google_response(
136 ask_google(f"turn {self.goog_name()} off")
140 def status(self) -> str:
146 def is_on(self) -> bool:
147 r = ask_google(f"is {self.goog_name()} on?")
150 return 'is on' in r.audio_transcription
153 def is_off(self) -> bool:
154 return not self.is_on()
157 def get_dimmer_level(self) -> Optional[int]:
158 if not self.has_keyword("dimmer"):
160 r = ask_google(f'how bright is {self.goog_name()}?')
164 # the bookcase one is set to 40% bright
165 txt = r.audio_transcription
166 m = re.search(r"(\d+)% bright", txt)
168 return int(m.group(1))
174 def set_dimmer_level(self, level: int) -> bool:
175 if not self.has_keyword("dimmer"):
177 if 0 <= level <= 100:
178 was_on = self.is_on()
179 r = ask_google(f"set {self.goog_name()} to {level} percent")
188 def make_color(self, color: str) -> bool:
189 return GoogleLight.parse_google_response(
190 ask_google(f"make {self.goog_name()} {color}")
194 class TuyaLight(BaseLight):
196 '68:C6:3A:DE:1A:94': '8844664268c63ade1a94',
197 '68:C6:3A:DE:27:1A': '8844664268c63ade271a',
198 '68:C6:3A:DE:1D:95': '8844664268c63ade1d95',
199 '68:C6:3A:DE:19:B3': '8844664268c63ade19b3',
200 '80:7D:3A:77:3B:F5': '07445340807d3a773bf5',
201 '80:7D:3A:58:37:02': '07445340807d3a583702',
204 '68:C6:3A:DE:1A:94': '237f19b1b3d49c36',
205 '68:C6:3A:DE:27:1A': '237f19b1b3d49c36',
206 '68:C6:3A:DE:1D:95': '04b90fc5cd7625d8',
207 '68:C6:3A:DE:19:B3': '2d601f2892f1aefd',
208 '80:7D:3A:77:3B:F5': '27ab921fe4633519',
209 '80:7D:3A:58:37:02': '8559b5416bfa0c05',
212 def __init__(self, name: str, mac: str, keywords: str = "") -> None:
213 super().__init__(name, mac, keywords)
215 if mac not in TuyaLight.ids_by_mac or mac not in TuyaLight.keys_by_mac:
216 raise Exception(f'{mac} is unknown; add it to ids_by_mac and keys_by_mac')
217 self.devid = TuyaLight.ids_by_mac[mac]
218 self.key = TuyaLight.keys_by_mac[mac]
219 self.arper = arper.Arper()
221 self.bulb = tt.BulbDevice(self.devid, ip, local_key=self.key)
223 def get_status(self) -> Dict[str, Any]:
224 return self.bulb.status()
227 def status(self) -> str:
229 for k, v in self.bulb.status().items():
230 ret += f'{k} = {v}\n'
234 def turn_on(self) -> bool:
239 def turn_off(self) -> bool:
244 def is_on(self) -> bool:
245 s = self.get_status()
249 def is_off(self) -> bool:
250 return not self.is_on()
253 def get_dimmer_level(self) -> Optional[int]:
254 s = self.get_status()
258 def set_dimmer_level(self, level: int) -> bool:
259 logger.debug(f'Setting brightness to {level}')
260 self.bulb.set_brightness(level)
264 def make_color(self, color: str) -> bool:
265 rgb = BaseLight.parse_color_string(color)
266 logger.debug(f'Light color: {color} -> {rgb}')
268 self.bulb.set_colour(rgb[0], rgb[1], rgb[2])
273 class TPLinkLight(BaseLight):
274 def __init__(self, name: str, mac: str, keywords: str = "") -> None:
275 super().__init__(name, mac, keywords)
276 self.children: List[str] = []
277 self.info: Optional[Dict] = None
278 self.info_ts: Optional[datetime.datetime] = None
279 if "children" in self.keywords:
280 self.info = self.get_info()
281 if self.info is not None:
282 for child in self.info["children"]:
283 self.children.append(child["id"])
286 def get_tplink_name(self) -> Optional[str]:
287 self.info = self.get_info()
288 if self.info is not None:
289 return self.info["alias"]
292 def get_cmdline(self, child: str = None) -> str:
294 f"{config.config['smart_lights_tplink_location']} -m {self.mac} "
295 f"--no_logging_console "
297 if child is not None:
298 cmd += f"-x {child} "
301 def get_children(self) -> List[str]:
305 self, cmd: str, child: str = None, extra_args: str = None
307 cmd = self.get_cmdline(child) + f"-c {cmd}"
308 if extra_args is not None:
309 cmd += f" {extra_args}"
310 logger.debug(f'About to execute {cmd}')
311 return tplink_light_command(cmd)
314 def turn_on(self, child: str = None) -> bool:
315 return self.command("on", child)
318 def turn_off(self, child: str = None) -> bool:
319 return self.command("off", child)
322 def is_on(self) -> bool:
323 self.info = self.get_info()
324 if self.info is None:
325 raise Exception('Unable to get info?')
326 return self.info.get("relay_state", 0) == 1
329 def is_off(self) -> bool:
330 return not self.is_on()
333 def make_color(self, color: str) -> bool:
334 raise NotImplementedError
337 10.0, use_signals=False, error_message="Timed out waiting for tplink.py"
339 def get_info(self) -> Optional[Dict]:
340 cmd = self.get_cmdline() + "-c info"
341 out = subprocess.getoutput(cmd)
342 logger.debug(f'RAW OUT> {out}')
343 out = re.sub("Sent:.*\n", "", out)
344 out = re.sub("Received: *", "", out)
346 self.info = json.loads(out)["system"]["get_sysinfo"]
347 logger.debug(json.dumps(self.info, indent=4, sort_keys=True))
348 self.info_ts = datetime.datetime.now()
350 except Exception as e:
352 print(out, file=sys.stderr)
358 def status(self) -> str:
360 for k, v in self.get_info().items():
361 ret += f'{k} = {v}\n'
364 def get_on_duration_seconds(self, child: str = None) -> int:
365 self.info = self.get_info()
367 if self.info is None:
369 return int(self.info.get("on_time", "0"))
371 if self.info is None:
373 for chi in self.info.get("children", {}):
374 if chi["id"] == child:
375 return int(chi.get("on_time", "0"))
379 def get_dimmer_level(self) -> Optional[int]:
380 if not self.has_keyword("dimmer"):
382 self.info = self.get_info()
383 if self.info is None:
385 return int(self.info.get("brightness", "0"))
388 def set_dimmer_level(self, level: int) -> bool:
389 if not self.has_keyword("dimmer"):
393 + f'-j \'{{"smartlife.iot.dimmer":{{"set_brightness":{{"brightness":{level} }} }} }}\''
395 return tplink_light_command(cmd)
398 # class GoogleLightGroup(GoogleLight):
399 # def __init__(self, name: str, members: List[GoogleLight], keywords: str = "") -> None:
400 # if len(members) < 1:
401 # raise Exception("There must be at least one light in the group.")
402 # self.members = members
403 # mac = GoogleLightGroup.make_up_mac(members)
404 # super().__init__(name, mac, keywords)
407 # def make_up_mac(members: List[GoogleLight]):
408 # mac = members[0].get_mac()
410 # b[5] = int(b[5], 16) + 1
416 # def is_on(self) -> bool:
417 # r = ask_google(f"are {self.goog_name()} on?")
420 # return 'is on' in r.audio_transcription
422 # def get_dimmer_level(self) -> Optional[int]:
423 # if not self.has_keyword("dimmer"):
425 # r = ask_google(f'how bright are {self.goog_name()}?')
429 # # four lights are set to 100% brightness
430 # txt = r.audio_transcription
431 # m = re.search(r"(\d+)% bright", txt)
433 # return int(m.group(1))
434 # if "is off" in txt:
438 # def set_dimmer_level(self, level: int) -> bool:
439 # if not self.has_keyword("dimmer"):
441 # if 0 <= level <= 100:
442 # was_on = self.is_on()
443 # r = ask_google(f"set {self.goog_name()} to {level} percent")
451 # def make_color(self, color: str) -> bool:
452 # return GoogleLight.parse_google_response(
453 # ask_google(f"make {self.goog_name()} {color}")