def get_sunrise_sunset(self, date=None):
     if self.data['sunrise_time'] is not None and self.data[
             'sunset_time'] is not None:
         if date is None:
             date = dt_now(self.data['timezone'])
         sunrise = date.replace(
             hour=int(self.data['sunrise_time'].strftime("%H")),
             minute=int(self.data['sunrise_time'].strftime("%M")),
             second=int(self.data['sunrise_time'].strftime("%S")),
             microsecond=int(self.data['sunrise_time'].strftime("%f")))
         sunset = date.replace(
             hour=int(self.data['sunset_time'].strftime("%H")),
             minute=int(self.data['sunset_time'].strftime("%M")),
             second=int(self.data['sunset_time'].strftime("%S")),
             microsecond=int(self.data['sunset_time'].strftime("%f")))
         solar_noon = sunrise + (sunset - sunrise) / 2
         solar_midnight = sunset + (
             (sunrise + timedelta(days=1)) - sunset) / 2
     else:
         import astral
         location = astral.Location()
         location.name = 'name'
         location.region = 'region'
         location.latitude = self.data['latitude']
         location.longitude = self.data['longitude']
         location.elevation = self.data['elevation']
         _LOGGER.debug("Astral location: " + str(location))
         if self.data['sunrise_time'] is not None:
             if date is None:
                 date = dt_now(self.data['timezone'])
             sunrise = date.replace(
                 hour=int(self.data['sunrise_time'].strftime("%H")),
                 minute=int(self.data['sunrise_time'].strftime("%M")),
                 second=int(self.data['sunrise_time'].strftime("%S")),
                 microsecond=int(self.data['sunrise_time'].strftime("%f")))
         else:
             sunrise = location.sunrise(date)
         if self.data['sunset_time'] is not None:
             if date is None:
                 date = dt_now(self.data['timezone'])
             sunset = date.replace(
                 hour=int(self.data['sunset_time'].strftime("%H")),
                 minute=int(self.data['sunset_time'].strftime("%M")),
                 second=int(self.data['sunset_time'].strftime("%S")),
                 microsecond=int(self.data['sunset_time'].strftime("%f")))
         else:
             sunset = location.sunset(date)
         solar_noon = location.solar_noon(date)
         solar_midnight = location.solar_midnight(date)
     if self.data['sunrise_offset'] is not None:
         sunrise = sunrise + self.data['sunrise_offset']
     if self.data['sunset_offset'] is not None:
         sunset = sunset + self.data['sunset_offset']
     return {
         SUN_EVENT_SUNRISE: sunrise.astimezone(self.data['timezone']),
         SUN_EVENT_SUNSET: sunset.astimezone(self.data['timezone']),
         'solar_noon': solar_noon.astimezone(self.data['timezone']),
         'solar_midnight': solar_midnight.astimezone(self.data['timezone'])
     }
Exemplo n.º 2
0
 def get_sunrise_sunset(self, date=None):
     if self.data['sunrise_time'] is not None and self.data[
             'sunset_time'] is not None:
         if date is None:
             date = dt_now()
         sunrise = date.replace(
             hour=int(self.data['sunrise_time'].strftime("%H")),
             minute=int(self.data['sunrise_time'].strftime("%M")),
             second=int(self.data['sunrise_time'].strftime("%S")),
             microsecond=int(self.data['sunrise_time'].strftime("%f")))
         sunset = date.replace(
             hour=int(self.data['sunset_time'].strftime("%H")),
             minute=int(self.data['sunset_time'].strftime("%M")),
             second=int(self.data['sunset_time'].strftime("%S")),
             microsecond=int(self.data['sunset_time'].strftime("%f")))
         solar_noon = sunrise + (sunset - sunrise) / 2
         solar_midnight = sunset + (
             (sunrise + timedelta(days=1)) - sunset) / 2
     else:
         location = astral.Location()
         location.latitude = self.data['latitude']
         location.longitude = self.data['longitude']
         if self.data['sunrise_time'] is not None:
             if date is None:
                 date = dt_now()
             sunrise = date.replace(
                 hour=int(self.data['sunrise_time'].strftime("%H")),
                 minute=int(self.data['sunrise_time'].strftime("%M")),
                 second=int(self.data['sunrise_time'].strftime("%S")),
                 microsecond=int(self.data['sunrise_time'].strftime("%f")))
         else:
             sunrise = location.sunrise(date)
         if self.data['sunset_time'] is not None:
             if date is None:
                 date = dt_now()
             sunset = date.replace(
                 hour=int(self.data['sunset_time'].strftime("%H")),
                 minute=int(self.data['sunset_time'].strftime("%M")),
                 second=int(self.data['sunset_time'].strftime("%S")),
                 microsecond=int(self.data['sunset_time'].strftime("%f")))
         else:
             sunset = location.sunset(date)
         solar_noon = location.solar_noon(date)
         solar_midnight = location.solar_midnight(date)
     if self.data['sunrise_offset'] is not None:
         sunrise = sunrise + self.data['sunrise_offset']
     if self.data['sunset_offset'] is not None:
         sunset = sunset + self.data['sunset_offset']
     return {
         'sunrise': sunrise,
         'sunset': sunset,
         'solar_noon': solar_noon,
         'solar_midnight': solar_midnight
     }
Exemplo n.º 3
0
    def flux_update(self, now=None):
        """Update all the lights using flux."""
        if now is None:
            now = dt_now()
        sunset = next_setting(self.hass, SUN).replace(day=now.day,
                                                      month=now.month,
                                                      year=now.year)
        start_time = self.find_start_time(now)
        stop_time = now.replace(hour=self._stop_time.hour,
                                minute=self._stop_time.minute,
                                second=0)

        if start_time < now < sunset:
            # Daytime
            time_state = 'day'
            temp_range = abs(self._start_colortemp - self._sunset_colortemp)
            day_length = int(sunset.timestamp() - start_time.timestamp())
            seconds_from_start = int(now.timestamp() - start_time.timestamp())
            percentage_complete = seconds_from_start / day_length
            temp_offset = temp_range * percentage_complete
            if self._start_colortemp > self._sunset_colortemp:
                temp = self._start_colortemp - temp_offset
            else:
                temp = self._start_colortemp + temp_offset
        else:
            # Nightime
            time_state = 'night'
            if now < stop_time and now > start_time:
                now_time = now
            else:
                now_time = stop_time
            temp_range = abs(self._sunset_colortemp - self._stop_colortemp)
            night_length = int(stop_time.timestamp() - sunset.timestamp())
            seconds_from_sunset = int(now_time.timestamp() -
                                      sunset.timestamp())
            percentage_complete = seconds_from_sunset / night_length
            temp_offset = temp_range * percentage_complete
            if self._sunset_colortemp > self._stop_colortemp:
                temp = self._sunset_colortemp - temp_offset
            else:
                temp = self._sunset_colortemp + temp_offset
        x_val, y_val, b_val = color_RGB_to_xy(*color_temperature_to_rgb(temp))
        brightness = self._brightness if self._brightness else b_val
        if self._mode == MODE_XY:
            set_lights_xy(self.hass, self._lights, x_val,
                          y_val, brightness)
            _LOGGER.info("Lights updated to x:%s y:%s brightness:%s, %s%%"
                         " of %s cycle complete at %s", x_val, y_val,
                         brightness, round(
                             percentage_complete * 100), time_state,
                         as_local(now))
        else:
            # Convert to mired and clamp to allowed values
            mired = color_temperature_kelvin_to_mired(temp)
            mired = max(HASS_COLOR_MIN, min(mired, HASS_COLOR_MAX))
            set_lights_temp(self.hass, self._lights, mired, brightness)
            _LOGGER.info("Lights updated to mired:%s brightness:%s, %s%%"
                         " of %s cycle complete at %s", mired, brightness,
                         round(percentage_complete * 100),
                         time_state, as_local(now))
Exemplo n.º 4
0
    def flux_update(self, now=None):
        """Update all the lights using flux."""
        if now is None:
            now = dt_now()
        sunset = next_setting(self.hass, SUN).replace(day=now.day,
                                                      month=now.month,
                                                      year=now.year)
        start_time = self.find_start_time(now)
        stop_time = now.replace(hour=self._stop_time.hour,
                                minute=self._stop_time.minute,
                                second=0)

        if start_time < now < sunset:
            # Daytime
            time_state = 'day'
            temp_range = abs(self._start_colortemp - self._sunset_colortemp)
            day_length = int(sunset.timestamp() - start_time.timestamp())
            seconds_from_start = int(now.timestamp() - start_time.timestamp())
            percentage_complete = seconds_from_start / day_length
            temp_offset = temp_range * percentage_complete
            if self._start_colortemp > self._sunset_colortemp:
                temp = self._start_colortemp - temp_offset
            else:
                temp = self._start_colortemp + temp_offset
        else:
            # Nightime
            time_state = 'night'
            if now < stop_time and now > start_time:
                now_time = now
            else:
                now_time = stop_time
            temp_range = abs(self._sunset_colortemp - self._stop_colortemp)
            night_length = int(stop_time.timestamp() - sunset.timestamp())
            seconds_from_sunset = int(now_time.timestamp() -
                                      sunset.timestamp())
            percentage_complete = seconds_from_sunset / night_length
            temp_offset = temp_range * percentage_complete
            if self._sunset_colortemp > self._stop_colortemp:
                temp = self._sunset_colortemp - temp_offset
            else:
                temp = self._sunset_colortemp + temp_offset
        x_val, y_val, b_val = color_RGB_to_xy(*color_temperature_to_rgb(temp))
        brightness = self._brightness if self._brightness else b_val
        if self._disable_brightness_adjust:
            brightness = None
        if self._mode == MODE_XY:
            set_lights_xy(self.hass, self._lights, x_val,
                          y_val, brightness)
            _LOGGER.info("Lights updated to x:%s y:%s brightness:%s, %s%%"
                         " of %s cycle complete at %s", x_val, y_val,
                         brightness, round(
                             percentage_complete * 100), time_state, now)
        else:
            # Convert to mired and clamp to allowed values
            mired = color_temperature_kelvin_to_mired(temp)
            mired = max(HASS_COLOR_MIN, min(mired, HASS_COLOR_MAX))
            set_lights_temp(self.hass, self._lights, mired, brightness)
            _LOGGER.info("Lights updated to mired:%s brightness:%s, %s%%"
                         " of %s cycle complete at %s", mired, brightness,
                         round(percentage_complete * 100), time_state, now)
Exemplo n.º 5
0
    def flux_update(self, now=None):
        """Update all the lights using flux."""
        if now is None:
            now = dt_now()
        sunset = next_setting(self.hass, SUN).replace(day=now.day,
                                                      month=now.month,
                                                      year=now.year)
        start_time = self.find_start_time(now)
        stop_time = now.replace(hour=self._stop_time.hour,
                                minute=self._stop_time.minute,
                                second=0)

        if start_time < now < sunset:
            # Daytime
            time_state = 'day'
            temp_range = abs(self._start_colortemp - self._sunset_colortemp)
            day_length = int(sunset.timestamp() - start_time.timestamp())
            seconds_from_start = int(now.timestamp() - start_time.timestamp())
            percentage_complete = seconds_from_start / day_length
            temp_offset = temp_range * percentage_complete
            if self._start_colortemp > self._sunset_colortemp:
                temp = self._start_colortemp - temp_offset
            else:
                temp = self._start_colortemp + temp_offset
        else:
            # Nightime
            time_state = 'night'
            if now < stop_time and now > start_time:
                now_time = now
            else:
                now_time = stop_time
            temp_range = abs(self._sunset_colortemp - self._stop_colortemp)
            night_length = int(stop_time.timestamp() - sunset.timestamp())
            seconds_from_sunset = int(now_time.timestamp() -
                                      sunset.timestamp())
            percentage_complete = seconds_from_sunset / night_length
            temp_offset = temp_range * percentage_complete
            if self._sunset_colortemp > self._stop_colortemp:
                temp = self._sunset_colortemp - temp_offset
            else:
                temp = self._sunset_colortemp + temp_offset
        if self._mode == MODE_XY:
            x_val, y_val, b_val = color_RGB_to_xy(*temp_to_rgb(temp))
            brightness = self._brightness if self._brightness else b_val
            set_lights_xy(self.hass, self._lights, x_val,
                          y_val, brightness)
            _LOGGER.info("Lights updated to x:%s y:%s brightness:%s, %s%%"
                         " of %s cycle complete at %s", x_val, y_val,
                         brightness, round(
                             percentage_complete * 100), time_state,
                         as_local(now))
        else:
            set_lights_temp(self.hass, self._lights, temp, self._mode)
            _LOGGER.info("Lights updated to temp:%s, %s%%"
                         " of %s cycle complete at %s", temp,
                         round(percentage_complete * 100),
                         time_state, as_local(now))
Exemplo n.º 6
0
    def get_sunrise_sunset(self, date=None):
        if (self.data["sunrise_time"] is not None
                and self.data["sunset_time"] is not None):
            if date is None:
                date = dt_now(self.data["timezone"])
            sunrise = date.replace(**self._time_dict("sunrise_time"))
            sunset = date.replace(**self._time_dict("sunset_time"))
            solar_noon = sunrise + (sunset - sunrise) / 2
            solar_midnight = sunset + (
                (sunrise + timedelta(days=1)) - sunset) / 2
        else:
            import astral

            location = astral.Location()
            location.name = "name"
            location.region = "region"
            location.latitude = self.data["latitude"]
            location.longitude = self.data["longitude"]
            location.elevation = self.data["elevation"]
            _LOGGER.debug("Astral location: " + str(location))
            if self.data["sunrise_time"] is not None:
                if date is None:
                    date = dt_now(self.data["timezone"])
                sunrise = date.replace(**self._time_dict("sunrise_time"))
            else:
                sunrise = location.sunrise(date)
            if self.data["sunset_time"] is not None:
                if date is None:
                    date = dt_now(self.data["timezone"])
                sunset = date.replace(**self._time_dict("sunset_time"))
            else:
                sunset = location.sunset(date)
            solar_noon = location.solar_noon(date)
            solar_midnight = location.solar_midnight(date)
        if self.data["sunrise_offset"] is not None:
            sunrise = sunrise + self.data["sunrise_offset"]
        if self.data["sunset_offset"] is not None:
            sunset = sunset + self.data["sunset_offset"]
        return {
            SUN_EVENT_SUNRISE: sunrise.astimezone(self.data["timezone"]),
            SUN_EVENT_SUNSET: sunset.astimezone(self.data["timezone"]),
            "solar_noon": solar_noon.astimezone(self.data["timezone"]),
            "solar_midnight": solar_midnight.astimezone(self.data["timezone"]),
        }
Exemplo n.º 7
0
    def flux_update(self, now=dt_now()):
        """Update all the lights using flux."""
        sunset = next_setting(self.hass, SUN).replace(day=now.day,
                                                      month=now.month,
                                                      year=now.year)
        start_time = self.find_start_time(now)
        stop_time = now.replace(hour=self._stop_time.hour,
                                minute=self._stop_time.minute,
                                second=0)

        if start_time < now < sunset:
            # Daytime
            time_state = 'day'
            temp_range = abs(self._start_colortemp - self._sunset_colortemp)
            day_length = int(sunset.timestamp() - start_time.timestamp())
            seconds_from_start = int(now.timestamp() - start_time.timestamp())
            percentage_complete = seconds_from_start / day_length
            temp_offset = temp_range * percentage_complete
            if self._start_colortemp > self._sunset_colortemp:
                temp = self._start_colortemp - temp_offset
            else:
                temp = self._start_colortemp + temp_offset
        else:
            # Nightime
            time_state = 'night'
            if now < stop_time and now > start_time:
                now_time = now
            else:
                now_time = stop_time
            temp_range = abs(self._sunset_colortemp - self._stop_colortemp)
            night_length = int(stop_time.timestamp() - sunset.timestamp())
            seconds_from_sunset = int(now_time.timestamp() -
                                      sunset.timestamp())
            percentage_complete = seconds_from_sunset / night_length
            temp_offset = temp_range * percentage_complete
            if self._sunset_colortemp > self._stop_colortemp:
                temp = self._sunset_colortemp - temp_offset
            else:
                temp = self._sunset_colortemp + temp_offset
        if self._mode == MODE_XY:
            x_val, y_val, b_val = color_RGB_to_xy(*temp_to_rgb(temp))
            brightness = self._brightness if self._brightness else b_val
            set_lights_xy(self.hass, self._lights, x_val,
                          y_val, brightness)
            _LOGGER.info("Lights updated to x:%s y:%s brightness:%s, %s%%"
                         " of %s cycle complete at %s", x_val, y_val,
                         brightness, round(
                             percentage_complete * 100), time_state,
                         as_local(now))
        else:
            set_lights_temp(self.hass, self._lights, temp, self._mode)
            _LOGGER.info("Lights updated to temp:%s, %s%%"
                         " of %s cycle complete at %s", temp,
                         round(percentage_complete * 100),
                         time_state, as_local(now))
Exemplo n.º 8
0
def sign_for_device(device):
    """Generate signature for divice"""
    if not device:
        return ['', '']
    
    now = dt_now()
    timestamp = int(now.timestamp())
    device_product_key = device[CONF_PRODUCT_KEY]
    device_name = device[CONF_DEVICE_NAME]
    device_secret = device[CONF_DEVICE_SECRET]
    device_client_id = "%s&&&%s" % (device_product_key, device_name)
    device_sign_content = "clientId%sdeviceName%sproductKey%stimestamp%d" % (device_client_id, device_name, device_product_key, timestamp)
    device_sign = make_hmacsha1_hexdigest(device_secret, device_sign_content)
    return [device_client_id, device_sign, timestamp]
Exemplo n.º 9
0
    def __init__(self, session, ip_address):
        """Initialize the data object."""
        self._session = session
        self._ip_address = ip_address
        self._data = None
        self._sensors = set()
        self._day = dt_now().day
        self._hour = dt_now().hour
        self._month = dt_now().month
        self._latest_call = time.time()

        self._latest_pv_power = 0
        self._latest_grid_power = 0
        self._latest_house_power = 0

        self._pv_energy_hour = 0
        self._pv_energy_month = 0

        self._grid_energy_hour = 0
        self._grid_energy_today = 0
        self._grid_energy_month = 0
        self._grid_energy_total = 0

        self._house_energy_hour = 0
        self._house_energy_today = 0
        self._house_energy_month = 0
        self._house_energy_total = 0

        self._grid_returned_energy_hour = 0
        self._grid_returned_energy_today = 0
        self._grid_returned_energy_month = 0
        self._grid_returned_energy_total = 0

        self._balance_neto_hour = 0
        self._balance_neto_today = 0
        self._balance_neto_month = 0
        self._balance_neto_total = 0
Exemplo n.º 10
0
    def flux_update(self, now=None):
        """Update all the lights using flux."""
        if now is None:
            now = dt_now()

        sunset = get_astral_event_date(self.hass, 'sunset', now.date())
        start_time = self.find_start_time(now)
        stop_time = now.replace(hour=self._stop_time.hour,
                                minute=self._stop_time.minute,
                                second=0)

        if stop_time <= start_time:
            # stop_time does not happen in the same day as start_time
            if start_time < now:
                # stop time is tomorrow
                stop_time += datetime.timedelta(days=1)
        elif now < start_time:
            # stop_time was yesterday since the new start_time is not reached
            stop_time -= datetime.timedelta(days=1)

        if start_time < now < sunset:
            # Daytime
            time_state = 'day'
            temp_range = abs(self._start_colortemp - self._sunset_colortemp)
            day_length = int(sunset.timestamp() - start_time.timestamp())
            seconds_from_start = int(now.timestamp() - start_time.timestamp())
            percentage_complete = seconds_from_start / day_length
            temp_offset = temp_range * percentage_complete
            if self._start_colortemp > self._sunset_colortemp:
                temp = self._start_colortemp - temp_offset
            else:
                temp = self._start_colortemp + temp_offset
        else:
            # Nightime
            time_state = 'night'

            if now < stop_time:
                if stop_time < start_time and stop_time.day == sunset.day:
                    # we need to use yesterday's sunset time
                    sunset_time = sunset - datetime.timedelta(days=1)
                else:
                    sunset_time = sunset

                # pylint: disable=no-member
                night_length = int(stop_time.timestamp() -
                                   sunset_time.timestamp())
                seconds_from_sunset = int(now.timestamp() -
                                          sunset_time.timestamp())
                percentage_complete = seconds_from_sunset / night_length
            else:
                percentage_complete = 1

            temp_range = abs(self._sunset_colortemp - self._stop_colortemp)
            temp_offset = temp_range * percentage_complete
            if self._sunset_colortemp > self._stop_colortemp:
                temp = self._sunset_colortemp - temp_offset
            else:
                temp = self._sunset_colortemp + temp_offset
        rgb = color_temperature_to_rgb(temp)
        x_val, y_val, b_val = color_RGB_to_xy(*rgb)
        brightness = self._brightness if self._brightness else b_val
        if self._disable_brightness_adjust:
            brightness = None
        if self._mode == MODE_XY:
            set_lights_xy(self.hass, self._lights, x_val, y_val, brightness)
            _LOGGER.info(
                "Lights updated to x:%s y:%s brightness:%s, %s%% "
                "of %s cycle complete at %s", x_val, y_val, brightness,
                round(percentage_complete * 100), time_state, now)
        elif self._mode == MODE_RGB:
            set_lights_rgb(self.hass, self._lights, rgb)
            _LOGGER.info(
                "Lights updated to rgb:%s, %s%% "
                "of %s cycle complete at %s", rgb,
                round(percentage_complete * 100), time_state, now)
        else:
            # Convert to mired and clamp to allowed values
            mired = color_temperature_kelvin_to_mired(temp)
            set_lights_temp(self.hass, self._lights, mired, brightness)
            _LOGGER.info(
                "Lights updated to mired:%s brightness:%s, %s%% "
                "of %s cycle complete at %s", mired, brightness,
                round(percentage_complete * 100), time_state, now)
Exemplo n.º 11
0
    def flux_update(self, now=None):
        """Update all the lights using flux."""
        if now is None:
            now = dt_now()

        sunset = get_astral_event_date(self.hass, 'sunset', now.date())
        start_time = self.find_start_time(now)
        stop_time = self.find_stop_time(now)

        if stop_time <= start_time:
            # stop_time does not happen in the same day as start_time
            if start_time < now:
                # stop time is tomorrow
                stop_time += datetime.timedelta(days=1)
        elif now < start_time:
            # stop_time was yesterday since the new start_time is not reached
            stop_time -= datetime.timedelta(days=1)

        if start_time < now < sunset:
            # Daytime
            time_state = 'day'
            temp_range = abs(self._start_colortemp - self._sunset_colortemp)
            day_length = int(sunset.timestamp() - start_time.timestamp())
            seconds_from_start = int(now.timestamp() - start_time.timestamp())
            percentage_complete = seconds_from_start / day_length
            temp_offset = temp_range * percentage_complete
            if self._start_colortemp > self._sunset_colortemp:
                temp = self._start_colortemp - temp_offset
            else:
                temp = self._start_colortemp + temp_offset
        else:
            # Night time
            time_state = 'night'

            if now < stop_time:
                if stop_time < start_time and stop_time.day == sunset.day:
                    # we need to use yesterday's sunset time
                    sunset_time = sunset - datetime.timedelta(days=1)
                else:
                    sunset_time = sunset

                # pylint: disable=no-member
                night_length = int(stop_time.timestamp() -
                                   sunset_time.timestamp())
                seconds_from_sunset = int(now.timestamp() -
                                          sunset_time.timestamp())
                percentage_complete = seconds_from_sunset / night_length
            else:
                percentage_complete = 1

            temp_range = abs(self._sunset_colortemp - self._stop_colortemp)
            temp_offset = temp_range * percentage_complete
            if self._sunset_colortemp > self._stop_colortemp:
                temp = self._sunset_colortemp - temp_offset
            else:
                temp = self._sunset_colortemp + temp_offset
        rgb = color_temperature_to_rgb(temp)
        x_val, y_val, b_val = color_RGB_to_xy_brightness(*rgb)
        brightness = self._brightness if self._brightness else b_val
        if self._disable_brightness_adjust:
            brightness = None
        if self._mode == MODE_XY:
            set_lights_xy(self.hass, self._lights, x_val,
                          y_val, brightness, self._transition)
            _LOGGER.info("Lights updated to x:%s y:%s brightness:%s, %s%% "
                         "of %s cycle complete at %s", x_val, y_val,
                         brightness, round(
                             percentage_complete * 100), time_state, now)
        elif self._mode == MODE_RGB:
            set_lights_rgb(self.hass, self._lights, rgb, self._transition)
            _LOGGER.info("Lights updated to rgb:%s, %s%% "
                         "of %s cycle complete at %s", rgb,
                         round(percentage_complete * 100), time_state, now)
        else:
            # Convert to mired and clamp to allowed values
            mired = color_temperature_kelvin_to_mired(temp)
            set_lights_temp(self.hass, self._lights, mired, brightness,
                            self._transition)
            _LOGGER.info("Lights updated to mired:%s brightness:%s, %s%% "
                         "of %s cycle complete at %s", mired, brightness,
                         round(percentage_complete * 100), time_state, now)
Exemplo n.º 12
0
    def calc_percent(self):
        now = dt_now(self.data['timezone'])
        _LOGGER.debug("now: " + str(now))

        today_sun_times = self.get_sunrise_sunset(now)
        _LOGGER.debug("today_sun_times: " + str(today_sun_times))

        # Convert everything to epoch timestamps for easy calculation
        now_seconds = now.timestamp()
        sunrise_seconds = today_sun_times[SUN_EVENT_SUNRISE].timestamp()
        sunset_seconds = today_sun_times[SUN_EVENT_SUNSET].timestamp()
        solar_noon_seconds = today_sun_times['solar_noon'].timestamp()
        solar_midnight_seconds = today_sun_times['solar_midnight'].timestamp()

        if now < today_sun_times[
                SUN_EVENT_SUNRISE]:  # It's before sunrise (after midnight)
            # Because it's before sunrise (and after midnight) sunset must have happend yesterday
            yesterday_sun_times = self.get_sunrise_sunset(now -
                                                          timedelta(days=1))
            _LOGGER.debug("yesterday_sun_times: " + str(yesterday_sun_times))
            sunset_seconds = yesterday_sun_times[SUN_EVENT_SUNSET].timestamp()
            if today_sun_times['solar_midnight'] > today_sun_times[
                    SUN_EVENT_SUNSET] and yesterday_sun_times[
                        'solar_midnight'] > yesterday_sun_times[
                            SUN_EVENT_SUNSET]:
                # Solar midnight is after sunset so use yesterdays's time
                solar_midnight_seconds = yesterday_sun_times[
                    'solar_midnight'].timestamp()
        elif now > today_sun_times[
                SUN_EVENT_SUNSET]:  # It's after sunset (before midnight)
            # Because it's after sunset (and before midnight) sunrise should happen tomorrow
            tomorrow_sun_times = self.get_sunrise_sunset(now +
                                                         timedelta(days=1))
            _LOGGER.debug("tomorrow_sun_times: " + str(tomorrow_sun_times))
            sunrise_seconds = tomorrow_sun_times[SUN_EVENT_SUNRISE].timestamp()
            if today_sun_times['solar_midnight'] < today_sun_times[
                    SUN_EVENT_SUNRISE] and tomorrow_sun_times[
                        'solar_midnight'] < tomorrow_sun_times[
                            SUN_EVENT_SUNRISE]:
                # Solar midnight is before sunrise so use tomorrow's time
                solar_midnight_seconds = tomorrow_sun_times[
                    'solar_midnight'].timestamp()

        _LOGGER.debug("now_seconds: " + str(now_seconds))
        _LOGGER.debug("sunrise_seconds: " + str(sunrise_seconds))
        _LOGGER.debug("sunset_seconds: " + str(sunset_seconds))
        _LOGGER.debug("solar_midnight_seconds: " + str(solar_midnight_seconds))
        _LOGGER.debug("solar_noon_seconds: " + str(solar_noon_seconds))

        # Figure out where we are in time so we know which half of the parabola to calculate
        # We're generating a different sunset-sunrise parabola for before and after solar midnight
        # because it might not be half way between sunrise and sunset
        # We're also (obviously) generating a different parabola for sunrise-sunset

        # sunrise-sunset parabola
        if now_seconds > sunrise_seconds and now_seconds < sunset_seconds:
            h = solar_noon_seconds
            k = 100
            # parabola before solar_noon
            if now_seconds < solar_noon_seconds:
                x = sunrise_seconds
            # parabola after solar_noon
            else:
                x = sunset_seconds
            y = 0

        # sunset_sunrise parabola
        elif now_seconds > sunset_seconds and now_seconds < sunrise_seconds:
            h = solar_midnight_seconds
            k = -100
            # parabola before solar_midnight
            if now_seconds < solar_midnight_seconds:
                x = sunset_seconds
            # parabola after solar_midnight
            else:
                x = sunrise_seconds
            y = 0

        a = (y - k) / (h - x)**2
        percentage = a * (now_seconds - h)**2 + k

        _LOGGER.debug("h: " + str(h))
        _LOGGER.debug("k: " + str(k))
        _LOGGER.debug("x: " + str(x))
        _LOGGER.debug("y: " + str(y))
        _LOGGER.debug("a: " + str(a))
        _LOGGER.debug("percentage: " + str(percentage))

        return percentage
Exemplo n.º 13
0
    def calc_percent(self):
        now = dt_now()
        today_sun_times = self.get_sunrise_sunset()

        now_seconds = now.timestamp()
        today_sunrise_seconds = today_sun_times['sunrise'].timestamp()
        today_sunset_seconds = today_sun_times['sunset'].timestamp()
        today_solar_noon_seconds = today_sun_times['solar_noon'].timestamp()
        today_solar_midnight_seconds = today_sun_times[
            'solar_midnight'].timestamp()

        if now < today_sun_times['sunrise']:
            yesterday_sun_times = self.get_sunrise_sunset(now -
                                                          timedelta(days=1))
            yesterday_sunrise_seconds = yesterday_sun_times[
                'sunrise'].timestamp()
            yesterday_sunset_seconds = yesterday_sun_times['sunset'].timestamp(
            )
            yesterday_solar_midnight_seconds = yesterday_sun_times[
                'solar_midnight'].timestamp()

            x1 = yesterday_sunset_seconds
            y1 = 0

            if today_sun_times['solar_midnight'] > yesterday_sun_times[
                    'sunset'] and today_sun_times[
                        'solar_midnight'] < today_sun_times['sunrise']:
                x2 = today_solar_midnight_seconds
            else:
                x2 = yesterday_solar_midnight_seconds
            y2 = -100

            x3 = today_sunrise_seconds
            y3 = 0
        elif now > today_sun_times['sunset']:
            tomorrow_sun_times = self.get_sunrise_sunset(now +
                                                         timedelta(days=1))
            tomorrow_sunrise_seconds = tomorrow_sun_times['sunrise'].timestamp(
            )
            tomorrow_sunset_seconds = tomorrow_sun_times['sunset'].timestamp()
            tomorrow_solar_midnight_seconds = tomorrow_sun_times[
                'solar_midnight'].timestamp()

            x1 = today_sunset_seconds
            y1 = 0

            if today_sun_times['solar_midnight'] > today_sun_times[
                    'sunset'] and today_sun_times[
                        'solar_midnight'] < tomorrow_sun_times['sunrise']:
                x2 = today_solar_midnight_seconds
            else:
                x2 = tomorrow_solar_midnight_seconds
            y2 = -100

            x3 = tomorrow_sunrise_seconds
            y3 = 0
        else:
            x1 = today_sunrise_seconds
            y1 = 0
            x2 = today_solar_noon_seconds
            y2 = 100
            x3 = today_sunset_seconds
            y3 = 0

        # Generate color temperature parabola from points
        a1 = -x1**2 + x2**2
        b1 = -x1 + x2
        d1 = -y1 + y2
        a2 = -x2**2 + x3**2
        b2 = -x2 + x3
        d2 = -y2 + y3
        bm = -(b2 / b1)
        a3 = bm * a1 + a2
        d3 = bm * d1 + d2
        a = d3 / a3
        b = (d1 - a1 * a) / b1
        c = y1 - a * x1**2 - b * x1
        percentage = a * now_seconds**2 + b * now_seconds + c

        return percentage
Exemplo n.º 14
0
    async def async_push_indications(
        self,
        indications: List[Union[str, SupportsFloat]],
        force: bool = False,
        service_type: Optional[str] = None,
        dry_run: bool = False,
    ) -> None:
        error = None
        pass_indications = None
        try:
            if isinstance(self.service_type, str):
                if service_type is None:
                    service_type = self.service_type
                elif service_type != self.service_type:
                    raise ValueError(
                        'Incorrect service type provided (expected: "%s", got: "%s"'
                        % (self.service_type, service_type)
                    )
            elif service_type is None:
                raise ValueError(
                    "Service type not defined for multi-service-type indications entity"
                )
            elif service_type not in self.service_type:
                raise ValueError(
                    'Incorrect service type provided (expected: %s, got: "%s")'
                    % (self.service_type, service_type)
                )

            if not indications:
                raise ValueError("Indications are empty")

            indications_count = await self.async_get_indications_count(service_type, force)
            if indications_count is not None:
                if isinstance(indications_count, int):
                    if indications_count != len(indications):
                        raise ValueError(
                            "Invalid indications count provided (expected: %d, got: %d)"
                            % (indications_count, len(indications))
                        )
                elif len(indications) not in range(indications_count[0], indications_count[1] + 1):
                    raise ValueError(
                        "Invalid indications count provided (expected: %d <= N <= %d, got: %d)"
                        % (indications_count[0], indications_count[1], len(indications))
                    )

            pass_indications = []
            state_machine = self.hass.states
            for indication in indications:
                if isinstance(indication, str):
                    state = state_machine.get(indication)
                    if state is None:
                        raise ValueError(
                            'Could not retrieve state for entity with ID "%s"' % (indication,)
                        )

                    indication = state.state

                pass_indications.append(
                    float(indication)
                )  # will raise ValueError if non-floatable type

            await self._async_push_indications(pass_indications, force, service_type, dry_run)

        except Exception as e:
            error = e
            raise

        finally:
            event_data_dict = {
                ATTR_TIME: dt_now().isoformat(),
                ATTR_ENTITY_ID: self.entity_id,
                ATTR_SERVICE_TYPE: service_type,
                ATTR_INDICATIONS: pass_indications,
                ATTR_ORIGINAL_INDICATIONS: indications,
                ATTR_DRY_RUN: dry_run,
                ATTR_SUCCESS: not error,
            }

            if error:
                event_data_dict[ATTR_REASON] = str(error)

            update_dict = await self.async_get_indications_event_data_dict(
                indications=pass_indications or indications, force=force, service_type=service_type
            )

            if update_dict:
                event_data_dict.update(update_dict)

            self.hass.bus.async_fire(
                event_type=EVENT_FORMAT_INDICATIONS_PUSH % (service_type,),
                event_data=event_data_dict,
            )
Exemplo n.º 15
0
    async def _update(self):
        """Get the latest data from inverter."""
        _LOGGER.debug("-->{}s {}(PowerflowData) ({}:{})".format(
            round(time.time() - start_time, 3),
            inspect.currentframe().f_code.co_name, os.path.basename(__file__),
            inspect.currentframe().f_lineno))
        self._data = (await self.fetch_data(self._build_url()))['Body']['Data']
        current_time = time.time()
        elapsed = int(round(current_time - self._latest_call))
        pv_energy_elapsed = self._latest_pv_power * elapsed
        grid_energy_elapsed = self._latest_grid_power * elapsed
        house_energy_elapsed = self._latest_house_power * elapsed
        self._balance_neto_hour -= grid_energy_elapsed

        self._pv_energy_hour += pv_energy_elapsed
        self._pv_energy_month += pv_energy_elapsed

        if self._latest_grid_power > 0:
            self._grid_energy_hour += grid_energy_elapsed
            self._grid_energy_today += grid_energy_elapsed
            self._grid_energy_month += grid_energy_elapsed
            self._grid_energy_total += grid_energy_elapsed
        else:
            self._grid_returned_energy_hour -= grid_energy_elapsed
            self._grid_returned_energy_today -= grid_energy_elapsed
            self._grid_returned_energy_month -= grid_energy_elapsed
            self._grid_returned_energy_total -= grid_energy_elapsed

        # house_power is a negative number
        if self._latest_house_power < 0:
            self._house_energy_hour -= house_energy_elapsed
            self._house_energy_today -= house_energy_elapsed
            self._house_energy_month -= house_energy_elapsed
            self._house_energy_total -= house_energy_elapsed

        if self._data:
            self._latest_pv_power = int(round(self._data['Site']['P_PV'])
                                        ) if self._data['Site']['P_PV'] else 0
            self._latest_grid_power = int(round(self._data['Site']['P_Grid']))
            self._latest_house_power = int(round(self._data['Site']['P_Load']))
            self._latest_call = current_time

        if dt_now().hour != self._hour:
            self._hour = dt_now().hour

            if self._grid_energy_hour > self._grid_returned_energy_hour:
                self._balance_neto_today += self._grid_returned_energy_hour
                self._balance_neto_month += self._grid_returned_energy_hour
                self._balance_neto_total += self._grid_returned_energy_hour
            else:
                self._balance_neto_today += self._grid_energy_hour
                self._balance_neto_month += self._grid_energy_hour
                self._balance_neto_total += self._grid_energy_hour

            self._balance_neto_hour = 0
            self._pv_energy_hour = 0
            self._grid_energy_hour = 0
            self._house_energy_hour = 0
            self._grid_returned_energy_hour = 0
            if dt_now().day != self._day:
                self._day = dt_now().day
                self._balance_neto_today = 0
                self._grid_energy_today = 0
                self._house_energy_today = 0
                self._grid_returned_energy_today = 0

                if dt_now().month != self._month:
                    self._month = dt_now().month
                    self._balance_neto_month = 0
                    self._pv_energy_month = 0
                    self._grid_energy_month = 0
                    self._house_energy_month = 0
                    self._grid_returned_energy_month = 0

        _LOGGER.debug("<--{}s {}(PowerflowData) ({}:{})".format(
            round(time.time() - start_time, 3),
            inspect.currentframe().f_code.co_name, os.path.basename(__file__),
            inspect.currentframe().f_lineno))
Exemplo n.º 16
0
    def flux_force_update(self, call=None, entity=None):
        """Forced update of given or all the lights using flux."""
        now = dt_now()

        if call is None:
            if entity is None:
                entity_id = self._lights
            else:
                entity_id = entity
        else:
            entity_id = call.data.get("entity_id", self._lights)

        _LOGGER.info("Flux forced update for %s",
            entity_id)


        sunset = get_astral_event_date(self.hass, 'sunset', now.date())
        start_time = self.find_start_time(now)
        stop_time = now.replace(
            hour=self._stop_time.hour, minute=self._stop_time.minute,
            second=0)

        if stop_time <= start_time:
            # stop_time does not happen in the same day as start_time
            if start_time < now:
                # stop time is tomorrow
                stop_time += datetime.timedelta(days=1)
        elif now < start_time:
            # stop_time was yesterday since the new start_time is not reached
            stop_time -= datetime.timedelta(days=1)

        if start_time < now < sunset:
            # Daytime
            time_state = 'day'
            temp_range = abs(self._start_colortemp - self._sunset_colortemp)
            day_length = int(sunset.timestamp() - start_time.timestamp())
            seconds_from_start = int(now.timestamp() - start_time.timestamp())
            percentage_complete = seconds_from_start / day_length
            temp_offset = temp_range * percentage_complete
            if self._start_colortemp > self._sunset_colortemp:
                temp = self._start_colortemp - temp_offset
            else:
                temp = self._start_colortemp + temp_offset
        else:
            # Nightime
            time_state = 'night'

            if now < stop_time:
                if stop_time < start_time and stop_time.day == sunset.day:
                    # we need to use yesterday's sunset time
                    sunset_time = sunset - datetime.timedelta(days=1)
                else:
                    sunset_time = sunset

                # pylint: disable=no-member
                night_length = int(stop_time.timestamp() -
                                   sunset_time.timestamp())
                seconds_from_sunset = int(now.timestamp() -
                                          sunset_time.timestamp())
                percentage_complete = seconds_from_sunset / night_length
            else:
                percentage_complete = 1

            temp_range = abs(self._sunset_colortemp - self._stop_colortemp)
            temp_offset = temp_range * percentage_complete
            if self._sunset_colortemp > self._stop_colortemp:
                temp = self._sunset_colortemp - temp_offset
            else:
                temp = self._sunset_colortemp + temp_offset
        rgb = color_temperature_to_rgb(temp)
        x_val, y_val, b_val = color_RGB_to_xy(*rgb)
        brightness = self._brightness if self._brightness else b_val
        
        if self._mode == MODE_XY:
            _LOGGER.debug("Trying to force update of %s to XY %s, %s", entity_id, x_val, y_val)
            force_light_xy(self.hass, entity_id, x_val,
                          y_val, brightness)
            new_color_xy = set_lights_xy(self.hass, self._lights, x_val,
                              y_val, brightness, self._transition, self._last_color)
            _LOGGER.info("Lights updated to x:%s y:%s brightness:%s, %s%% "
                         "of %s cycle complete at %s", x_val, y_val,
                         brightness, round(
                             percentage_complete * 100), time_state, now)
            self._last_color = new_color_xy
        elif self._mode == MODE_RGB:
            force_light_rgb(self.hass, entity_id, rgb)
            new_color_rgb = set_lights_rgb(self.hass, self._lights, rgb, self._transition, self._last_color)
            _LOGGER.info("Lights updated to rgb:%s, %s%% "
                         "of %s cycle complete at %s", rgb,
                         round(percentage_complete * 100), time_state, now)
            self._last_color = new_color_rgb
        else:
            # Convert to mired and clamp to allowed values
            mired = color_temperature_kelvin_to_mired(temp)
            _LOGGER.debug("Trying to force update of %s to mired %s", entity_id, mired)
            force_light_temp(self.hass, entity_id, mired, brightness)
            new_colortemp = set_lights_temp(self.hass, self._lights, mired, brightness,
                            self._transition, self._last_color)
            _LOGGER.info("Lights updated from %s to mired:%s brightness:%s, %s%% "
                         "of %s cycle complete at %s", self._last_color, mired, brightness,
                         round(percentage_complete * 100), time_state, now)
            self._last_color = new_colortemp