def init_predictor(self): print("initializing occupancy predictor") occupancy_feature = FeatureColumn( "occupancy", get_resource(self.occupancy_resource), "occupancy") day_of_week_feature = FeatureColumn("day_of_week", DayOfWeekResource(), "day_of_week") hour_feature = FeatureColumn("hour_of_day", HourOfDayResource(), "hour_of_day") all_features = [occupancy_feature, day_of_week_feature, hour_feature] shape = features_shape(all_features) layers = [ keras.layers.LSTM(64, activation="relu", input_shape=(shape - 1, 1)), keras.layers.Dense(128, activation="relu"), keras.layers.Dense(1, activation="sigmoid") ] self.predictors = Learning(model_subdir=self.model_dir, features=all_features, prediction_feature="occupancy", persist=True, layers=layers, loss="binary_crossentropy") self.poller = resource_poll(self.poll_func, MINS(10)) self.poller = resource_poll( lambda: self.wait_can_run(interval=MINS(5)), HOURS(1))
def poll(self): while True: try: if self.predictor is None: yield from asyncio.sleep(MINS(5)) continue predicted_temperature = self.predictor.predict() print( "predicted temperature: {}".format(predicted_temperature)) print("actual temperature: {}".format( gr(self.temp1).get_value("temperature"))) self.set_value("temperature", predicted_temperature) predicted_solar = self.predict_solar() print("predicted solar power: {}".format(predicted_solar)) print("actual solar power: {}".format( gr(self.solar).get_value("current_power"))) self.set_value("solar_power", predicted_solar) except AttributeError as ae: print("{} - Error. don't have a predictor yet? {}".format( self.name, ae)) import sys import traceback exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=12, file=sys.stdout) traceback.print_exception(exc_type, exc_value, exc_traceback, limit=12, file=sys.stdout) pass except Exception as ex: import sys import traceback exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=6, file=sys.stdout) traceback.print_exception(exc_type, exc_value, exc_traceback, limit=6, file=sys.stdout) yield from asyncio.sleep(MINS(5))
def __init__(self, name="NightTime", lat=None, lon=None, timezone="US/Pacific"): Resource.__init__( self, name, ["nightTime", "night_time", "sunset", "sunrise"]) if lat is None or lon is None: try: config = get_resource("ConfigurationResource") lat = config.get_value("latitude") lon = config.get_value("longitude") except ResourceNotFoundException: raise Exception( "NightTime requires lat/lon set or ConfigurationResource") if lat is None or lon is None: raise Exception( "NightTime: missing latitude/longitude in ConfigurationResource") print("using lat/lon: {}, {}".format(lat, lon)) self.location = Location() self.location.latitude = float(lat) self.location.longitude = float(lon) self.location.timezone = timezone self.process() self.poller = resource_poll(self.process, MINS(1))
def poll(self): while True: if self.ecobee_service and self.ecobee_service.thermostat: value = self.ecobee_service.get_occupancy(self.sensor_name) # print("occupancy sensor {} is now: {}".format( # self.name, value)) self.set_value("occupancy", value) temp = self.ecobee_service.get_sensor_value(self.sensor_name, "temperature") if temp is not None: self.set_value("temperature", f_to_c(float(temp) / 10.0)) """prediction = self.prediction_resource.predict_occupancy() print("occupancy sensor {} predicted is now: {}".format( self.name, prediction)) if prediction is not None: self.setValue("predicted_occupancy", round(prediction, 2)) try: import data_logging as dl dl.log_some_data("{}/occupancy_prediction_{}.json".format( self.prediction_resource.model_dir, self.name), predicted=round(prediction, 2), actual=self.getValue("occupancy")) except Exception: pass """ yield from asyncio.sleep(MINS(3))
def __init__(self, name, hammock_instance, poll_rate=2): self.hammock_instance = hammock_instance variables = self.hammock_instance.GET(verify=False).json()["variables"] Resource.__init__(self, name, variables.keys()) self.poller = resource_poll(self.poll_func, MINS(poll_rate))
def do_stuff(plugs): while True: for plug in plugs: print("plug {} is running: {} {}W".format( plug.name, plug.running(), plug.power_usage)) yield from asyncio.sleep(MINS(1))
def _ping_loop(self): while True: yield from asyncio.sleep(MINS(3)) var = "{}/keep_alive".format(self.name) try: self.client.publish(var, "1") except AttributeError: yield from self.do_connect(self.broker)
def do_get_kasa_plug(self): self.device = None while not self.device: self.device = yield from get_kasa_plug(self.device_name) yield from asyncio.sleep(MINS(1)) self.has_emeter = self.device.has_emeter self.is_dimmable = self.device.is_dimmable
def __init__(self, occupancy_predictor_name=None, power_usage=1750): super().__init__("EcobeeResource", power_usage=power_usage, variables=["occupancy", "setpoint_heat", "setpoint_cool", "temperature", "humidity", "running_program"], priority=RuntimePriority.high) self.subscribe("temperature", lambda v: self.process()) self.subscribe("running_program", lambda v: self.process()) self.occupancy_prediction = False self.occupancy_predictor_name = occupancy_predictor_name self.occupancy_predictor = None config = Resource.resource("ConfigurationResource").config api_key = config["ecobee_apikey"] thermostat_name = config["ecobee_thermostat_name"] self.ecobee_user_preferences = None self.present_users = [] if "ecobee_user_preferences" in config: self.ecobee_user_preferences = config["ecobee_user_preferences"] self.ecobee_service = Ecobee(thermostat_name, api_key) self.poller = resource_poll(self.poll_func, MINS(3), is_coroutine=True) def wait_resources(): self.occupancy_predictor = Resource.resource( self.occupancy_predictor_name) self.occupancy_predictor.subscribe( "occupancy_prediction", self.occupancy_changed) Resource.resource("SolarPower").subscribe( "current_power", self.solar_power_changed) self.night_time_resource = Resource.resource("NightTime") Resource.waitResource( [self.occupancy_predictor_name, "SolarPower", "NightTime"], wait_resources) def wait_ble_resource(): Resource.resource("BleUserResource").subscribe( "present_users", self.ble_present_users_changed) Resource.waitResource("BleUserResource", wait_ble_resource) self.ecobee_can_run_hold = False self.setpoint_cool = None self.setpoint_heat = None
def poll(self): while True: try: t = get_current_datetime(utc=True) self.set_value("current_power", get_solar_radiation(self.lat, self.lon, t)) except Exception as ex: print("error getting solar insolation: {}".format(ex)) yield from asyncio.sleep(MINS(3))
def __init__(self): Resource.__init__(self, "TimeOfUse", ["mode", "schedule"]) try: config = Resource.resource("ConfigurationResource").config self.winter_schedule = config["time_of_use_schedule"]["winter"] self.summer_schedule = config["time_of_use_schedule"]["summer"] self.poller = resource_poll(self.update_schedule, MINS(1)) except ResourceNotFoundException: print("TimeOfUse: No configuration resource!")
def __init__(self): Resource.__init__(self, "weather", [ "temperature", "humidity", "forecast_high", "forecast_low", "forecast_conditions", "condition", "current_observation", "cloud_cover", "forecast_cloud_cover" ]) self.key = get_resource("ConfigurationResource").config["weather_key"] self.lat = get_resource("ConfigurationResource").config["latitude"] self.lon = get_resource("ConfigurationResource").config["longitude"] self.poller = resource_poll(self.poll_func, MINS(15), is_coroutine=True)
def __init__(self, device_name, username, passwd, brand="liftmaster"): super().__init__(name=device_name, variables=["state"]) self.device = None self.username = username self.passwd = passwd self.brand = brand self.trying_to_run = False self.poll_rate = MINS(1) asyncio.get_event_loop().create_task(self.async_connect())
def do_stuff(plugs): while True: print("number of plugs: {}".format(len(plugs))) for plug in plugs: print("plug {} is running: {}".format( plug.name, plug.running())) print("power: {}".format(plug.power_usage)) try: print(plug.device.plugs) except Exception: pass yield from asyncio.sleep(MINS(1))
def __init__(self, name="DeviceManager", max_power_budget=0, power_source=None, debug=False): """ max_power_budget is to be used to define the max power budget when there is no solar system (ie battery system, or pure-grid system). power_source must have the "available_power" property unless max power_budget is set. available_power is max_power_budget until power_source updates. """ super().__init__(name, ["total_power", "running_devices", "capacity", "total_capacity"]) if power_source is None: power_source = ["SolarPower"] if isinstance(power_source, str): power_source = [power_source] power_sources = power_source self.running_devices = [] self.managed_devices = [] self.ignored_devices = [] self.max_power_budget = max_power_budget self.time_of_use_mode = None self.debug = debug self.power_sources = None if not max_power_budget: self.power_sources = ResourceRequires( power_sources, lambda rsrcs: True) def wait_time_of_use(): gr("TimeOfUse").subscribe("mode", self.time_of_use_changed) try: wait_time_of_use() except ResourceNotFoundException: Resource.waitResource("TimeOfUse", wait_time_of_use) self.poller = resource_poll(self.process_managed_devices, MINS(1))
def process(self): while True: try: yield from self.update() except SmartDeviceException as ex: print("KasaPlug error ({}). trying to reconnect".format( self.name)) print(ex) yield from self.do_get_kasa_plug() except Exception: print("error in kasa_resource process()") import sys import traceback exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=12, file=sys.stdout) traceback.print_exception(exc_type, exc_value, exc_traceback, limit=12, file=sys.stdout) yield from asyncio.sleep(MINS(1))
def can_run_check_timeout(self): self.checked = True yield from asyncio.sleep(MINS(15)) self.checked = False
def _do_lock_unlock(self, val): self.set_lock(val) while self.locked is None or self.locked != val: yield from asyncio.sleep(MINS(1)) print("trying to set lock ({}) to {}".format(self.name, val)) self.set_lock(val)
def poll(self): while True: yield from self.update() yield from asyncio.sleep(MINS(3))
def __init__(self): super().__init__("DayOfWeekResource", ["day_of_week"]) self.poller = resource_poll(self.poll_func, MINS(10)) self.poll_func()
def __init__(self, update_rate=MINS(1)): super().__init__("HourOfDayResource", ["hour_of_day"]) self.poller = resource_poll(self.poll_func, update_rate) self.override_value = False self.poll_func()