Last active
April 23, 2020 17:33
-
-
Save Crocmagnon/4df32b0e209a39edf53556497f598e23 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import hassapi as hass | |
| class TimedLight(hass.Hass): | |
| def initialize(self): | |
| self.timer_duration = self.args["timer_duration"] | |
| self.light_id = self.args["light_id"] | |
| self.before = self.get_time_boundary("before") | |
| self.after = self.get_time_boundary("after") | |
| self.timer = None | |
| controller_ids = self.args["controller_ids"] | |
| for controller_id in controller_ids: | |
| self.log("Listening for %s", controller_id) | |
| self.listen_event(self.callback, "zha_event", command="on_with_timed_off", device_ieee=controller_id) | |
| def get_time_boundary(self, name): | |
| boundary = self.args.get(name) | |
| if boundary in ["sunset", "sunrise"]: | |
| offset = self.args.get(f"{name}_offset") | |
| if offset: | |
| boundary = " ".join([boundary, offset]) | |
| self.log("Will turn on %s %s", name, self.parse_time(boundary)) | |
| return boundary | |
| def callback(self, event_name, data, kwargs): | |
| args = data["args"] | |
| if not isinstance(args, list) or len(args) != 3: | |
| self.log("args must be a list of 3 elements: %s", args, level="ERROR") | |
| return | |
| if not self.now_is_between(self.after, self.before): | |
| self.log("Not in time interval, not turning on.") | |
| return | |
| if self.timer: | |
| self.log("Canceling timer.") | |
| self.cancel_timer(self.timer) | |
| self.timer = self.run_in(self.turn_off_callback, self.timer_duration) | |
| if args[0] != 0: | |
| self.log("Enough light, not turning on.") | |
| return | |
| self.log("Turning light on.") | |
| self.turn_on(self.light_id) | |
| def turn_off_callback(self, kwargs): | |
| self.log("Turning light off.") | |
| self.turn_off(self.light_id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment