3 """Utilities for dealing with the smart lights."""
5 from abc import ABC, abstractmethod
13 from typing import Any, Dict, List, Optional, Set
21 from google_assistant import ask_google, GoogleResponse
22 from decorator_utils import timeout, memoized
24 logger = logging.getLogger(__name__)
26 parser = config.add_commandline_args(
27 f"Light Utils ({__file__})",
28 "Args related to light utilities."
31 '--light_utils_tplink_location',
32 default='/home/scott/bin/tplink.py',
34 help='The location of the tplink.py helper',
35 type=argparse_utils.valid_filename,
38 '--light_utils_network_mac_addresses_location',
39 default='/home/scott/bin/network_mac_addresses.txt',
41 help='The location of network_mac_addresses.txt',
42 type=argparse_utils.valid_filename,
47 5.0, use_signals=False, error_message="Timed out waiting for tplink.py"
49 def tplink_light_command(command: str) -> bool:
50 result = os.system(command)
51 signal = result & 0xFF
53 logger.warning(f'{command} died with signal {signal}')
54 logging_utils.hlog("%s died with signal %d" % (command, signal))
57 exit_value = result >> 8
59 logger.warning(f'{command} failed, exited {exit_value}')
60 logging_utils.hlog("%s failed, exit %d" % (command, exit_value))
62 logger.debug(f'{command} succeeded.')
67 def __init__(self, name: str, mac: str, keywords: str = "") -> None:
68 self.name = name.strip()
69 self.mac = mac.strip()
70 self.keywords = keywords.strip()
71 self.kws = keywords.split()
73 def get_name(self) -> str:
76 def get_mac(self) -> str:
80 def turn_on(self) -> bool:
84 def turn_off(self) -> bool:
88 def is_on(self) -> bool:
92 def is_off(self) -> bool:
96 def get_dimmer_level(self) -> Optional[int]:
100 def set_dimmer_level(self, level: int) -> bool:
104 def make_color(self, color: str) -> bool:
107 def get_keywords(self) -> List[str]:
110 def has_keyword(self, keyword: str) -> bool:
117 class GoogleLight(Light):
118 def __init__(self, name: str, mac: str, keywords: str = "") -> None:
119 super().__init__(name, mac, keywords)
121 def goog_name(self) -> str:
122 name = self.get_name()
123 return name.replace("_", " ")
126 def parse_google_response(response: GoogleResponse) -> bool:
127 return response.success
129 def turn_on(self) -> bool:
130 return GoogleLight.parse_google_response(
131 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")
139 def is_on(self) -> bool:
140 r = ask_google(f"is {self.goog_name()} on?")
143 return 'is on' in r.audio_transcription
145 def is_off(self) -> bool:
146 return not self.is_on()
148 def get_dimmer_level(self) -> Optional[int]:
149 if not self.has_keyword("dimmer"):
151 r = ask_google(f'how bright is {self.goog_name()}?')
155 # the bookcase one is set to 40% bright
156 txt = r.audio_transcription
157 m = re.search(r"(\d+)% bright", txt)
159 return int(m.group(1))
164 def set_dimmer_level(self, level: int) -> bool:
165 if not self.has_keyword("dimmer"):
167 if 0 <= level <= 100:
168 was_on = self.is_on()
169 r = ask_google(f"set {self.goog_name()} to {level} percent")
177 def make_color(self, color: str) -> bool:
178 return GoogleLight.parse_google_response(
179 ask_google(f"make {self.goog_name()} {color}")
183 class TuyaLight(Light):
185 '68:C6:3A:DE:1A:94': '8844664268c63ade1a94',
186 '68:C6:3A:DE:27:1A': '8844664268c63ade271a',
187 '68:C6:3A:DE:1D:95': '8844664268c63ade1d95',
188 '68:C6:3A:DE:19:B3': '8844664268c63ade19b3',
189 '80:7D:3A:77:3B:F5': '07445340807d3a773bf5',
190 '80:7D:3A:58:37:02': '07445340807d3a583702',
193 '68:C6:3A:DE:1A:94': '237f19b1b3d49c36',
194 '68:C6:3A:DE:27:1A': '237f19b1b3d49c36',
195 '68:C6:3A:DE:1D:95': '04b90fc5cd7625d8',
196 '68:C6:3A:DE:19:B3': '2d601f2892f1aefd',
197 '80:7D:3A:77:3B:F5': '27ab921fe4633519',
198 '80:7D:3A:58:37:02': '8559b5416bfa0c05',
201 def __init__(self, name: str, mac: str, keywords: str = "") -> None:
202 from subprocess import Popen, PIPE
203 super().__init__(name, mac, keywords)
205 if mac not in TuyaLight.ids_by_mac or mac not in TuyaLight.keys_by_mac:
206 raise Exception(f'{mac} is unknown; add it to ids_by_mac and keys_by_mac')
207 self.devid = TuyaLight.ids_by_mac[mac]
208 self.key = TuyaLight.keys_by_mac[mac]
210 pid = Popen(['maclookup', mac], stdout=PIPE)
211 ip = pid.communicate()[0]
215 self.bulb = tt.BulbDevice(self.devid, ip, local_key=self.key)
217 def turn_on(self) -> bool:
221 def turn_off(self) -> bool:
225 def get_status(self) -> Dict[str, Any]:
226 return self.bulb.status()
228 def is_on(self) -> bool:
229 s = self.get_status()
232 def is_off(self) -> bool:
233 return not self.is_on()
235 def get_dimmer_level(self) -> Optional[int]:
236 s = self.get_status()
239 def set_dimmer_level(self, level: int) -> bool:
240 self.bulb.set_brightness(level)
243 def make_color(self, color: str) -> bool:
244 self.bulb.set_colour(255,0,0)
248 class TPLinkLight(Light):
249 def __init__(self, name: str, mac: str, keywords: str = "") -> None:
250 super().__init__(name, mac, keywords)
251 self.children: List[str] = []
252 self.info: Optional[Dict] = None
253 self.info_ts: Optional[datetime.datetime] = None
254 if "children" in self.keywords:
255 self.info = self.get_info()
256 if self.info is not None:
257 for child in self.info["children"]:
258 self.children.append(child["id"])
261 def get_tplink_name(self) -> Optional[str]:
262 self.info = self.get_info()
263 if self.info is not None:
264 return self.info["alias"]
267 def get_cmdline(self, child: str = None) -> str:
269 f"{config.config['light_utils_tplink_location']} -m {self.mac} "
270 f"--no_logging_console "
272 if child is not None:
273 cmd += f"-x {child} "
276 def get_children(self) -> List[str]:
280 self, cmd: str, child: str = None, extra_args: str = None
282 cmd = self.get_cmdline(child) + f"-c {cmd}"
283 if extra_args is not None:
284 cmd += f" {extra_args}"
285 logger.debug(f'About to execute {cmd}')
286 return tplink_light_command(cmd)
288 def turn_on(self, child: str = None) -> bool:
289 return self.command("on", child)
291 def turn_off(self, child: str = None) -> bool:
292 return self.command("off", child)
294 def is_on(self) -> bool:
295 return self.get_on_duration_seconds() > 0
297 def is_off(self) -> bool:
298 return not self.is_on()
300 def make_color(self, color: str) -> bool:
301 raise NotImplementedError
304 10.0, use_signals=False, error_message="Timed out waiting for tplink.py"
306 def get_info(self) -> Optional[Dict]:
307 cmd = self.get_cmdline() + "-c info"
308 out = subprocess.getoutput(cmd)
309 out = re.sub("Sent:.*\n", "", out)
310 out = re.sub("Received: *", "", out)
312 self.info = json.loads(out)["system"]["get_sysinfo"]
313 self.info_ts = datetime.datetime.now()
315 except Exception as e:
317 print(out, file=sys.stderr)
322 def get_on_duration_seconds(self, child: str = None) -> int:
323 self.info = self.get_info()
325 if self.info is None:
327 return int(self.info.get("on_time", "0"))
329 if self.info is None:
331 for chi in self.info.get("children", {}):
332 if chi["id"] == child:
333 return int(chi.get("on_time", "0"))
336 def get_on_limit_seconds(self) -> Optional[int]:
338 m = re.search(r"timeout:(\d+)", kw)
340 return int(m.group(1)) * 60
343 def get_dimmer_level(self) -> Optional[int]:
344 if not self.has_keyword("dimmer"):
346 self.info = self.get_info()
347 if self.info is None:
349 return int(self.info.get("brightness", "0"))
351 def set_dimmer_level(self, level: int) -> bool:
352 if not self.has_keyword("dimmer"):
356 + f'-j \'{{"smartlife.iot.dimmer":{{"set_brightness":{{"brightness":{level} }} }} }}\''
358 return tplink_light_command(cmd)
361 class GoogleLightGroup(GoogleLight):
362 def __init__(self, name: str, members: List[GoogleLight], keywords: str = "") -> None:
364 raise Exception("There must be at least one light in the group.")
365 self.members = members
366 mac = GoogleLightGroup.make_up_mac(members)
367 super().__init__(name, mac, keywords)
370 def make_up_mac(members: List[GoogleLight]):
371 mac = members[0].get_mac()
373 b[5] = int(b[5], 16) + 1
379 def is_on(self) -> bool:
380 r = ask_google(f"are {self.goog_name()} on?")
383 return 'is on' in r.audio_transcription
385 def get_dimmer_level(self) -> Optional[int]:
386 if not self.has_keyword("dimmer"):
388 r = ask_google(f'how bright are {self.goog_name()}?')
392 # four lights are set to 100% brightness
393 txt = r.audio_transcription
394 m = re.search(r"(\d+)% bright", txt)
396 return int(m.group(1))
401 def set_dimmer_level(self, level: int) -> bool:
402 if not self.has_keyword("dimmer"):
404 if 0 <= level <= 100:
405 was_on = self.is_on()
406 r = ask_google(f"set {self.goog_name()} to {level} percent")
414 def make_color(self, color: str) -> bool:
415 return GoogleLight.parse_google_response(
416 ask_google(f"make {self.goog_name()} {color}")
420 class LightingConfig(object):
421 """Representation of the smart light device config."""
425 config_file: str = None,
427 if config_file is None:
428 config_file = config.config[
429 'light_utils_network_mac_addresses_location'
431 self.macs_by_name = {}
432 self._keywords_by_name = {}
433 self.keywords_by_mac = {}
434 self.names_by_mac = {}
435 self.corpus = logical_search.Corpus()
436 with open(config_file, "r") as f:
437 contents = f.readlines()
439 diningroom_lights = []
441 for line in contents:
442 line = line.rstrip("\n")
443 line = re.sub(r"#.*$", r"", line)
447 (mac, name, keywords) = line.split(",")
450 keywords = keywords.strip()
451 if "perm" not in keywords:
453 self.macs_by_name[name] = mac
454 self._keywords_by_name[name] = keywords
455 self.keywords_by_mac[mac] = keywords
456 self.names_by_mac[mac] = name
458 # if "bookcase_light_" in name:
459 # bookcase_lights.append(mac)
460 # elif "diningroom_light_" in name:
461 # diningroom_lights.append(mac)
463 self.index_light(name, keywords, mac)
465 # name = 'bookcase_lights'
467 # keywords = 'perm wifi light smart goog dimmer'
468 # for b in bookcase_lights:
469 # group.append(self.get_light_by_mac(b))
470 # self.bookcase_group = GoogleLightGroup(
475 # mac = self.bookcase_group.get_mac()
476 # self.macs_by_name[name] = mac
477 # self._keywords_by_name[name] = keywords
478 # self.keywords_by_mac[mac] = keywords
479 # self.names_by_mac[mac] = name
480 # self.index_light(name, keywords, mac)
482 # name = 'dining_room_lights'
484 # for b in diningroom_lights:
485 # group.append(self.get_light_by_mac(b))
486 # self.diningroom_group = GoogleLightGroup(
491 # mac = self.diningroom_group.get_mac()
492 # self.macs_by_name[name] = mac
493 # self._keywords_by_name[name] = keywords
494 # self.keywords_by_mac[mac] = keywords
495 # self.names_by_mac[mac] = name
496 # self.index_light(name, keywords, mac)
498 def index_light(self, name: str, keywords: str, mac: str) -> None:
499 properties = [("name", name)]
501 for kw in keywords.split():
503 key, value = kw.split(":")
504 properties.append((key, value))
507 light = logical_search.Document(
510 properties=properties,
513 self.corpus.add_doc(light)
515 def __repr__(self) -> str:
516 s = "Known devices:\n"
517 for name, keywords in self._keywords_by_name.items():
518 mac = self.macs_by_name[name]
519 s += f" {name} ({mac}) => {keywords}\n"
522 def get_keywords_by_name(self, name: str) -> Optional[str]:
523 return self._keywords_by_name.get(name, None)
525 def get_macs_by_name(self, name: str) -> Set[str]:
527 for (mac, lname) in self.names_by_mac.items():
532 def get_macs_by_keyword(self, keyword: str) -> Set[str]:
534 for (mac, keywords) in self.keywords_by_mac.items():
535 if keyword in keywords:
539 def get_light_by_name(self, name: str) -> Optional[Light]:
540 if name in self.macs_by_name:
541 return self.get_light_by_mac(self.macs_by_name[name])
544 def get_all_lights(self) -> List[Light]:
546 for (mac, kws) in self.keywords_by_mac.items():
548 light = self.get_light_by_mac(mac)
549 if light is not None:
553 def get_light_by_mac(self, mac: str) -> Optional[Light]:
554 if mac in self.keywords_by_mac:
555 name = self.names_by_mac[mac]
556 kws = self.keywords_by_mac[mac]
557 if name == 'bookcase_lights':
558 return self.bookcase_group
559 elif name == 'dining_room_lights':
560 return self.diningroom_group
561 elif 'tplink' in kws.lower():
562 return TPLinkLight(name, mac, kws)
563 elif 'tuya' in kws.lower():
564 return TuyaLight(name, mac, kws)
566 return GoogleLight(name, mac, kws)
569 def query(self, query: str) -> List[Light]:
570 """Evaluates a lighting query expression formed of keywords to search
571 for, logical operators (and, or, not), and parenthesis.
572 Returns a list of matching lights.
575 results = self.corpus.query(query)
576 if results is not None:
579 light = self.get_light_by_mac(mac)
580 if light is not None: