Exemplo n.º 1
0
    def update(self):
        """Get the latest data and updates the states."""
        time_date = dt_util.utcnow()
        time = dt_util.as_local(time_date).strftime(TIME_STR_FORMAT)
        time_utc = time_date.strftime(TIME_STR_FORMAT)
        date = dt_util.as_local(time_date).date().isoformat()

        # Calculate Swatch Internet Time.
        time_bmt = time_date + timedelta(hours=1)
        delta = timedelta(hours=time_bmt.hour,
                          minutes=time_bmt.minute,
                          seconds=time_bmt.second,
                          microseconds=time_bmt.microsecond)
        beat = int((delta.seconds + delta.microseconds / 1000000.0) / 86.4)

        if self.type == 'time':
            self._state = time
        elif self.type == 'date':
            self._state = date
        elif self.type == 'date_time':
            self._state = date + ', ' + time
        elif self.type == 'time_date':
            self._state = time + ', ' + date
        elif self.type == 'time_utc':
            self._state = time_utc
        elif self.type == 'beat':
            self._state = '@{0:03d}'.format(beat)
Exemplo n.º 2
0
    def update(self):
        """Get the latest data and updates the states."""
        time_date = dt_util.utcnow()
        time = dt_util.as_local(time_date).strftime(TIME_STR_FORMAT)
        time_utc = time_date.strftime(TIME_STR_FORMAT)
        date = dt_util.as_local(time_date).date().isoformat()

        # Calculate Swatch Internet Time.
        time_bmt = time_date + timedelta(hours=1)
        delta = timedelta(hours=time_bmt.hour,
                          minutes=time_bmt.minute,
                          seconds=time_bmt.second,
                          microseconds=time_bmt.microsecond)
        beat = int((delta.seconds + delta.microseconds / 1000000.0) / 86.4)

        if self.type == 'time':
            self._state = time
        elif self.type == 'date':
            self._state = date
        elif self.type == 'date_time':
            self._state = date + ', ' + time
        elif self.type == 'time_date':
            self._state = time + ', ' + date
        elif self.type == 'time_utc':
            self._state = time_utc
        elif self.type == 'beat':
            self._state = '@{0:03d}'.format(beat)
Exemplo n.º 3
0
    def update(self):
        """Get the latest data from opendata.ch."""
        response = requests.get(
            _RESOURCE +
            'connections?' +
            'from=' + self.start + '&' +
            'to=' + self.destination + '&' +
            'fields[]=connections/from/departureTimestamp/&' +
            'fields[]=connections/',
            timeout=30)
        connections = response.json()['connections'][:2]

        try:
            self.times = [
                dt_util.as_local(
                    dt_util.utc_from_timestamp(
                        item['from']['departureTimestamp'])).strftime(
                            TIME_STR_FORMAT)
                for item in connections
            ]
            self.times.append(
                dt_util.as_local(
                    dt_util.utc_from_timestamp(
                        connections[0]['from']['departureTimestamp'])) -
                dt_util.as_local(dt_util.utcnow()))
        except KeyError:
            self.times = ['n/a']
Exemplo n.º 4
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
            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_of_day_complete = seconds_from_start / day_length
            temp_offset = temp_range * percentage_of_day_complete
            if self._start_colortemp > self._sunset_colortemp:
                temp = self._start_colortemp - temp_offset
            else:
                temp = self._start_colortemp + temp_offset
            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 day cycle complete at %s", x_val, y_val, brightness,
                round(percentage_of_day_complete * 100), as_local(now))
        else:
            # Nightime
            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_of_night_complete = seconds_from_sunset / night_length
            temp_offset = temp_range * percentage_of_night_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(*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 night cycle complete at %s", x_val, y_val, brightness,
                round(percentage_of_night_complete * 100), as_local(now))
Exemplo n.º 5
0
    def __repr__(self):
        """Return the representation of the states."""
        attr = "; {}".format(util.repr_helper(self.attributes)) \
               if self.attributes else ""

        return "<state {}={}{} @ {}>".format(
            self.entity_id, self.state, attr,
            dt_util.as_local(self.last_changed).isoformat())
Exemplo n.º 6
0
    def busy_callback(worker_count, current_jobs, pending_jobs_count):
        """Callback to be called when the pool queue gets too big."""
        _LOGGER.warning(
            "WorkerPool:All %d threads are busy and %d jobs pending",
            worker_count, pending_jobs_count)

        for start, job in current_jobs:
            _LOGGER.warning("WorkerPool:Current job from %s: %s",
                            dt_util.as_local(start).isoformat(), job)
Exemplo n.º 7
0
    def test_as_local_with_utc_object(self):
        """Test local time with UTC object."""
        dt_util.set_default_time_zone(dt_util.get_time_zone(TEST_TIME_ZONE))

        utcnow = dt_util.utcnow()
        localnow = dt_util.as_local(utcnow)

        self.assertEqual(localnow, utcnow)
        self.assertNotEqual(localnow.tzinfo, utcnow.tzinfo)
Exemplo n.º 8
0
 def update(self):
     """Get the latest system information."""
     import psutil
     if self.type == 'disk_use_percent':
         self._state = psutil.disk_usage(self.argument).percent
     elif self.type == 'disk_use':
         self._state = round(psutil.disk_usage(self.argument).used /
                             1024**3, 1)
     elif self.type == 'disk_free':
         self._state = round(psutil.disk_usage(self.argument).free /
                             1024**3, 1)
     elif self.type == 'memory_use_percent':
         self._state = psutil.virtual_memory().percent
     elif self.type == 'memory_use':
         self._state = round((psutil.virtual_memory().total -
                              psutil.virtual_memory().available) /
                             1024**2, 1)
     elif self.type == 'memory_free':
         self._state = round(psutil.virtual_memory().available / 1024**2, 1)
     elif self.type == 'swap_use_percent':
         self._state = psutil.swap_memory().percent
     elif self.type == 'swap_use':
         self._state = round(psutil.swap_memory().used / 1024**3, 1)
     elif self.type == 'swap_free':
         self._state = round(psutil.swap_memory().free / 1024**3, 1)
     elif self.type == 'processor_use':
         self._state = round(psutil.cpu_percent(interval=None))
     elif self.type == 'process':
         if any(self.argument in l.name() for l in psutil.process_iter()):
             self._state = STATE_ON
         else:
             self._state = STATE_OFF
     elif self.type == 'network_out':
         self._state = round(psutil.net_io_counters(pernic=True)
                             [self.argument][0] / 1024**2, 1)
     elif self.type == 'network_in':
         self._state = round(psutil.net_io_counters(pernic=True)
                             [self.argument][1] / 1024**2, 1)
     elif self.type == 'packets_out':
         self._state = psutil.net_io_counters(pernic=True)[self.argument][2]
     elif self.type == 'packets_in':
         self._state = psutil.net_io_counters(pernic=True)[self.argument][3]
     elif self.type == 'ipv4_address':
         self._state = psutil.net_if_addrs()[self.argument][0][1]
     elif self.type == 'ipv6_address':
         self._state = psutil.net_if_addrs()[self.argument][1][1]
     elif self.type == 'last_boot':
         self._state = dt_util.as_local(
             dt_util.utc_from_timestamp(psutil.boot_time())
         ).date().isoformat()
     elif self.type == 'since_last_boot':
         self._state = dt_util.utcnow() - dt_util.utc_from_timestamp(
             psutil.boot_time())
Exemplo n.º 9
0
    def update(self):
        """Get the latest data from opendata.ch."""
        response = requests.get(
            _RESOURCE + 'connections?' + 'from=' + self.start + '&' + 'to=' +
            self.destination + '&' +
            'fields[]=connections/from/departureTimestamp/&' +
            'fields[]=connections/',
            timeout=30)
        connections = response.json()['connections'][:2]

        try:
            self.times = [
                dt_util.as_local(
                    dt_util.utc_from_timestamp(
                        item['from']['departureTimestamp'])).strftime(
                            TIME_STR_FORMAT) for item in connections
            ]
            self.times.append(
                dt_util.as_local(
                    dt_util.utc_from_timestamp(connections[0]['from']
                                               ['departureTimestamp'])) -
                dt_util.as_local(dt_util.utcnow()))
        except KeyError:
            self.times = ['n/a']
Exemplo n.º 10
0
def render(hass, template, variables=None, **kwargs):
    """Render given template."""
    if variables is not None:
        kwargs.update(variables)

    location_methods = LocationMethods(hass)
    utcnow = dt_util.utcnow()

    try:
        return ENV.from_string(template, {
            'closest': location_methods.closest,
            'distance': location_methods.distance,
            'float': forgiving_float,
            'is_state': hass.states.is_state,
            'is_state_attr': hass.states.is_state_attr,
            'now': dt_util.as_local(utcnow),
            'states': AllStates(hass),
            'utcnow': utcnow,
            'as_timestamp': dt_util.as_timestamp,
            'relative_time': dt_util.get_age
        }).render(kwargs).strip()
    except jinja2.TemplateError as err:
        raise TemplateError(err)
Exemplo n.º 11
0
def render(hass, template, variables=None, **kwargs):
    """Render given template."""
    if variables is not None:
        kwargs.update(variables)

    location_methods = LocationMethods(hass)
    utcnow = dt_util.utcnow()

    try:
        return ENV.from_string(
            template, {
                'closest': location_methods.closest,
                'distance': location_methods.distance,
                'float': forgiving_float,
                'is_state': hass.states.is_state,
                'is_state_attr': hass.states.is_state_attr,
                'now': dt_util.as_local(utcnow),
                'states': AllStates(hass),
                'utcnow': utcnow,
                'as_timestamp': dt_util.as_timestamp,
                'relative_time': dt_util.get_age
            }).render(kwargs).strip()
    except jinja2.TemplateError as err:
        raise TemplateError(err)
Exemplo n.º 12
0
 def test_as_local_with_naive_object(self):
     """Test local time with native object."""
     now = dt_util.now()
     self.assertAlmostEqual(
         now, dt_util.as_local(datetime.utcnow()),
         delta=timedelta(seconds=1))
Exemplo n.º 13
0
def next_rising(hass, entity_id=None):
    """Local datetime object of the next sun rising."""
    utc_next = next_rising_utc(hass, entity_id)

    return dt_util.as_local(utc_next) if utc_next else None