3 """Utilities for dealing with the smart lights."""
5 from abc import ABC, abstractmethod
13 from typing import Dict, List, Optional, Set
19 from google_assistant import ask_google, GoogleResponse
20 from decorator_utils import timeout, memoized
22 logger = logging.getLogger(__name__)
24 parser = config.add_commandline_args(
25 f"Light Utils ({__file__})",
26 "Args related to light utilities."
29 '--light_utils_tplink_location',
30 default='/home/scott/bin/tplink.py',
32 help='The location of the tplink.py helper',
33 type=argparse_utils.valid_filename,
36 '--light_utils_network_mac_addresses_location',
37 default='/home/scott/bin/network_mac_addresses.txt',
39 help='The location of network_mac_addresses.txt',
40 type=argparse_utils.valid_filename,
45 5.0, use_signals=False, error_message="Timed out waiting for tplink.py"
47 def tplink_light_command(command: str) -> bool:
48 result = os.system(command)
49 signal = result & 0xFF
51 logger.warning(f'{command} died with signal {signal}')
52 logging_utils.hlog("%s died with signal %d" % (command, signal))
55 exit_value = result >> 8
57 logger.warning(f'{command} failed, exited {exit_value}')
58 logging_utils.hlog("%s failed, exit %d" % (command, exit_value))
60 logger.debug(f'{command} succeeded.')
65 def __init__(self, name: str, mac: str, keywords: str = "") -> None:
66 self.name = name.strip()
67 self.mac = mac.strip()
68 self.keywords = keywords.strip()
69 self.kws = keywords.split()
71 def get_name(self) -> str:
74 def get_mac(self) -> str:
78 def turn_on(self) -> bool:
82 def turn_off(self) -> bool:
86 def is_on(self) -> bool:
90 def is_off(self) -> bool:
94 def get_dimmer_level(self) -> Optional[int]:
98 def set_dimmer_level(self, level: int) -> bool:
102 def make_color(self, color: str) -> bool:
105 def get_keywords(self) -> List[str]:
108 def has_keyword(self, keyword: str) -> bool:
115 class GoogleLight(Light):
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
127 def turn_on(self) -> bool:
128 return GoogleLight.parse_google_response(
129 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")
137 def is_on(self) -> bool:
138 r = ask_google(f"is {self.goog_name()} on?")
141 return 'is on' in r.audio_transcription
143 def is_off(self) -> bool:
144 return not self.is_on()
146 def get_dimmer_level(self) -> Optional[int]:
147 if not self.has_keyword("dimmer"):
149 r = ask_google(f'how bright is {self.goog_name()}?')
153 # the bookcase one is set to 40% bright
154 txt = r.audio_transcription
155 m = re.search(r"(\d+)% bright", txt)
157 return int(m.group(1))
162 def set_dimmer_level(self, level: int) -> bool:
163 if not self.has_keyword("dimmer"):
165 if 0 <= level <= 100:
166 was_on = self.is_on()
167 r = ask_google(f"set {self.goog_name()} to {level} percent")
175 def make_color(self, color: str) -> bool:
176 return GoogleLight.parse_google_response(
177 ask_google(f"make {self.goog_name()} {color}")
181 class TPLinkLight(Light):
182 def __init__(self, name: str, mac: str, keywords: str = "") -> None:
183 super().__init__(name, mac, keywords)
184 self.children: List[str] = []
185 self.info: Optional[Dict] = None
186 self.info_ts: Optional[datetime.datetime] = None
187 if "children" in self.keywords:
188 self.info = self.get_info()
189 if self.info is not None:
190 for child in self.info["children"]:
191 self.children.append(child["id"])
194 def get_tplink_name(self) -> Optional[str]:
195 self.info = self.get_info()
196 if self.info is not None:
197 return self.info["alias"]
200 def get_cmdline(self, child: str = None) -> str:
202 f"{config.config['light_utils_tplink_location']} -m {self.mac} "
203 f"--no_logging_console "
205 if child is not None:
206 cmd += f"-x {child} "
209 def get_children(self) -> List[str]:
213 self, cmd: str, child: str = None, extra_args: str = None
215 cmd = self.get_cmdline(child) + f"-c {cmd}"
216 if extra_args is not None:
217 cmd += f" {extra_args}"
218 logger.debug(f'About to execute {cmd}')
219 return tplink_light_command(cmd)
221 def turn_on(self, child: str = None) -> bool:
222 return self.command("on", child)
224 def turn_off(self, child: str = None) -> bool:
225 return self.command("off", child)
227 def is_on(self) -> bool:
228 return self.get_on_duration_seconds() > 0
230 def is_off(self) -> bool:
231 return not self.is_on()
233 def make_color(self, color: str) -> bool:
234 raise NotImplementedError
237 10.0, use_signals=False, error_message="Timed out waiting for tplink.py"
239 def get_info(self) -> Optional[Dict]:
240 cmd = self.get_cmdline() + "-c info"
241 out = subprocess.getoutput(cmd)
242 out = re.sub("Sent:.*\n", "", out)
243 out = re.sub("Received: *", "", out)
245 self.info = json.loads(out)["system"]["get_sysinfo"]
246 self.info_ts = datetime.datetime.now()
248 except Exception as e:
250 print(out, file=sys.stderr)
255 def get_on_duration_seconds(self, child: str = None) -> int:
256 self.info = self.get_info()
258 if self.info is None:
260 return int(self.info.get("on_time", "0"))
262 if self.info is None:
264 for chi in self.info.get("children", {}):
265 if chi["id"] == child:
266 return int(chi.get("on_time", "0"))
269 def get_on_limit_seconds(self) -> Optional[int]:
271 m = re.search(r"timeout:(\d+)", kw)
273 return int(m.group(1)) * 60
276 def get_dimmer_level(self) -> Optional[int]:
277 if not self.has_keyword("dimmer"):
279 self.info = self.get_info()
280 if self.info is None:
282 return int(self.info.get("brightness", "0"))
284 def set_dimmer_level(self, level: int) -> bool:
285 if not self.has_keyword("dimmer"):
289 + f'-j \'{{"smartlife.iot.dimmer":{{"set_brightness":{{"brightness":{level} }} }} }}\''
291 return tplink_light_command(cmd)
294 class GoogleLightGroup(GoogleLight):
295 def __init__(self, name: str, members: List[GoogleLight], keywords: str = "") -> None:
297 raise Exception("There must be at least one light in the group.")
298 self.members = members
299 mac = GoogleLightGroup.make_up_mac(members)
300 super().__init__(name, mac, keywords)
303 def make_up_mac(members: List[GoogleLight]):
304 mac = members[0].get_mac()
306 b[5] = int(b[5], 16) + 1
312 def is_on(self) -> bool:
313 r = ask_google(f"are {self.goog_name()} on?")
316 return 'is on' in r.audio_transcription
318 def get_dimmer_level(self) -> Optional[int]:
319 if not self.has_keyword("dimmer"):
321 r = ask_google(f'how bright are {self.goog_name()}?')
325 # four lights are set to 100% brightness
326 txt = r.audio_transcription
327 m = re.search(r"(\d+)% bright", txt)
329 return int(m.group(1))
334 def set_dimmer_level(self, level: int) -> bool:
335 if not self.has_keyword("dimmer"):
337 if 0 <= level <= 100:
338 was_on = self.is_on()
339 r = ask_google(f"set {self.goog_name()} to {level} percent")
347 def make_color(self, color: str) -> bool:
348 return GoogleLight.parse_google_response(
349 ask_google(f"make {self.goog_name()} {color}")
353 def group_google_lights(lights: List[Light]) -> List[Light]:
355 diningroom_group = []
357 name = light.get_name()
358 if "bookcase_light_" in name:
359 bookcase_group.append(light)
360 elif "diningroom_light_" in name:
361 diningroom_group.append(light)
364 did_diningroom = False
367 name = light.get_name()
368 if "bookcase_light_" in name:
369 if len(bookcase_group) == 4 and not did_bookcase:
374 "perm wifi light smart goog dimmer"
378 elif "diningroom_light_" in name:
379 if len(diningroom_group) == 2 and not did_diningroom:
382 "dining_room_lights",
384 "intermittent wifi light smart goog dimmer"
387 did_diningroom = True
393 class LightingConfig(object):
394 """Representation of the smart light device config."""
398 config_file: str = None,
400 if config_file is None:
401 config_file = config.config[
402 'light_utils_network_mac_addresses_location'
404 self.macs_by_name = {}
405 self._keywords_by_name = {}
406 self.keywords_by_mac = {}
407 self.names_by_mac = {}
408 self.corpus = logical_search.Corpus()
409 with open(config_file, "r") as f:
410 contents = f.readlines()
412 diningroom_lights = []
414 for line in contents:
415 line = line.rstrip("\n")
416 line = re.sub(r"#.*$", r"", line)
420 (mac, name, keywords) = line.split(",")
423 keywords = keywords.strip()
424 if "perm" not in keywords:
426 self.macs_by_name[name] = mac
427 self._keywords_by_name[name] = keywords
428 self.keywords_by_mac[mac] = keywords
429 self.names_by_mac[mac] = name
431 if "bookcase_light_" in name:
432 bookcase_lights.append(mac)
433 elif "diningroom_light_" in name:
434 diningroom_lights.append(mac)
436 self.index_light(name, keywords, mac)
438 name = 'bookcase_lights'
440 keywords = 'perm wifi light smart goog dimmer'
441 for b in bookcase_lights:
442 group.append(self.get_light_by_mac(b))
443 self.bookcase_group = GoogleLightGroup(
448 mac = self.bookcase_group.get_mac()
449 self.macs_by_name[name] = mac
450 self._keywords_by_name[name] = keywords
451 self.keywords_by_mac[mac] = keywords
452 self.names_by_mac[mac] = name
453 self.index_light(name, keywords, mac)
455 name = 'dining_room_lights'
457 for b in diningroom_lights:
458 group.append(self.get_light_by_mac(b))
459 self.diningroom_group = GoogleLightGroup(
464 mac = self.diningroom_group.get_mac()
465 self.macs_by_name[name] = mac
466 self._keywords_by_name[name] = keywords
467 self.keywords_by_mac[mac] = keywords
468 self.names_by_mac[mac] = name
469 self.index_light(name, keywords, mac)
471 def index_light(self, name: str, keywords: str, mac: str) -> None:
472 properties = [("name", name)]
474 for kw in keywords.split():
476 key, value = kw.split(":")
477 properties.append((key, value))
481 logical_search.Document(
484 properties=properties,
489 def __repr__(self) -> str:
490 s = "Known devices:\n"
491 for name, keywords in self._keywords_by_name.items():
492 mac = self.macs_by_name[name]
493 s += f" {name} ({mac}) => {keywords}\n"
496 def get_keywords_by_name(self, name: str) -> Optional[str]:
497 return self._keywords_by_name.get(name, None)
499 def get_macs_by_name(self, name: str) -> Set[str]:
501 for (mac, lname) in self.names_by_mac.items():
506 def get_macs_by_keyword(self, keyword: str) -> Set[str]:
508 for (mac, keywords) in self.keywords_by_mac.items():
509 if keyword in keywords:
513 def get_light_by_name(self, name: str) -> Optional[Light]:
514 if name in self.macs_by_name:
515 return self.get_light_by_mac(self.macs_by_name[name])
518 def get_all_lights(self) -> List[Light]:
520 for (mac, kws) in self.keywords_by_mac.items():
522 light = self.get_light_by_mac(mac)
523 if light is not None:
525 return group_google_lights(retval)
527 def get_light_by_mac(self, mac: str) -> Optional[Light]:
528 if mac in self.keywords_by_mac:
529 name = self.names_by_mac[mac]
530 kws = self.keywords_by_mac[mac]
531 if name == 'bookcase_lights':
532 return self.bookcase_group
533 elif name == 'dining_room_lights':
534 return self.diningroom_group
535 elif "tplink" in kws.lower():
536 return TPLinkLight(name, mac, kws)
538 return GoogleLight(name, mac, kws)
541 def query(self, query: str) -> List[Light]:
542 """Evaluates a lighting query expression formed of keywords to search
543 for, logical operators (and, or, not), and parenthesis.
544 Returns a list of matching lights.
547 results = self.corpus.query(query)
548 if results is not None:
551 light = self.get_light_by_mac(mac)
552 if light is not None:
554 return group_google_lights(retval)