Esempio n. 1
0
    async def get(self, request, datetime=None):
        """Retrieve logbook entries."""
        if datetime:
            datetime = dt_util.parse_datetime(datetime)

            if datetime is None:
                return self.json_message("Invalid datetime", HTTP_BAD_REQUEST)
        else:
            datetime = dt_util.start_of_local_day()

        period = request.query.get("period")
        if period is None:
            period = 1
        else:
            period = int(period)

        entity_id = request.query.get("entity")
        start_day = dt_util.as_utc(datetime) - timedelta(days=period - 1)
        end_day = start_day + timedelta(days=period)
        opp = request.app["opp"]

        def json_events():
            """Fetch events and generate JSON."""
            return self.json(
                _get_events(opp, self.config, start_day, end_day, entity_id))

        return await opp.async_add_job(json_events)
Esempio n. 2
0
 async def async_update(self) -> None:
     """Update entity."""
     local = dt_util.start_of_local_day().replace(microsecond=0)
     start = dt_util.as_utc(local)
     end = start + timedelta(days=self._days)
     self._upcoming = await self.sonarr.calendar(start=start.isoformat(),
                                                 end=end.isoformat())
Esempio n. 3
0
def get_date(date):
    """Get the dateTime from date or dateTime as a local."""
    if "date" in date:
        return dt.start_of_local_day(
            dt.dt.datetime.combine(dt.parse_date(date["date"]),
                                   dt.dt.time.min))
    return dt.as_local(dt.parse_datetime(date["dateTime"]))
Esempio n. 4
0
def convert_time_to_isodate(timestr: str) -> str:
    """Take a string like 08:00:00 and combine it with the current date."""
    combined = datetime.combine(dt.start_of_local_day(),
                                dt.parse_time(timestr))
    if combined < datetime.now():
        combined = combined + timedelta(days=1)
    return combined.isoformat()
Esempio n. 5
0
def convert_time_to_utc(timestr):
    """Take a string like 08:00:00 and convert it to a unix timestamp."""
    combined = datetime.combine(dt_util.start_of_local_day(),
                                dt_util.parse_time(timestr))
    if combined < datetime.now():
        combined = combined + timedelta(days=1)
    return dt_util.as_timestamp(combined)
Esempio n. 6
0
    async def get(self, request, datetime=None):
        """Retrieve logbook entries."""
        if datetime:
            datetime = dt_util.parse_datetime(datetime)

            if datetime is None:
                return self.json_message("Invalid datetime", HTTP_BAD_REQUEST)
        else:
            datetime = dt_util.start_of_local_day()

        period = request.query.get("period")
        if period is None:
            period = 1
        else:
            period = int(period)

        entity_ids = request.query.get("entity")
        if entity_ids:
            try:
                entity_ids = cv.entity_ids(entity_ids)
            except vol.Invalid:
                raise InvalidEntityFormatError(
                    f"Invalid entity id(s) encountered: {entity_ids}. "
                    "Format should be <domain>.<object_id>") from vol.Invalid

        end_time = request.query.get("end_time")
        if end_time is None:
            start_day = dt_util.as_utc(datetime) - timedelta(days=period - 1)
            end_day = start_day + timedelta(days=period)
        else:
            start_day = datetime
            end_day = dt_util.parse_datetime(end_time)
            if end_day is None:
                return self.json_message("Invalid end_time", HTTP_BAD_REQUEST)

        opp = request.app["opp"]

        entity_matches_only = "entity_matches_only" in request.query
        context_id = request.query.get("context_id")

        if entity_ids and context_id:
            return self.json_message("Can't combine entity with context_id",
                                     HTTP_BAD_REQUEST)

        def json_events():
            """Fetch events and generate JSON."""
            return self.json(
                _get_events(
                    opp,
                    start_day,
                    end_day,
                    entity_ids,
                    self.filters,
                    self.entities_filter,
                    entity_matches_only,
                    context_id,
                ))

        return await opp.async_add_executor_job(json_events)
Esempio n. 7
0
    def parse_time_at_default_timezone(time_str: str) -> time | None:
        """Parse a time string and add default timezone."""
        parsed_time = dt_util.parse_time(time_str)

        if parsed_time is None:
            return None

        return (dt_util.start_of_local_day().replace(
            hour=parsed_time.hour,
            minute=parsed_time.minute,
            second=parsed_time.second,
        ).timetz())
Esempio n. 8
0
 def get_next_interval(self, now=None):
     """Compute next time an update should occur."""
     if now is None:
         now = dt_util.utcnow()
     if self.type == "date":
         now = dt_util.start_of_local_day(dt_util.as_local(now))
         return now + timedelta(seconds=86400)
     if self.type == "beat":
         interval = 86.4
     else:
         interval = 60
     timestamp = int(dt_util.as_timestamp(now))
     delta = interval - (timestamp % interval)
     return now + timedelta(seconds=delta)
Esempio n. 9
0
    def get_daily_usage(self):
        """Return current daily power usage."""
        kwh = 0
        start_time = dt_util.start_of_local_day().astimezone(
            dt_util.UTC).isoformat()
        end_time = dt_util.utcnow().isoformat()

        _LOGGER.debug("Start: %s, End: %s", start_time, end_time)

        try:
            history = self.neurio_client.get_samples_stats(
                self.sensor_id, start_time, "days", end_time)
        except (requests.exceptions.RequestException, ValueError, KeyError):
            _LOGGER.warning("Could not update daily power usage")
            return None

        for result in history:
            kwh += result["consumptionEnergy"] / 3600000

        self._daily_usage = round(kwh, 2)
Esempio n. 10
0
    async def async_tcs_svc_request(self, service: dict, data: dict) -> None:
        """Process a service request (system mode) for a controller.

        Data validation is not required, it will have been done upstream.
        """
        if service == SVC_SET_SYSTEM_MODE:
            mode = data[ATTR_SYSTEM_MODE]
        else:  # otherwise it is SVC_RESET_SYSTEM
            mode = EVO_RESET

        if ATTR_DURATION_DAYS in data:
            until = dt_util.start_of_local_day()
            until += data[ATTR_DURATION_DAYS]

        elif ATTR_DURATION_HOURS in data:
            until = dt_util.now() + data[ATTR_DURATION_HOURS]

        else:
            until = None

        await self._set_tcs_mode(mode, until=until)
Esempio n. 11
0
    def get_next_interval(self):
        """Compute next time an update should occur."""
        now = dt_util.utcnow()

        if self.type == "date":
            tomorrow = dt_util.as_local(now) + timedelta(days=1)
            return dt_util.start_of_local_day(tomorrow)

        if self.type == "beat":
            # Add 1 hour because @0 beats is at 23:00:00 UTC.
            timestamp = dt_util.as_timestamp(now + timedelta(hours=1))
            interval = 86.4
        else:
            timestamp = dt_util.as_timestamp(now)
            interval = 60

        delta = interval - (timestamp % interval)
        next_interval = now + timedelta(seconds=delta)
        _LOGGER.debug("%s + %s -> %s (%s)", now, delta, next_interval, self.type)

        return next_interval
Esempio n. 12
0
    def update(self):
        """Get the latest data."""
        start_of_today = dt.start_of_local_day()
        start_of_tomorrow = dt.start_of_local_day() + timedelta(days=self.days)

        # We have to retrieve the results for the whole day as the server
        # won't return events that have already started
        results = self.calendar.date_search(start_of_today, start_of_tomorrow)

        # Create new events for each recurrence of an event that happens today.
        # For recurring events, some servers return the original event with recurrence rules
        # and they would not be properly parsed using their original start/end dates.
        new_events = []
        for event in results:
            vevent = event.instance.vevent
            for start_dt in vevent.getrruleset() or []:
                _start_of_today = start_of_today
                _start_of_tomorrow = start_of_tomorrow
                if self.is_all_day(vevent):
                    start_dt = start_dt.date()
                    _start_of_today = _start_of_today.date()
                    _start_of_tomorrow = _start_of_tomorrow.date()
                if _start_of_today <= start_dt < _start_of_tomorrow:
                    new_event = event.copy()
                    new_vevent = new_event.instance.vevent
                    if hasattr(new_vevent, "dtend"):
                        dur = new_vevent.dtend.value - new_vevent.dtstart.value
                        new_vevent.dtend.value = start_dt + dur
                    new_vevent.dtstart.value = start_dt
                    new_events.append(new_event)
                elif _start_of_tomorrow <= start_dt:
                    break
        vevents = [event.instance.vevent for event in results + new_events]

        # dtstart can be a date or datetime depending if the event lasts a
        # whole day. Convert everything to datetime to be able to sort it
        vevents.sort(key=lambda x: self.to_datetime(x.dtstart.value))

        vevent = next(
            (
                vevent
                for vevent in vevents
                if (
                    self.is_matching(vevent, self.search)
                    and (not self.is_all_day(vevent) or self.include_all_day)
                    and not self.is_over(vevent)
                )
            ),
            None,
        )

        # If no matching event could be found
        if vevent is None:
            _LOGGER.debug(
                "No matching event found in the %d results for %s",
                len(vevents),
                self.calendar.name,
            )
            self.event = None
            return

        # Populate the entity attributes with the event values
        self.event = {
            "summary": vevent.summary.value,
            "start": self.get_opp_date(vevent.dtstart.value),
            "end": self.get_opp_date(self.get_end_date(vevent)),
            "location": self.get_attr_value(vevent, "location"),
            "description": self.get_attr_value(vevent, "description"),
        }