From e0ecb64a108db390488ef91b70279ebe42429f80 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Tue, 28 Apr 2015 19:12:05 -0700 Subject: [PATCH 01/11] Use UTC as the internal datetime format --- homeassistant/__init__.py | 56 +++++-- homeassistant/bootstrap.py | 24 ++- .../components/device_tracker/__init__.py | 9 +- homeassistant/components/history.py | 19 +-- homeassistant/components/logbook.py | 10 +- homeassistant/components/recorder.py | 75 ++++++++-- homeassistant/components/sun.py | 71 +++++---- homeassistant/helpers/state.py | 4 +- homeassistant/{util.py => util/__init__.py} | 42 ++---- homeassistant/util/dt.py | 99 +++++++++++++ requirements.txt | 1 + scripts/run_tests | 6 +- ...er.py => test_component_device_tracker.py} | 11 +- tests/test_component_sun.py | 25 ++-- tests/test_core.py | 4 +- tests/test_util.py | 11 -- tests/test_util_dt.py | 137 ++++++++++++++++++ 17 files changed, 457 insertions(+), 147 deletions(-) rename homeassistant/{util.py => util/__init__.py} (94%) create mode 100644 homeassistant/util/dt.py rename tests/{test_component_device_scanner.py => test_component_device_tracker.py} (97%) create mode 100644 tests/test_util_dt.py diff --git a/homeassistant/__init__.py b/homeassistant/__init__.py index 5b3e4fd8b9e..7d6a1f03d00 100644 --- a/homeassistant/__init__.py +++ b/homeassistant/__init__.py @@ -12,7 +12,6 @@ import logging import threading import enum import re -import datetime as dt import functools as ft from homeassistant.const import ( @@ -22,6 +21,7 @@ from homeassistant.const import ( EVENT_SERVICE_EXECUTED, ATTR_SERVICE_CALL_ID, EVENT_SERVICE_REGISTERED, TEMP_CELCIUS, TEMP_FAHRENHEIT, ATTR_FRIENDLY_NAME) import homeassistant.util as util +import homeassistant.util.dt as date_util DOMAIN = "homeassistant" @@ -107,7 +107,20 @@ class HomeAssistant(object): def track_point_in_time(self, action, point_in_time): """ - Adds a listener that fires once at or after a spefic point in time. + Adds a listener that fires once after a spefic point in time. + """ + utc_point_in_time = date_util.as_utc(point_in_time) + + @ft.wraps(action) + def utc_converter(utc_now): + """ Converts passed in UTC now to local now. """ + action(date_util.as_local(utc_now)) + + self.track_point_in_utc_time(utc_converter, utc_point_in_time) + + def track_point_in_utc_time(self, action, point_in_time): + """ + Adds a listener that fires once after a specific point in UTC time. """ @ft.wraps(action) @@ -133,11 +146,19 @@ class HomeAssistant(object): self.bus.listen(EVENT_TIME_CHANGED, point_in_time_listener) return point_in_time_listener + # pylint: disable=too-many-arguments + def track_utc_time_change(self, action, + year=None, month=None, day=None, + hour=None, minute=None, second=None): + """ Adds a listener that will fire if time matches a pattern. """ + self.track_time_change( + action, year, month, day, hour, minute, second, utc=True) + # pylint: disable=too-many-arguments def track_time_change(self, action, year=None, month=None, day=None, - hour=None, minute=None, second=None): - """ Adds a listener that will fire if time matches a pattern. """ + hour=None, minute=None, second=None, utc=False): + """ Adds a listener that will fire if UTC time matches a pattern. """ # We do not have to wrap the function with time pattern matching logic # if no pattern given @@ -153,6 +174,9 @@ class HomeAssistant(object): """ Listens for matching time_changed events. """ now = event.data[ATTR_NOW] + if not utc: + now = date_util.as_local(now) + mat = _matcher if mat(now.year, year) and \ @@ -303,7 +327,7 @@ def create_worker_pool(): for start, job in current_jobs: _LOGGER.warning("WorkerPool:Current job from %s: %s", - util.datetime_to_str(start), job) + date_util.datetime_to_local_str(start), job) return util.ThreadPool(job_handler, MIN_WORKER_THREAD, busy_callback) @@ -331,7 +355,7 @@ class Event(object): self.data = data or {} self.origin = origin self.time_fired = util.strip_microseconds( - time_fired or dt.datetime.now()) + time_fired or date_util.utcnow()) def as_dict(self): """ Returns a dict representation of this Event. """ @@ -339,7 +363,7 @@ class Event(object): 'event_type': self.event_type, 'data': dict(self.data), 'origin': str(self.origin), - 'time_fired': util.datetime_to_str(self.time_fired), + 'time_fired': date_util.datetime_to_str(self.time_fired), } def __repr__(self): @@ -472,13 +496,13 @@ class State(object): self.entity_id = entity_id.lower() self.state = state self.attributes = attributes or {} - self.last_updated = last_updated or dt.datetime.now() + self.last_updated = last_updated or date_util.utcnow() # Strip microsecond from last_changed else we cannot guarantee # state == State.from_dict(state.as_dict()) # This behavior occurs because to_dict uses datetime_to_str # which does not preserve microseconds - self.last_changed = util.strip_microseconds( + self.last_changed = date_util.strip_microseconds( last_changed or self.last_updated) @property @@ -510,8 +534,8 @@ class State(object): return {'entity_id': self.entity_id, 'state': self.state, 'attributes': self.attributes, - 'last_changed': util.datetime_to_str(self.last_changed), - 'last_updated': util.datetime_to_str(self.last_updated)} + 'last_changed': date_util.datetime_to_str(self.last_changed), + 'last_updated': date_util.datetime_to_str(self.last_updated)} @classmethod def from_dict(cls, json_dict): @@ -526,12 +550,12 @@ class State(object): last_changed = json_dict.get('last_changed') if last_changed: - last_changed = util.str_to_datetime(last_changed) + last_changed = date_util.str_to_datetime(last_changed) last_updated = json_dict.get('last_updated') if last_updated: - last_updated = util.str_to_datetime(last_updated) + last_updated = date_util.str_to_datetime(last_updated) return cls(json_dict['entity_id'], json_dict['state'], json_dict.get('attributes'), last_changed, last_updated) @@ -548,7 +572,7 @@ class State(object): return "".format( self.entity_id, self.state, attr, - util.datetime_to_str(self.last_changed)) + date_util.datetime_to_local_str(self.last_changed)) class StateMachine(object): @@ -585,7 +609,7 @@ class StateMachine(object): """ Returns all states that have been changed since point_in_time. """ - point_in_time = util.strip_microseconds(point_in_time) + point_in_time = date_util.strip_microseconds(point_in_time) with self._lock: return [state for state in self._states.values() @@ -847,7 +871,7 @@ class Timer(threading.Thread): last_fired_on_second = -1 - calc_now = dt.datetime.now + calc_now = date_util.utcnow interval = self.interval while not self._stop_event.isSet(): diff --git a/homeassistant/bootstrap.py b/homeassistant/bootstrap.py index 4f323f34bea..2544ff5fa79 100644 --- a/homeassistant/bootstrap.py +++ b/homeassistant/bootstrap.py @@ -15,6 +15,7 @@ from collections import defaultdict import homeassistant import homeassistant.util as util +import homeassistant.util.dt as date_util import homeassistant.config as config_util import homeassistant.loader as loader import homeassistant.components as core_components @@ -183,13 +184,27 @@ def process_ha_core_config(hass, config): """ Processes the [homeassistant] section from the config. """ hac = hass.config + def set_time_zone(time_zone_str): + """ Helper method to set time zone in HA. """ + if time_zone_str is None: + return + + time_zone = date_util.get_time_zone(time_zone_str) + + if time_zone: + hac.time_zone = time_zone + date_util.set_default_time_zone(time_zone) + else: + _LOGGER.error("Received invalid time zone %s", time_zone_str) + for key, attr in ((CONF_LATITUDE, 'latitude'), (CONF_LONGITUDE, 'longitude'), - (CONF_NAME, 'location_name'), - (CONF_TIME_ZONE, 'time_zone')): + (CONF_NAME, 'location_name')): if key in config: setattr(hac, attr, config[key]) + set_time_zone(config.get(CONF_TIME_ZONE)) + for entity_id, attrs in config.get(CONF_CUSTOMIZE, {}).items(): Entity.overwrite_attribute(entity_id, attrs.keys(), attrs.values()) @@ -202,7 +217,8 @@ def process_ha_core_config(hass, config): hac.temperature_unit = TEMP_FAHRENHEIT # If we miss some of the needed values, auto detect them - if None not in (hac.latitude, hac.longitude, hac.temperature_unit): + if None not in ( + hac.latitude, hac.longitude, hac.temperature_unit, hac.time_zone): return _LOGGER.info('Auto detecting location and temperature unit') @@ -227,7 +243,7 @@ def process_ha_core_config(hass, config): hac.location_name = info.city if hac.time_zone is None: - hac.time_zone = info.time_zone + set_time_zone(info.time_zone) def _ensure_loader_prepared(hass): diff --git a/homeassistant/components/device_tracker/__init__.py b/homeassistant/components/device_tracker/__init__.py index 6d4db7ad7ed..40dd6e5150e 100644 --- a/homeassistant/components/device_tracker/__init__.py +++ b/homeassistant/components/device_tracker/__init__.py @@ -8,11 +8,12 @@ import logging import threading import os import csv -from datetime import datetime, timedelta +from datetime import timedelta from homeassistant.loader import get_component from homeassistant.helpers import validate_config import homeassistant.util as util +import homeassistant.util.dt as dt_util from homeassistant.const import ( STATE_HOME, STATE_NOT_HOME, ATTR_ENTITY_PICTURE, ATTR_FRIENDLY_NAME, @@ -113,7 +114,7 @@ class DeviceTracker(object): """ Reload known devices file. """ self._read_known_devices_file() - self.update_devices(datetime.now()) + self.update_devices(dt_util.utcnow()) dev_group.update_tracked_entity_ids(self.device_entity_ids) @@ -125,7 +126,7 @@ class DeviceTracker(object): seconds = range(0, 60, seconds) _LOGGER.info("Device tracker interval second=%s", seconds) - hass.track_time_change(update_device_state, second=seconds) + hass.track_utc_time_change(update_device_state, second=seconds) hass.services.register(DOMAIN, SERVICE_DEVICE_TRACKER_RELOAD, @@ -226,7 +227,7 @@ class DeviceTracker(object): self.untracked_devices.clear() with open(known_dev_path) as inp: - default_last_seen = datetime(1990, 1, 1) + default_last_seen = dt_util.utcnow().replace(year=1990) # To track which devices need an entity_id assigned need_entity_id = [] diff --git a/homeassistant/components/history.py b/homeassistant/components/history.py index a288d5471d9..2717cdccd7f 100644 --- a/homeassistant/components/history.py +++ b/homeassistant/components/history.py @@ -5,10 +5,11 @@ homeassistant.components.history Provide pre-made queries on top of the recorder component. """ import re -from datetime import datetime, timedelta +from datetime import timedelta from itertools import groupby from collections import defaultdict +import homeassistant.util.dt as date_util import homeassistant.components.recorder as recorder DOMAIN = 'history' @@ -30,7 +31,7 @@ def last_5_states(entity_id): def state_changes_during_period(start_time, end_time=None, entity_id=None): """ - Return states changes during period start_time - end_time. + Return states changes during UTC period start_time - end_time. """ where = "last_changed=last_updated AND last_changed > ? " data = [start_time] @@ -64,17 +65,17 @@ def state_changes_during_period(start_time, end_time=None, entity_id=None): return result -def get_states(point_in_time, entity_ids=None, run=None): +def get_states(utc_point_in_time, entity_ids=None, run=None): """ Returns the states at a specific point in time. """ if run is None: - run = recorder.run_information(point_in_time) + run = recorder.run_information(utc_point_in_time) - # History did not run before point_in_time + # History did not run before utc_point_in_time if run is None: return [] where = run.where_after_start_run + "AND created < ? " - where_data = [point_in_time] + where_data = [utc_point_in_time] if entity_ids is not None: where += "AND entity_id IN ({}) ".format( @@ -93,9 +94,9 @@ def get_states(point_in_time, entity_ids=None, run=None): return recorder.query_states(query, where_data) -def get_state(point_in_time, entity_id, run=None): +def get_state(utc_point_in_time, entity_id, run=None): """ Return a state at a specific point in time. """ - states = get_states(point_in_time, (entity_id,), run) + states = get_states(utc_point_in_time, (entity_id,), run) return states[0] if states else None @@ -128,7 +129,7 @@ def _api_last_5_states(handler, path_match, data): def _api_history_period(handler, path_match, data): """ Return history over a period of time. """ # 1 day for now.. - start_time = datetime.now() - timedelta(seconds=86400) + start_time = date_util.utcnow() - timedelta(seconds=86400) entity_id = data.get('filter_entity_id') diff --git a/homeassistant/components/logbook.py b/homeassistant/components/logbook.py index a8299fbd6ed..4d1e5ba8e00 100644 --- a/homeassistant/components/logbook.py +++ b/homeassistant/components/logbook.py @@ -4,14 +4,13 @@ homeassistant.components.logbook Parses events and generates a human log """ -from datetime import datetime from itertools import groupby from homeassistant import State, DOMAIN as HA_DOMAIN from homeassistant.const import ( EVENT_STATE_CHANGED, STATE_HOME, STATE_ON, STATE_OFF, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP) -import homeassistant.util as util +import homeassistant.util.dt as dt_util import homeassistant.components.recorder as recorder import homeassistant.components.sun as sun @@ -38,10 +37,11 @@ def setup(hass, config): def _handle_get_logbook(handler, path_match, data): """ Return logbook entries. """ - start_today = datetime.now().date() + start_today = dt_util.now().date() handler.write_json(humanify( - recorder.query_events(QUERY_EVENTS_AFTER, (start_today,)))) + recorder.query_events( + QUERY_EVENTS_AFTER, (dt_util.as_utc(start_today),)))) class Entry(object): @@ -60,7 +60,7 @@ class Entry(object): def as_dict(self): """ Convert Entry to a dict to be used within JSON. """ return { - 'when': util.datetime_to_str(self.when), + 'when': dt_util.datetime_to_str(self.when), 'name': self.name, 'message': self.message, 'domain': self.domain, diff --git a/homeassistant/components/recorder.py b/homeassistant/components/recorder.py index 6856ce4d7b5..ad4d2f3caa4 100644 --- a/homeassistant/components/recorder.py +++ b/homeassistant/components/recorder.py @@ -15,6 +15,7 @@ import json import atexit from homeassistant import Event, EventOrigin, State +import homeassistant.util.dt as date_util from homeassistant.remote import JSONEncoder from homeassistant.const import ( MATCH_ALL, EVENT_TIME_CHANGED, EVENT_STATE_CHANGED, @@ -60,8 +61,9 @@ def row_to_state(row): """ Convert a databsae row to a state. """ try: return State( - row[1], row[2], json.loads(row[3]), datetime.fromtimestamp(row[4]), - datetime.fromtimestamp(row[5])) + row[1], row[2], json.loads(row[3]), + date_util.utc_from_timestamp(row[4]), + date_util.utc_from_timestamp(row[5])) except ValueError: # When json.loads fails _LOGGER.exception("Error converting row to state: %s", row) @@ -72,7 +74,7 @@ def row_to_event(row): """ Convert a databse row to an event. """ try: return Event(row[1], json.loads(row[2]), EventOrigin[row[3].lower()], - datetime.fromtimestamp(row[5])) + date_util.utc_from_timestamp(row[5])) except ValueError: # When json.loads fails _LOGGER.exception("Error converting row to event: %s", row) @@ -113,10 +115,10 @@ class RecorderRun(object): self.start = _INSTANCE.recording_start self.closed_incorrect = False else: - self.start = datetime.fromtimestamp(row[1]) + self.start = date_util.utc_from_timestamp(row[1]) if row[2] is not None: - self.end = datetime.fromtimestamp(row[2]) + self.end = date_util.utc_from_timestamp(row[2]) self.closed_incorrect = bool(row[3]) @@ -166,7 +168,8 @@ class Recorder(threading.Thread): self.queue = queue.Queue() self.quit_object = object() self.lock = threading.Lock() - self.recording_start = datetime.now() + self.recording_start = date_util.utcnow() + self.utc_offset = date_util.now().utcoffset().total_seconds() def start_recording(event): """ Start recording. """ @@ -209,31 +212,33 @@ class Recorder(threading.Thread): def record_state(self, entity_id, state): """ Save a state to the database. """ - now = datetime.now() + now = date_util.utcnow() + # State got deleted if state is None: info = (entity_id, '', "{}", now, now, now) else: info = ( entity_id.lower(), state.state, json.dumps(state.attributes), - state.last_changed, state.last_updated, now) + state.last_changed, state.last_updated, now, self.utc_offset) self.query( "INSERT INTO states (" "entity_id, state, attributes, last_changed, last_updated," - "created) VALUES (?, ?, ?, ?, ?, ?)", info) + "created, utc_offset) VALUES (?, ?, ?, ?, ?, ?, ?)", info) def record_event(self, event): """ Save an event to the database. """ info = ( event.event_type, json.dumps(event.data, cls=JSONEncoder), - str(event.origin), datetime.now(), event.time_fired, + str(event.origin), date_util.utcnow(), event.time_fired, + self.utc_offset ) self.query( "INSERT INTO events (" - "event_type, event_data, origin, created, time_fired" - ") VALUES (?, ?, ?, ?, ?)", info) + "event_type, event_data, origin, created, time_fired, utc_offset" + ") VALUES (?, ?, ?, ?, ?, ?)", info) def query(self, sql_query, data=None, return_value=None): """ Query the database. """ @@ -282,7 +287,7 @@ class Recorder(threading.Thread): def save_migration(migration_id): """ Save and commit a migration to the database. """ cur.execute('INSERT INTO schema_version VALUES (?, ?)', - (migration_id, datetime.now())) + (migration_id, date_util.utcnow())) self.conn.commit() _LOGGER.info("Database migrated to version %d", migration_id) @@ -341,6 +346,44 @@ class Recorder(threading.Thread): save_migration(2) + if migration_id < 3: + utc_offset = self.utc_offset + + cur.execute(""" + ALTER TABLE recorder_runs + ADD COLUMN utc_offset integer + """) + + cur.execute(""" + ALTER TABLE events + ADD COLUMN utc_offset integer + """) + + cur.execute(""" + ALTER TABLE states + ADD COLUMN utc_offset integer + """) + + cur.execute("UPDATE schema_version SET performed=performed+?", + (utc_offset,)) + + cur.execute(""" + UPDATE recorder_runs SET utc_offset=?, + start=start + ?, end=end + ?, created=created + ? + """, [utc_offset]*4) + + cur.execute(""" + UPDATE events SET utc_offset=?, + time_fired=time_fired + ?, created=created + ? + """, [utc_offset]*3) + + cur.execute(""" + UPDATE states SET utc_offset=?, last_changed=last_changed + ?, + last_updated=last_updated + ?, created=created + ? + """, [utc_offset]*4) + + save_migration(3) + def _close_connection(self): """ Close connection to the database. """ _LOGGER.info("Closing database") @@ -357,18 +400,18 @@ class Recorder(threading.Thread): self.query( "INSERT INTO recorder_runs (start, created) VALUES (?, ?)", - (self.recording_start, datetime.now())) + (self.recording_start, date_util.utcnow())) def _close_run(self): """ Save end time for current run. """ self.query( "UPDATE recorder_runs SET end=? WHERE start=?", - (datetime.now(), self.recording_start)) + (date_util.utcnow(), self.recording_start)) def _adapt_datetime(datetimestamp): """ Turn a datetime into an integer for in the DB. """ - return time.mktime(datetimestamp.timetuple()) + return time.mktime(date_util.as_utc(datetimestamp).timetuple()) def _verify_instance(): diff --git a/homeassistant/components/sun.py b/homeassistant/components/sun.py index a7228a1e42f..208d17167c6 100644 --- a/homeassistant/components/sun.py +++ b/homeassistant/components/sun.py @@ -30,7 +30,7 @@ except ImportError: # Error will be raised during setup ephem = None -from homeassistant.util import str_to_datetime, datetime_to_str +import homeassistant.util.dt as dt_util from homeassistant.helpers.entity import Entity from homeassistant.components.scheduler import ServiceEventListener @@ -55,13 +55,21 @@ def is_on(hass, entity_id=None): def next_setting(hass, entity_id=None): - """ Returns the datetime object representing the next sun setting. """ + """ Returns the local datetime object of the next sun setting. """ + utc_next = next_setting_utc(hass, entity_id) + + return dt_util.as_local(utc_next) if utc_next else None + + +def next_setting_utc(hass, entity_id=None): + """ Returns the UTC datetime object of the next sun setting. """ entity_id = entity_id or ENTITY_ID state = hass.states.get(ENTITY_ID) try: - return str_to_datetime(state.attributes[STATE_ATTR_NEXT_SETTING]) + return dt_util.str_to_datetime( + state.attributes[STATE_ATTR_NEXT_SETTING]) except (AttributeError, KeyError): # AttributeError if state is None # KeyError if STATE_ATTR_NEXT_SETTING does not exist @@ -69,13 +77,21 @@ def next_setting(hass, entity_id=None): def next_rising(hass, entity_id=None): - """ Returns the datetime object representing the next sun rising. """ + """ Returns the 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 + + +def next_rising_utc(hass, entity_id=None): + """ Returns the UTC datetime object of the next sun rising. """ entity_id = entity_id or ENTITY_ID state = hass.states.get(ENTITY_ID) try: - return str_to_datetime(state.attributes[STATE_ATTR_NEXT_RISING]) + return dt_util.str_to_datetime( + state.attributes[STATE_ATTR_NEXT_RISING]) except (AttributeError, KeyError): # AttributeError if state is None # KeyError if STATE_ATTR_NEXT_RISING does not exist @@ -94,15 +110,15 @@ def setup(hass, config): logger.error("Latitude or longitude not set in Home Assistant config") return False - sun = Sun(hass, str(hass.config.latitude), str(hass.config.longitude)) - try: - sun.point_in_time_listener(datetime.now()) + sun = Sun(hass, str(hass.config.latitude), str(hass.config.longitude)) except ValueError: # Raised when invalid latitude or longitude is given to Observer logger.exception("Invalid value for latitude or longitude") return False + sun.point_in_time_listener(dt_util.utcnow()) + return True @@ -113,8 +129,11 @@ class Sun(Entity): def __init__(self, hass, latitude, longitude): self.hass = hass - self.latitude = latitude - self.longitude = longitude + self.observer = ephem.Observer() + # pylint: disable=assigning-non-slot + self.observer.lat = latitude + # pylint: disable=assigning-non-slot + self.observer.long = longitude self._state = self.next_rising = self.next_setting = None @@ -137,8 +156,8 @@ class Sun(Entity): @property def state_attributes(self): return { - STATE_ATTR_NEXT_RISING: datetime_to_str(self.next_rising), - STATE_ATTR_NEXT_SETTING: datetime_to_str(self.next_setting) + STATE_ATTR_NEXT_RISING: dt_util.datetime_to_str(self.next_rising), + STATE_ATTR_NEXT_SETTING: dt_util.datetime_to_str(self.next_setting) } @property @@ -146,22 +165,19 @@ class Sun(Entity): """ Returns the datetime when the next change to the state is. """ return min(self.next_rising, self.next_setting) - def update_as_of(self, point_in_time): - """ Calculate sun state at a point in time. """ - utc_offset = datetime.utcnow() - datetime.now() - utc_now = point_in_time + utc_offset - + def update_as_of(self, utc_point_in_time): + """ Calculate sun state at a point in UTC time. """ sun = ephem.Sun() # pylint: disable=no-member - # Setting invalid latitude and longitude to observer raises ValueError - observer = ephem.Observer() - observer.lat = self.latitude # pylint: disable=assigning-non-slot - observer.long = self.longitude # pylint: disable=assigning-non-slot + # pylint: disable=assigning-non-slot + self.observer.date = ephem.date(utc_point_in_time) - self.next_rising = ephem.localtime( - observer.next_rising(sun, start=utc_now)) - self.next_setting = ephem.localtime( - observer.next_setting(sun, start=utc_now)) + self.next_rising = self.observer.next_rising( + sun, + start=utc_point_in_time).datetime().replace(tzinfo=dt_util.UTC) + self.next_setting = self.observer.next_setting( + sun, + start=utc_point_in_time).datetime().replace(tzinfo=dt_util.UTC) def point_in_time_listener(self, now): """ Called when the state of the sun has changed. """ @@ -169,8 +185,9 @@ class Sun(Entity): self.update_ha_state() # Schedule next update at next_change+1 second so sun state has changed - self.hass.track_point_in_time(self.point_in_time_listener, - self.next_change + timedelta(seconds=1)) + self.hass.track_point_in_utc_time( + self.point_in_time_listener, + self.next_change + timedelta(seconds=1)) def create_event_listener(schedule, event_listener_data): diff --git a/homeassistant/helpers/state.py b/homeassistant/helpers/state.py index 43d48898303..18c68808e94 100644 --- a/homeassistant/helpers/state.py +++ b/homeassistant/helpers/state.py @@ -5,9 +5,9 @@ homeassistant.helpers.state Helpers that help with state related things. """ import logging -from datetime import datetime from homeassistant import State +import homeassistant.util.dt as dt_util from homeassistant.const import ( STATE_ON, STATE_OFF, SERVICE_TURN_ON, SERVICE_TURN_OFF, ATTR_ENTITY_ID) @@ -26,7 +26,7 @@ class TrackStates(object): self.states = [] def __enter__(self): - self.now = datetime.now() + self.now = dt_util.utcnow() return self.states def __exit__(self, exc_type, exc_value, traceback): diff --git a/homeassistant/util.py b/homeassistant/util/__init__.py similarity index 94% rename from homeassistant/util.py rename to homeassistant/util/__init__.py index e50ac3f30cf..5c69fd02243 100644 --- a/homeassistant/util.py +++ b/homeassistant/util/__init__.py @@ -8,7 +8,7 @@ import collections from itertools import chain import threading import queue -from datetime import datetime, timedelta +from datetime import datetime import re import enum import socket @@ -18,12 +18,17 @@ from functools import wraps import requests +# DEPRECATED AS OF 4/27/2015 - moved to homeassistant.util.dt package +# pylint: disable=unused-import +from .dt import ( # noqa + datetime_to_str, str_to_datetime, strip_microseconds, + datetime_to_local_str, utcnow) + + RE_SANITIZE_FILENAME = re.compile(r'(~|\.\.|/|\\)') RE_SANITIZE_PATH = re.compile(r'(~|\.(\.)+)') RE_SLUGIFY = re.compile(r'[^A-Za-z0-9_]+') -DATE_STR_FORMAT = "%H:%M:%S %d-%m-%Y" - def sanitize_filename(filename): """ Sanitizes a filename by removing .. / and \\. """ @@ -42,33 +47,6 @@ def slugify(text): return RE_SLUGIFY.sub("", text) -def datetime_to_str(dattim): - """ Converts datetime to a string format. - - @rtype : str - """ - return dattim.strftime(DATE_STR_FORMAT) - - -def str_to_datetime(dt_str): - """ Converts a string to a datetime object. - - @rtype: datetime - """ - try: - return datetime.strptime(dt_str, DATE_STR_FORMAT) - except ValueError: # If dt_str did not match our format - return None - - -def strip_microseconds(dattim): - """ Returns a copy of dattime object but with microsecond set to 0. """ - if dattim.microsecond: - return dattim - timedelta(microseconds=dattim.microsecond) - else: - return dattim - - def split_entity_id(entity_id): """ Splits a state entity_id into domain, object_id. """ return entity_id.split(".", 1) @@ -81,7 +59,7 @@ def repr_helper(inp): repr_helper(key)+"="+repr_helper(item) for key, item in inp.items()) elif isinstance(inp, datetime): - return datetime_to_str(inp) + return datetime_to_local_str(inp) else: return str(inp) @@ -464,7 +442,7 @@ class ThreadPool(object): return # Add to current running jobs - job_log = (datetime.now(), job) + job_log = (utcnow(), job) self.current_jobs.append(job_log) # Do the job diff --git a/homeassistant/util/dt.py b/homeassistant/util/dt.py new file mode 100644 index 00000000000..c0e695bbb0c --- /dev/null +++ b/homeassistant/util/dt.py @@ -0,0 +1,99 @@ +""" +homeassistant.util.dt +~~~~~~~~~~~~~~~~~~~~~ + +Provides helper methods to handle the time in HA. + +""" +import datetime as dt + +import pytz + +DATE_STR_FORMAT = "%H:%M:%S %d-%m-%Y" +UTC = DEFAULT_TIME_ZONE = pytz.utc + + +def set_default_time_zone(time_zone): + """ Sets a default time zone to be used when none is specified. """ + global DEFAULT_TIME_ZONE # pylint: disable=global-statement + + assert isinstance(time_zone, dt.tzinfo) + + DEFAULT_TIME_ZONE = time_zone + + +def get_time_zone(time_zone_str): + """ Get time zone from string. Return None if unable to determine. """ + try: + return pytz.timezone(time_zone_str) + except pytz.exceptions.UnknownTimeZoneError: + return None + + +def utcnow(): + """ Get now in UTC time. """ + return dt.datetime.utcnow().replace(tzinfo=pytz.utc) + + +def now(time_zone=None): + """ Get now in specified time zone. """ + if time_zone is None: + time_zone = DEFAULT_TIME_ZONE + + return utcnow().astimezone(time_zone) + + +def as_utc(dattim): + """ Return a datetime as UTC time. + Assumes datetime without tzinfo to be in the DEFAULT_TIME_ZONE. """ + if dattim.tzinfo == pytz.utc: + return dattim + elif dattim.tzinfo is None: + dattim = dattim.replace(tzinfo=DEFAULT_TIME_ZONE) + + return dattim.astimezone(pytz.utc) + + +def as_local(dattim): + """ Converts a UTC datetime object to local time_zone. """ + if dattim.tzinfo == DEFAULT_TIME_ZONE: + return dattim + elif dattim.tzinfo is None: + dattim = dattim.replace(tzinfo=pytz.utc) + + return dattim.astimezone(DEFAULT_TIME_ZONE) + + +def utc_from_timestamp(timestamp): + """ Returns a UTC time from a timestamp. """ + return dt.datetime.fromtimestamp(timestamp, pytz.utc) + + +def datetime_to_local_str(dattim, time_zone=None): + """ Converts datetime to specified time_zone and returns a string. """ + return datetime_to_str(as_local(dattim)) + + +def datetime_to_str(dattim): + """ Converts datetime to a string format. + + @rtype : str + """ + return dattim.strftime(DATE_STR_FORMAT) + + +def str_to_datetime(dt_str): + """ Converts a string to a UTC datetime object. + + @rtype: datetime + """ + try: + return dt.datetime.strptime( + dt_str, DATE_STR_FORMAT).replace(tzinfo=pytz.utc) + except ValueError: # If dt_str did not match our format + return None + + +def strip_microseconds(dattim): + """ Returns a copy of dattime object but with microsecond set to 0. """ + return dattim.replace(microsecond=0) diff --git a/requirements.txt b/requirements.txt index e1b0a942f80..59a1c3ea39a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,7 @@ # required for Home Assistant core requests>=2.0 pyyaml>=3.11 +pytz>=2015.2 # optional, needed for specific components diff --git a/scripts/run_tests b/scripts/run_tests index 8d1c6aed114..75b25ca805a 100755 --- a/scripts/run_tests +++ b/scripts/run_tests @@ -3,4 +3,8 @@ if [ ${PWD##*/} == "scripts" ]; then cd .. fi -python3 -m unittest discover tests +if [ "$1" = "coverage" ]; then + coverage run -m unittest discover tests +else + python3 -m unittest discover tests +fi diff --git a/tests/test_component_device_scanner.py b/tests/test_component_device_tracker.py similarity index 97% rename from tests/test_component_device_scanner.py rename to tests/test_component_device_tracker.py index 2bd392c21d0..74af55fdc66 100644 --- a/tests/test_component_device_scanner.py +++ b/tests/test_component_device_tracker.py @@ -1,17 +1,18 @@ """ -tests.test_component_group -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +tests.test_component_device_tracker +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Tests the group compoments. +Tests the device tracker compoments. """ # pylint: disable=protected-access,too-many-public-methods import unittest -from datetime import datetime, timedelta +from datetime import timedelta import logging import os import homeassistant as ha import homeassistant.loader as loader +import homeassistant.util.dt as dt_util from homeassistant.const import ( STATE_HOME, STATE_NOT_HOME, ATTR_ENTITY_PICTURE, CONF_PLATFORM) import homeassistant.components.device_tracker as device_tracker @@ -116,7 +117,7 @@ class TestComponentsDeviceTracker(unittest.TestCase): dev2 = device_tracker.ENTITY_ID_FORMAT.format('device_2') dev3 = device_tracker.ENTITY_ID_FORMAT.format('DEV3') - now = datetime.now() + now = dt_util.utcnow() # Device scanner scans every 12 seconds. We need to sync our times to # be every 12 seconds or else the time_changed event will be ignored. diff --git a/tests/test_component_sun.py b/tests/test_component_sun.py index a4ff19429f3..aec97ede6a8 100644 --- a/tests/test_component_sun.py +++ b/tests/test_component_sun.py @@ -6,11 +6,12 @@ Tests Sun component. """ # pylint: disable=too-many-public-methods,protected-access import unittest -import datetime as dt +from datetime import timedelta import ephem import homeassistant as ha +import homeassistant.util.dt as dt_util import homeassistant.components.sun as sun @@ -42,22 +43,20 @@ class TestSun(unittest.TestCase): observer.lat = '32.87336' # pylint: disable=assigning-non-slot observer.long = '117.22743' # pylint: disable=assigning-non-slot - utc_now = dt.datetime.utcnow() + utc_now = dt_util.utcnow() body_sun = ephem.Sun() # pylint: disable=no-member - next_rising_dt = ephem.localtime( - observer.next_rising(body_sun, start=utc_now)) - next_setting_dt = ephem.localtime( - observer.next_setting(body_sun, start=utc_now)) + next_rising_dt = observer.next_rising( + body_sun, start=utc_now).datetime().replace(tzinfo=dt_util.UTC) + next_setting_dt = observer.next_setting( + body_sun, start=utc_now).datetime().replace(tzinfo=dt_util.UTC) # Home Assistant strips out microseconds # strip it out of the datetime objects - next_rising_dt = next_rising_dt - dt.timedelta( - microseconds=next_rising_dt.microsecond) - next_setting_dt = next_setting_dt - dt.timedelta( - microseconds=next_setting_dt.microsecond) + next_rising_dt = dt_util.strip_microseconds(next_rising_dt) + next_setting_dt = dt_util.strip_microseconds(next_setting_dt) - self.assertEqual(next_rising_dt, sun.next_rising(self.hass)) - self.assertEqual(next_setting_dt, sun.next_setting(self.hass)) + self.assertEqual(next_rising_dt, sun.next_rising_utc(self.hass)) + self.assertEqual(next_setting_dt, sun.next_setting_utc(self.hass)) # Point it at a state without the proper attributes self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON) @@ -84,7 +83,7 @@ class TestSun(unittest.TestCase): self.assertIsNotNone(test_time) self.hass.bus.fire(ha.EVENT_TIME_CHANGED, - {ha.ATTR_NOW: test_time + dt.timedelta(seconds=5)}) + {ha.ATTR_NOW: test_time + timedelta(seconds=5)}) self.hass.pool.block_till_done() diff --git a/tests/test_core.py b/tests/test_core.py index a5c37f753b9..b450479f2d9 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -72,7 +72,7 @@ class TestHomeAssistant(unittest.TestCase): runs = [] - self.hass.track_point_in_time( + self.hass.track_point_in_utc_time( lambda x: runs.append(1), birthday_paulus) self._send_time_changed(before_birthday) @@ -88,7 +88,7 @@ class TestHomeAssistant(unittest.TestCase): self.hass.pool.block_till_done() self.assertEqual(1, len(runs)) - self.hass.track_point_in_time( + self.hass.track_point_in_utc_time( lambda x: runs.append(1), birthday_paulus) self._send_time_changed(after_birthday) diff --git a/tests/test_util.py b/tests/test_util.py index 038db227e1a..f75b6db8aeb 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -35,17 +35,6 @@ class TestUtil(unittest.TestCase): self.assertEqual("Test_More", util.slugify("Test More")) self.assertEqual("Test_More", util.slugify("Test_(More)")) - def test_datetime_to_str(self): - """ Test datetime_to_str. """ - self.assertEqual("12:00:00 09-07-1986", - util.datetime_to_str(datetime(1986, 7, 9, 12, 0, 0))) - - def test_str_to_datetime(self): - """ Test str_to_datetime. """ - self.assertEqual(datetime(1986, 7, 9, 12, 0, 0), - util.str_to_datetime("12:00:00 09-07-1986")) - self.assertIsNone(util.str_to_datetime("not a datetime string")) - def test_split_entity_id(self): """ Test split_entity_id. """ self.assertEqual(['domain', 'object_id'], diff --git a/tests/test_util_dt.py b/tests/test_util_dt.py new file mode 100644 index 00000000000..5deafb58040 --- /dev/null +++ b/tests/test_util_dt.py @@ -0,0 +1,137 @@ +""" +tests.test_util +~~~~~~~~~~~~~~~~~ + +Tests Home Assistant date util methods. +""" +# pylint: disable=too-many-public-methods +import unittest +from datetime import datetime, timedelta + +import homeassistant.util.dt as dt_util + +TEST_TIME_ZONE = 'America/Los_Angeles' + + +class TestDateUtil(unittest.TestCase): + """ Tests util date methods. """ + + def setUp(self): + self.orig_default_time_zone = dt_util.DEFAULT_TIME_ZONE + + def tearDown(self): + dt_util.set_default_time_zone(self.orig_default_time_zone) + + def test_get_time_zone_retrieves_valid_time_zone(self): + """ Test getting a time zone. """ + time_zone = dt_util.get_time_zone(TEST_TIME_ZONE) + + self.assertIsNotNone(time_zone) + self.assertEqual(TEST_TIME_ZONE, time_zone.zone) + + def test_get_time_zone_returns_none_for_garbage_time_zone(self): + """ Test getting a non existing time zone. """ + time_zone = dt_util.get_time_zone("Non existing time zone") + + self.assertIsNone(time_zone) + + def test_set_default_time_zone(self): + """ Test setting default time zone. """ + time_zone = dt_util.get_time_zone(TEST_TIME_ZONE) + + dt_util.set_default_time_zone(time_zone) + + # We cannot compare the timezones directly because of DST + self.assertEqual(time_zone.zone, dt_util.now().tzinfo.zone) + + def test_utcnow(self): + """ Test the UTC now method. """ + self.assertAlmostEqual( + dt_util.utcnow().replace(tzinfo=None), + datetime.utcnow(), + delta=timedelta(seconds=1)) + + def test_now(self): + """ Test the now method. """ + dt_util.set_default_time_zone(dt_util.get_time_zone(TEST_TIME_ZONE)) + + self.assertAlmostEqual( + dt_util.as_utc(dt_util.now()).replace(tzinfo=None), + datetime.utcnow(), + delta=timedelta(seconds=1)) + + def test_as_utc_with_naive_object(self): + utcnow = datetime.utcnow() + + self.assertEqual(utcnow, + dt_util.as_utc(utcnow).replace(tzinfo=None)) + + def test_as_utc_with_utc_object(self): + utcnow = dt_util.utcnow() + + self.assertEqual(utcnow, dt_util.as_utc(utcnow)) + + def test_as_utc_with_local_object(self): + dt_util.set_default_time_zone(dt_util.get_time_zone(TEST_TIME_ZONE)) + + localnow = dt_util.now() + + utcnow = dt_util.as_utc(localnow) + + self.assertEqual(localnow, utcnow) + self.assertNotEqual(localnow.tzinfo, utcnow.tzinfo) + + def test_as_local_with_naive_object(self): + now = dt_util.now() + + self.assertAlmostEqual( + now, dt_util.as_local(datetime.utcnow()), + delta=timedelta(seconds=1)) + + def test_as_local_with_local_object(self): + now = dt_util.now() + + self.assertEqual(now, now) + + def test_as_local_with_utc_object(self): + 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) + + def test_utc_from_timestamp(self): + """ Test utc_from_timestamp method. """ + self.assertEqual( + datetime(1986, 7, 9, tzinfo=dt_util.UTC), + dt_util.utc_from_timestamp(521251200)) + + def test_datetime_to_str(self): + """ Test datetime_to_str. """ + self.assertEqual( + "12:00:00 09-07-1986", + dt_util.datetime_to_str(datetime(1986, 7, 9, 12, 0, 0))) + + def test_datetime_to_local_str(self): + """ Test datetime_to_local_str. """ + self.assertEqual( + dt_util.datetime_to_str(dt_util.now()), + dt_util.datetime_to_local_str(dt_util.utcnow())) + + def test_str_to_datetime_converts_correctly(self): + """ Test str_to_datetime converts strings. """ + self.assertEqual( + datetime(1986, 7, 9, 12, 0, 0, tzinfo=dt_util.UTC), + dt_util.str_to_datetime("12:00:00 09-07-1986")) + + def test_str_to_datetime_returns_none_for_incorrect_format(self): + """ Test str_to_datetime returns None if incorrect format. """ + self.assertIsNone(dt_util.str_to_datetime("not a datetime string")) + + def test_strip_microseconds(self): + test_time = datetime(2015, 1, 1, microsecond=5000) + + self.assertNotEqual(0, test_time.microsecond) + self.assertEqual(0, dt_util.strip_microseconds(test_time).microsecond) From 54904a163084f81e7e068ec97e731f2e5b7a1fa1 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Tue, 28 Apr 2015 22:34:44 -0700 Subject: [PATCH 02/11] Make frontend UTC aware --- homeassistant/components/frontend/version.py | 2 +- .../frontend/www_static/frontend.html | 12 ++++++------ .../polymer/components/display-time.html | 9 +++++---- .../components/relative-ha-datetime.html | 11 +++++++++-- .../polymer/components/state-info.html | 4 ++-- .../www_static/polymer/home-assistant-js | 2 +- .../polymer/resources/home-assistant-js.html | 14 ++------------ .../polymer/resources/moment-js.html | 19 +++++++++++++++++++ 8 files changed, 45 insertions(+), 28 deletions(-) diff --git a/homeassistant/components/frontend/version.py b/homeassistant/components/frontend/version.py index bf7aed7c7fd..9c13c6d75a2 100644 --- a/homeassistant/components/frontend/version.py +++ b/homeassistant/components/frontend/version.py @@ -1,2 +1,2 @@ """ DO NOT MODIFY. Auto-generated by build_frontend script """ -VERSION = "93774c7a1643c7e3f9cbbb1554b36683" +VERSION = "37514744ac03f1d764a70b8e6a7e572f" diff --git a/homeassistant/components/frontend/www_static/frontend.html b/homeassistant/components/frontend/www_static/frontend.html index 5995df6e07d..3835c812b98 100644 --- a/homeassistant/components/frontend/www_static/frontend.html +++ b/homeassistant/components/frontend/www_static/frontend.html @@ -11,11 +11,11 @@ window.PolymerGestures={},function(a){var b=!1,c=document.createElement("meta"); LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",ObjectExpression:"ObjectExpression",Program:"Program",Property:"Property",ThisExpression:"ThisExpression",UnaryExpression:"UnaryExpression"},V={UnexpectedToken:"Unexpected token %0",UnknownLabel:"Undefined label '%0'",Redeclaration:"%0 '%1' has already been declared"};var ab=H,bb=L;a.esprima={parse:R}}(this),function(a){"use strict";function b(a,b,d,e){var f;try{if(f=c(a),f.scopeIdent&&(d.nodeType!==Node.ELEMENT_NODE||"TEMPLATE"!==d.tagName||"bind"!==b&&"repeat"!==b))throw Error("as and in can only be used within + + diff --git a/homeassistant/components/frontend/www_static/polymer/resources/moment-js.html b/homeassistant/components/frontend/www_static/polymer/resources/moment-js.html index 70e14e72d7f..14742dd2d2d 100644 --- a/homeassistant/components/frontend/www_static/polymer/resources/moment-js.html +++ b/homeassistant/components/frontend/www_static/polymer/resources/moment-js.html @@ -3,3 +3,22 @@ --> + + From 372033392732d32256c3bc4a7aa192708493998d Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Tue, 28 Apr 2015 22:38:43 -0700 Subject: [PATCH 03/11] UTC bugfixes --- homeassistant/components/logbook.py | 2 +- homeassistant/components/recorder.py | 43 +++++++++------------------- homeassistant/util/dt.py | 9 ++---- 3 files changed, 18 insertions(+), 36 deletions(-) diff --git a/homeassistant/components/logbook.py b/homeassistant/components/logbook.py index 4d1e5ba8e00..68718a7ac43 100644 --- a/homeassistant/components/logbook.py +++ b/homeassistant/components/logbook.py @@ -37,7 +37,7 @@ def setup(hass, config): def _handle_get_logbook(handler, path_match, data): """ Return logbook entries. """ - start_today = dt_util.now().date() + start_today = dt_util.now().replace(hour=0, minute=0, second=0) handler.write_json(humanify( recorder.query_events( diff --git a/homeassistant/components/recorder.py b/homeassistant/components/recorder.py index ad4d2f3caa4..4f0a76cf18a 100644 --- a/homeassistant/components/recorder.py +++ b/homeassistant/components/recorder.py @@ -10,7 +10,6 @@ import threading import queue import sqlite3 from datetime import datetime, date -import time import json import atexit @@ -302,7 +301,7 @@ class Recorder(threading.Thread): migration_id = 0 if migration_id < 1: - cur.execute(""" + self.query(""" CREATE TABLE recorder_runs ( run_id integer primary key, start integer, @@ -311,7 +310,7 @@ class Recorder(threading.Thread): created integer) """) - cur.execute(""" + self.query(""" CREATE TABLE events ( event_id integer primary key, event_type text, @@ -319,10 +318,10 @@ class Recorder(threading.Thread): origin text, created integer) """) - cur.execute( + self.query( 'CREATE INDEX events__event_type ON events(event_type)') - cur.execute(""" + self.query(""" CREATE TABLE states ( state_id integer primary key, entity_id text, @@ -332,55 +331,41 @@ class Recorder(threading.Thread): last_updated integer, created integer) """) - cur.execute('CREATE INDEX states__entity_id ON states(entity_id)') + self.query('CREATE INDEX states__entity_id ON states(entity_id)') save_migration(1) if migration_id < 2: - cur.execute(""" + self.query(""" ALTER TABLE events ADD COLUMN time_fired integer """) - cur.execute('UPDATE events SET time_fired=created') + self.query('UPDATE events SET time_fired=created') save_migration(2) if migration_id < 3: utc_offset = self.utc_offset - cur.execute(""" + self.query(""" ALTER TABLE recorder_runs ADD COLUMN utc_offset integer """) - cur.execute(""" + self.query(""" ALTER TABLE events ADD COLUMN utc_offset integer """) - cur.execute(""" + self.query(""" ALTER TABLE states ADD COLUMN utc_offset integer """) - cur.execute("UPDATE schema_version SET performed=performed+?", - (utc_offset,)) - - cur.execute(""" - UPDATE recorder_runs SET utc_offset=?, - start=start + ?, end=end + ?, created=created + ? - """, [utc_offset]*4) - - cur.execute(""" - UPDATE events SET utc_offset=?, - time_fired=time_fired + ?, created=created + ? - """, [utc_offset]*3) - - cur.execute(""" - UPDATE states SET utc_offset=?, last_changed=last_changed + ?, - last_updated=last_updated + ?, created=created + ? - """, [utc_offset]*4) + self.query("UPDATE recorder_runs SET utc_offset=?", [utc_offset]) + self.query("UPDATE events SET utc_offset=?", [utc_offset]) + self.query("UPDATE states SET utc_offset=?", [utc_offset]) save_migration(3) @@ -411,7 +396,7 @@ class Recorder(threading.Thread): def _adapt_datetime(datetimestamp): """ Turn a datetime into an integer for in the DB. """ - return time.mktime(date_util.as_utc(datetimestamp).timetuple()) + return date_util.as_utc(datetimestamp.replace(microsecond=0)).timestamp() def _verify_instance(): diff --git a/homeassistant/util/dt.py b/homeassistant/util/dt.py index c0e695bbb0c..2439f77c558 100644 --- a/homeassistant/util/dt.py +++ b/homeassistant/util/dt.py @@ -32,15 +32,12 @@ def get_time_zone(time_zone_str): def utcnow(): """ Get now in UTC time. """ - return dt.datetime.utcnow().replace(tzinfo=pytz.utc) + return dt.datetime.now(pytz.utc) def now(time_zone=None): """ Get now in specified time zone. """ - if time_zone is None: - time_zone = DEFAULT_TIME_ZONE - - return utcnow().astimezone(time_zone) + return dt.datetime.now(time_zone or DEFAULT_TIME_ZONE) def as_utc(dattim): @@ -66,7 +63,7 @@ def as_local(dattim): def utc_from_timestamp(timestamp): """ Returns a UTC time from a timestamp. """ - return dt.datetime.fromtimestamp(timestamp, pytz.utc) + return dt.datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.utc) def datetime_to_local_str(dattim, time_zone=None): From 10a5db7924d3c7bdc8bee451a9d503d0b5144567 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Tue, 28 Apr 2015 23:50:53 -0700 Subject: [PATCH 04/11] UTC bugfix for more-info-sun --- homeassistant/components/frontend/version.py | 2 +- .../frontend/www_static/frontend.html | 2 +- .../polymer/more-infos/more-info-sun.html | 21 ++++++++++++------- 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/homeassistant/components/frontend/version.py b/homeassistant/components/frontend/version.py index 9c13c6d75a2..30b4dbae681 100644 --- a/homeassistant/components/frontend/version.py +++ b/homeassistant/components/frontend/version.py @@ -1,2 +1,2 @@ """ DO NOT MODIFY. Auto-generated by build_frontend script """ -VERSION = "37514744ac03f1d764a70b8e6a7e572f" +VERSION = "fdfcc1c10ff8713976c482931769a8e6" diff --git a/homeassistant/components/frontend/www_static/frontend.html b/homeassistant/components/frontend/www_static/frontend.html index 3835c812b98..f9812693475 100644 --- a/homeassistant/components/frontend/www_static/frontend.html +++ b/homeassistant/components/frontend/www_static/frontend.html @@ -18,4 +18,4 @@ for(var n=-1,r=t.length,i=-1,o=[];++n>>1,Ou=au?au.BYTES_PER_ELEMENT:0,Iu=Co.pow(2,53)-1,Su=uu&&new uu,Au={},Nu=e.support={};!function(t){var e=function(){this.x=t},n=[];e.prototype={valueOf:t,y:t};for(var r in new e)n.push(r);Nu.funcDecomp=/\bthis\b/.test(function(){return this}),Nu.funcNames="string"==typeof ko.name;try{Nu.dom=11===qo.createDocumentFragment().nodeType}catch(i){Nu.dom=!1}try{Nu.nonEnumArgs=!eu.call(arguments,1)}catch(i){Nu.nonEnumArgs=!0}}(1,0),e.templateSettings={escape:Et,evaluate:Ot,interpolate:It,variable:"",imports:{_:e}};var ku=su||function(t,e){return null==e?t:ge(e,Uu(e),ge(e,ja(e),t))},Cu=function(){function e(){}return function(n){if(Ti(n)){e.prototype=n;var r=new e;e.prototype=null}return r||t.Object()}}(),Du=fn(ke),xu=fn(Ce,!0),Mu=ln(),Ru=ln(!0),ju=Su?function(t,e){return Su.set(t,e),t}:ho;Fo||(on=Ho&&ou?function(t){var e=t.byteLength,n=au?Yo(e/Ou):0,r=n*Ou,i=new Ho(e);if(n){var o=new au(i,0,n);o.set(new au(t,0,n))}return e!=r&&(o=new ou(i,r),o.set(new ou(t,r))),i}:lo(null));var Lu=fu&&nu?function(t){return new Xt(t)}:lo(null),zu=Su?function(t){return Su.get(t)}:go,Pu=function(){return Nu.funcNames?"constant"==lo.name?We("name"):function(t){for(var e=t.name,n=Au[e],r=n?n.length:0;r--;){var i=n[r],o=i.func;if(null==o||o==t)return i.name}return e}:lo("")}(),qu=We("length"),Uu=Xo?function(t){return Xo(nr(t))}:lo([]),Wu=function(){var t=0,e=0;return function(n,r){var i=fa(),o=W-(i-e);if(e=i,o>0){if(++t>=U)return n}else t=0;return ju(n,r)}}(),Vu=si(function(t,e){return Ea(t)||_i(t)?be(t,Ae(e,!1,!0)):[]}),Gu=gn(),Ku=gn(!0),$u=si(function(t,e){t||(t=[]),e=Ae(e);var n=ye(t,e);return Ge(t,e.sort(o)),n}),Hu=Cn(),Fu=Cn(!0),Bu=si(function(t){return Xe(Ae(t,!1,!0))}),Ju=si(function(t,e){return Ea(t)||_i(t)?be(t,e):[]}),Yu=si(kr),Xu=si(function(t,e){var n=t?qu(t):0;return Fn(n)&&(t=er(t)),ye(t,Ae(e))}),Zu=sn(function(t,e,n){Wo.call(t,n)?++t[n]:t[n]=1}),Qu=yn(Du),ta=yn(xu,!0),ea=Tn(ee,Du),na=Tn(ne,xu),ra=sn(function(t,e,n){Wo.call(t,n)?t[n].push(e):t[n]=[e]}),ia=sn(function(t,e,n){t[n]=e}),oa=si(function(t,e,n){var r=-1,i="function"==typeof e,o=$n(e),u=qu(t),a=Fn(u)?So(u):[];return Du(t,function(t){var u=i?e:o&&null!=t&&t[e];a[++r]=u?u.apply(t,n):Vn(t,e,n)}),a}),ua=sn(function(t,e,n){t[n?0:1].push(e)},function(){return[[],[]]}),aa=Sn(fe,Du),sa=Sn(le,xu),ca=si(function(t,e){if(null==t)return[];var n=e[2];return n&&Kn(e[0],e[1],n)&&(e.length=1),Je(t,Ae(e),[])}),fa=vu||function(){return(new Ao).getTime()},la=si(function(t,e,n){var r=k;if(n.length){var i=T(n,la.placeholder);r|=R}return Dn(t,r,e,n,i)}),ha=si(function(t,e){e=e.length?Ae(e):Ri(t);for(var n=-1,r=e.length;++nt?this.takeRight(-t):this.drop(t);return e!==A&&(e=+e||0,n=0>e?n.dropRight(-e):n.take(e-t)),n},i.prototype.toArray=function(){return this.drop(0)},ke(i.prototype,function(t,n){var o=e[n];if(o){var u=/^(?:filter|map|reject)|While$/.test(n),a=/^(?:first|last)$/.test(n);e.prototype[n]=function(){var n=arguments,s=(n.length,this.__chain__),c=this.__wrapped__,f=!!this.__actions__.length,l=c instanceof i,h=n[0],p=l||Ea(c);p&&u&&"function"==typeof h&&1!=h.length&&(l=p=!1);var _=l&&!f;if(a&&!s)return _?t.call(c):o.call(e,this.value());var v=function(t){var r=[t];return Qo.apply(r,n),o.apply(e,r)};if(p){var d=_?c:new i(this),y=t.apply(d,n);if(!a&&(f||y.__actions__)){var g=y.__actions__||(y.__actions__=[]);g.push({func:Rr,args:[v],thisArg:e})}return new r(y,s)}return this.thru(v)}}}),ee(["concat","join","pop","push","replace","shift","sort","splice","split","unshift"],function(t){var n=(/^(?:replace|split)$/.test(t)?Po:Lo)[t],r=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",i=/^(?:join|pop|replace|shift)$/.test(t);e.prototype[t]=function(){var t=arguments;return i&&!this.__chain__?n.apply(this.value(),t):this[r](function(e){return n.apply(e,t)})}}),ke(i.prototype,function(t,n){var r=e[n];if(r){var i=r.name,o=Au[i]||(Au[i]=[]);o.push({name:n,func:r})}}),Au[An(null,C).name]=[{name:"wrapper",func:null}],i.prototype.clone=w,i.prototype.reverse=Q,i.prototype.value=rt,e.prototype.chain=jr,e.prototype.commit=Lr,e.prototype.plant=zr,e.prototype.reverse=Pr,e.prototype.toString=qr,e.prototype.run=e.prototype.toJSON=e.prototype.valueOf=e.prototype.value=Ur,e.prototype.collect=e.prototype.map,e.prototype.head=e.prototype.first,e.prototype.select=e.prototype.filter,e.prototype.tail=e.prototype.rest,e}var A,N="3.7.0",k=1,C=2,D=4,x=8,M=16,R=32,j=64,L=128,z=256,P=30,q="...",U=150,W=16,V=0,G=1,K=2,$="Expected a function",H="__lodash_placeholder__",F="[object Arguments]",B="[object Array]",J="[object Boolean]",Y="[object Date]",X="[object Error]",Z="[object Function]",Q="[object Map]",tt="[object Number]",et="[object Object]",nt="[object RegExp]",rt="[object Set]",it="[object String]",ot="[object WeakMap]",ut="[object ArrayBuffer]",at="[object Float32Array]",st="[object Float64Array]",ct="[object Int8Array]",ft="[object Int16Array]",lt="[object Int32Array]",ht="[object Uint8Array]",pt="[object Uint8ClampedArray]",_t="[object Uint16Array]",vt="[object Uint32Array]",dt=/\b__p \+= '';/g,yt=/\b(__p \+=) '' \+/g,gt=/(__e\(.*?\)|\b__t\)) \+\n'';/g,mt=/&(?:amp|lt|gt|quot|#39|#96);/g,wt=/[&<>"'`]/g,Tt=RegExp(mt.source),bt=RegExp(wt.source),Et=/<%-([\s\S]+?)%>/g,Ot=/<%([\s\S]+?)%>/g,It=/<%=([\s\S]+?)%>/g,St=/\.|\[(?:[^[\]]+|(["'])(?:(?!\1)[^\n\\]|\\.)*?)\1\]/,At=/^\w*$/,Nt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g,kt=/[.*+?^${}()|[\]\/\\]/g,Ct=RegExp(kt.source),Dt=/[\u0300-\u036f\ufe20-\ufe23]/g,xt=/\\(\\)?/g,Mt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Rt=/\w*$/,jt=/^0[xX]/,Lt=/^\[object .+?Constructor\]$/,zt=/[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g,Pt=/($^)/,qt=/['\n\r\u2028\u2029\\]/g,Ut=function(){var t="[A-Z\\xc0-\\xd6\\xd8-\\xde]",e="[a-z\\xdf-\\xf6\\xf8-\\xff]+";return RegExp(t+"+(?="+t+e+")|"+t+"?"+e+"|"+t+"+|[0-9]+","g")}(),Wt=" \f \ufeff\n\r\u2028\u2029 ᠎              ",Vt=["Array","ArrayBuffer","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Math","Number","Object","RegExp","Set","String","_","clearTimeout","document","isFinite","parseInt","setTimeout","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","window"],Gt=-1,Kt={};Kt[at]=Kt[st]=Kt[ct]=Kt[ft]=Kt[lt]=Kt[ht]=Kt[pt]=Kt[_t]=Kt[vt]=!0,Kt[F]=Kt[B]=Kt[ut]=Kt[J]=Kt[Y]=Kt[X]=Kt[Z]=Kt[Q]=Kt[tt]=Kt[et]=Kt[nt]=Kt[rt]=Kt[it]=Kt[ot]=!1;var $t={};$t[F]=$t[B]=$t[ut]=$t[J]=$t[Y]=$t[at]=$t[st]=$t[ct]=$t[ft]=$t[lt]=$t[tt]=$t[et]=$t[nt]=$t[it]=$t[ht]=$t[pt]=$t[_t]=$t[vt]=!0,$t[X]=$t[Z]=$t[Q]=$t[rt]=$t[ot]=!1;var Ht={leading:!1,maxWait:0,trailing:!1},Ft={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss"},Bt={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},Jt={"&":"&","<":"<",">":">",""":'"',"'":"'","`":"`"},Yt={"function":!0,object:!0},Xt={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Zt=Yt[typeof e]&&e&&!e.nodeType&&e,Qt=Yt[typeof t]&&t&&!t.nodeType&&t,te=Zt&&Qt&&"object"==typeof i&&i&&i.Object&&i,ee=Yt[typeof self]&&self&&self.Object&&self,ne=Yt[typeof window]&&window&&window.Object&&window,re=(Qt&&Qt.exports===Zt&&Zt,te||ne!==(this&&this.window)&&ne||ee||this),ie=S();re._=ie,r=function(){return ie}.call(e,n,e,t),!(r!==A&&(t.exports=r))}).call(this)}).call(e,n(38)(t),function(){return this}())},function(t,e,n){"use strict";var r=function(t){return t&&t.__esModule?t:{"default":t}},i=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},o=function(){function t(t,e){for(var n=0;n0&&h["default"].dispatch({actionType:_["default"].ACTION_NEW_SERVICES,services:t})}function i(t){return u("homeassistant","turn_on",{entity_id:t})}function o(t){return u("homeassistant","turn_off",{entity_id:t})}function u(t,e){var n=void 0===arguments[2]?{}:arguments[2];return f["default"]("POST","services/"+t+"/"+e,n).then(function(r){v.notify("turn_on"==e&&n.entity_id?"Turned on "+n.entity_id+".":"turn_off"==e&&n.entity_id?"Turned off "+n.entity_id+".":"Service "+t+"/"+e+" called."),d.newStates(r)})}function a(){return f["default"]("GET","services").then(r)}var s=function(t){return t&&t.__esModule?t:{"default":t}};Object.defineProperty(e,"__esModule",{value:!0}),e.newServices=r,e.callTurnOn=i,e.callTurnOff=o,e.callService=u,e.fetchAll=a;var c=n(5),f=s(c),l=n(1),h=s(l),p=n(2),_=s(p),v=n(10),d=n(12)},function(t,e,n){"use strict";function r(t,e){(t.length>0||e)&&l["default"].dispatch({actionType:h.ACTION_NEW_STATES,states:t,replace:!!e})}function i(t,e){var n=void 0===arguments[2]?!1:arguments[2],i={state:e};n&&(i.attributes=n),c["default"]("POST","states/"+t,i).then(function(n){p.notify("State of "+t+" set to "+e+"."),r([n])})}function o(t){c["default"]("GET","states/"+t).then(function(t){r([t])})}function u(){c["default"]("GET","states").then(function(t){r(t,!0)})}var a=function(t){return t&&t.__esModule?t:{"default":t}};Object.defineProperty(e,"__esModule",{value:!0}),e.newStates=r,e.set=i,e.fetch=o,e.fetchAll=u;var s=n(5),c=a(s),f=n(1),l=a(f),h=n(2),p=n(10)},function(t,e,n){"use strict";function r(){f["default"].dispatch({actionType:h["default"].ACTION_FETCH_ALL}),_.fetchAll(),d.fetchAll(),g.fetchAll(),w.fetchAll(),b&&E()}function i(){b=!0,r()}function o(){b=!1,E.cancel()}var u=function(t){return t&&t.__esModule?t:{"default":t}};Object.defineProperty(e,"__esModule",{value:!0}),e.fetchAll=r,e.start=i,e.stop=o;var a=n(6),s=u(a),c=n(1),f=u(c),l=n(2),h=u(l),p=n(26),_=u(p),v=n(12),d=u(v),y=n(11),g=u(y),m=n(25),w=u(m),T=3e4,b=!1,E=s["default"].debounce(r,T)},function(t,e,n){"use strict";var r=function(t){return t&&t.__esModule?t:{"default":t}},i=function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t)){var n=[],r=!0,i=!1,o=void 0;try{for(var u,a=t[Symbol.iterator]();!(r=(u=a.next()).done)&&(n.push(u.value),!e||n.length!==e);r=!0);}catch(s){i=!0,o=s}finally{try{!r&&a["return"]&&a["return"]()}finally{if(i)throw o}}return n}throw new TypeError("Invalid attempt to destructure non-iterable instance")},o=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},u=function(){function t(t,e){for(var n=0;nd}},{key:"all",get:function(){return g}}]),e}(p["default"]),w=new m;w.dispatchToken=c["default"].register(function(t){switch(t.actionType){case l["default"].ACTION_NEW_LOGBOOK:g=new a.List(t.logbookEntries.map(function(t){return v["default"].fromJSON(t)})),y=new Date,w.emitChange();break;case l["default"].ACTION_LOG_OUT:y=null,g=new a.List,w.emitChange()}}),e["default"]=w,t.exports=e["default"]},function(t,e,n){"use strict";function r(){return y.size}var i=function(t){return t&&t.__esModule?t:{"default":t}},o=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},u=function(){function t(t,e){for(var n=0;nv}},{key:"get",value:function(t){return g[t]||null}},{key:"all",get:function(){return s["default"].sortBy(s["default"].values(g),function(t){return t[0].entityId})}}]),e}(_["default"]),w=new m;w.dispatchToken=f["default"].register(function(t){switch(t.actionType){case h["default"].ACTION_NEW_STATE_HISTORY:s["default"].forEach(t.stateHistory,function(t){if(0!==t.length){var e=t[0].entityId;g[e]=t,y[e]=new Date}}),t.isFetchAll&&(d=new Date),w.emitChange();break;case h["default"].ACTION_LOG_OUT:d=null,y={},g={},w.emitChange()}}),e["default"]=w,t.exports=e["default"]},function(t,e,n){"use strict";function r(t){return-1!==y.indexOf(t)}function i(){return y.length===v}var o=function(t){return t&&t.__esModule?t:{"default":t}},u=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},a=function(){function t(t,e){for(var n=0;n0)&&f["default"].dispatch({actionType:h["default"].ACTION_NEW_STATE_HISTORY,stateHistory:e.map(function(t){return t.map(_["default"].fromJSON)}),isFetchAll:t})}function i(){s["default"]("GET","history/period").then(function(t){return r(!0,t)})}function o(t){s["default"]("GET","history/period?filter_entity_id="+t).then(function(t){return r(!1,t)})}var u=function(t){return t&&t.__esModule?t:{"default":t}};Object.defineProperty(e,"__esModule",{value:!0}),e.fetchAll=i,e.fetch=o;var a=n(5),s=u(a),c=n(1),f=u(c),l=n(2),h=u(l),p=n(14),_=u(p)},function(t,e,n){"use strict";function r(){return"webkitSpeechRecognition"in window}function i(){var t=g||y;l["default"].dispatch({actionType:p["default"].ACTION_LISTENING_TRANSMITTING,finalTranscript:t}),_.callService("conversation","process",{text:t}).then(function(){l["default"].dispatch({actionType:p["default"].ACTION_LISTENING_DONE,finalTranscript:t})},function(){l["default"].dispatch({actionType:p["default"].ACTION_LISTENING_ERROR})})}function o(){null!==d&&(d.onstart=null,d.onresult=null,d.onerror=null,d.onend=null,d.stop(),d=null,i()),y="",g=""}function u(){o(),window.r=d=new webkitSpeechRecognition,d.interimResults=!0,d.onstart=function(){l["default"].dispatch({actionType:p["default"].ACTION_LISTENING_START})},d.onresult=function(t){y="";for(var e=t.resultIndex;et||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},r.prototype.emit=function(t){var e,n,r,o,s,c;if(this._events||(this._events={}),"error"===t&&(!this._events.error||u(this._events.error)&&!this._events.error.length)){if(e=arguments[1],e instanceof Error)throw e;throw TypeError('Uncaught, unspecified "error" event.')}if(n=this._events[t],a(n))return!1;if(i(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:for(r=arguments.length,o=new Array(r-1),s=1;r>s;s++)o[s-1]=arguments[s];n.apply(this,o)}else if(u(n)){for(r=arguments.length,o=new Array(r-1),s=1;r>s;s++)o[s-1]=arguments[s];for(c=n.slice(),r=c.length,s=0;r>s;s++)c[s].apply(this,o)}return!0},r.prototype.addListener=function(t,e){var n;if(!i(e))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,i(e.listener)?e.listener:e),this._events[t]?u(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,u(this._events[t])&&!this._events[t].warned){var n;n=a(this._maxListeners)?r.defaultMaxListeners:this._maxListeners,n&&n>0&&this._events[t].length>n&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())}return this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(t,e){function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var r=!1;return n.listener=e,this.on(t,n),this},r.prototype.removeListener=function(t,e){var n,r,o,a;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(n=this._events[t],o=n.length,r=-1,n===e||i(n.listener)&&n.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(u(n)){for(a=o;a-->0;)if(n[a]===e||n[a].listener&&n[a].listener===e){r=a;break}if(0>r)return this;1===n.length?(n.length=0,delete this._events[t]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},r.prototype.removeAllListeners=function(t){var e,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[t],i(n))this.removeListener(t,n);else for(;n.length;)this.removeListener(t,n[n.length-1]);return delete this._events[t],this},r.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},r.listenerCount=function(t,e){var n;return n=t._events&&t._events[e]?i(t._events[e])?1:t._events[e].length:0}},function(t,e,n){function r(t){return n(i(t))}function i(t){return o[t]||function(){throw new Error("Cannot find module '"+t+"'.")}()}var o={"./auth":7,"./auth.js":7,"./component":15,"./component.js":15,"./event":16,"./event.js":16,"./logbook":17,"./logbook.js":17,"./notification":18,"./notification.js":18,"./preference":19,"./preference.js":19,"./service":8,"./service.js":8,"./state":20,"./state.js":20,"./state_history":21,"./state_history.js":21,"./store":3,"./store.js":3,"./stream":9,"./stream.js":9,"./sync":22,"./sync.js":22,"./voice":23,"./voice.js":23};r.keys=function(){return Object.keys(o)},r.resolve=i,t.exports=r,r.id=40}]); \ No newline at end of file +return pickBy("isBefore",args)};moment.max=function(){var args=[].slice.call(arguments,0);return pickBy("isAfter",args)};moment.utc=function(input,format,locale,strict){var c;if(typeof locale==="boolean"){strict=locale;locale=undefined}c={};c._isAMomentObject=true;c._useUTC=true;c._isUTC=true;c._l=locale;c._i=input;c._f=format;c._strict=strict;c._pf=defaultParsingFlags();return makeMoment(c).utc()};moment.unix=function(input){return moment(input*1e3)};moment.duration=function(input,key){var duration=input,match=null,sign,ret,parseIso,diffRes;if(moment.isDuration(input)){duration={ms:input._milliseconds,d:input._days,M:input._months}}else if(typeof input==="number"){duration={};if(key){duration[key]=input}else{duration.milliseconds=input}}else if(!!(match=aspNetTimeSpanJsonRegex.exec(input))){sign=match[1]==="-"?-1:1;duration={y:0,d:toInt(match[DATE])*sign,h:toInt(match[HOUR])*sign,m:toInt(match[MINUTE])*sign,s:toInt(match[SECOND])*sign,ms:toInt(match[MILLISECOND])*sign}}else if(!!(match=isoDurationRegex.exec(input))){sign=match[1]==="-"?-1:1;parseIso=function(inp){var res=inp&&parseFloat(inp.replace(",","."));return(isNaN(res)?0:res)*sign};duration={y:parseIso(match[2]),M:parseIso(match[3]),d:parseIso(match[4]),h:parseIso(match[5]),m:parseIso(match[6]),s:parseIso(match[7]),w:parseIso(match[8])}}else if(duration==null){duration={}}else if(typeof duration==="object"&&("from"in duration||"to"in duration)){diffRes=momentsDifference(moment(duration.from),moment(duration.to));duration={};duration.ms=diffRes.milliseconds;duration.M=diffRes.months}ret=new Duration(duration);if(moment.isDuration(input)&&hasOwnProp(input,"_locale")){ret._locale=input._locale}return ret};moment.version=VERSION;moment.defaultFormat=isoFormat;moment.ISO_8601=function(){};moment.momentProperties=momentProperties;moment.updateOffset=function(){};moment.relativeTimeThreshold=function(threshold,limit){if(relativeTimeThresholds[threshold]===undefined){return false}if(limit===undefined){return relativeTimeThresholds[threshold]}relativeTimeThresholds[threshold]=limit;return true};moment.lang=deprecate("moment.lang is deprecated. Use moment.locale instead.",function(key,value){return moment.locale(key,value)});moment.locale=function(key,values){var data;if(key){if(typeof values!=="undefined"){data=moment.defineLocale(key,values)}else{data=moment.localeData(key)}if(data){moment.duration._locale=moment._locale=data}}return moment._locale._abbr};moment.defineLocale=function(name,values){if(values!==null){values.abbr=name;if(!locales[name]){locales[name]=new Locale}locales[name].set(values);moment.locale(name);return locales[name]}else{delete locales[name];return null}};moment.langData=deprecate("moment.langData is deprecated. Use moment.localeData instead.",function(key){return moment.localeData(key)});moment.localeData=function(key){var locale;if(key&&key._locale&&key._locale._abbr){key=key._locale._abbr}if(!key){return moment._locale}if(!isArray(key)){locale=loadLocale(key);if(locale){return locale}key=[key]}return chooseLocale(key)};moment.isMoment=function(obj){return obj instanceof Moment||obj!=null&&hasOwnProp(obj,"_isAMomentObject")};moment.isDuration=function(obj){return obj instanceof Duration};for(i=lists.length-1;i>=0;--i){makeList(lists[i])}moment.normalizeUnits=function(units){return normalizeUnits(units)};moment.invalid=function(flags){var m=moment.utc(NaN);if(flags!=null){extend(m._pf,flags)}else{m._pf.userInvalidated=true}return m};moment.parseZone=function(){return moment.apply(null,arguments).parseZone()};moment.parseTwoDigitYear=function(input){return toInt(input)+(toInt(input)>68?1900:2e3)};moment.isDate=isDate;extend(moment.fn=Moment.prototype,{clone:function(){return moment(this)},valueOf:function(){return+this._d-(this._offset||0)*6e4},unix:function(){return Math.floor(+this/1e3)},toString:function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},toDate:function(){return this._offset?new Date(+this):this._d},toISOString:function(){var m=moment(this).utc();if(00}return false},parsingFlags:function(){return extend({},this._pf)},invalidAt:function(){return this._pf.overflow},utc:function(keepLocalTime){return this.utcOffset(0,keepLocalTime)},local:function(keepLocalTime){if(this._isUTC){this.utcOffset(0,keepLocalTime);this._isUTC=false;if(keepLocalTime){this.subtract(this._dateUtcOffset(),"m")}}return this},format:function(inputString){var output=formatMoment(this,inputString||moment.defaultFormat);return this.localeData().postformat(output)},add:createAdder(1,"add"),subtract:createAdder(-1,"subtract"),diff:function(input,units,asFloat){var that=makeAs(input,this),zoneDiff=(that.utcOffset()-this.utcOffset())*6e4,anchor,diff,output,daysAdjust;units=normalizeUnits(units);if(units==="year"||units==="month"||units==="quarter"){output=monthDiff(this,that);if(units==="quarter"){output=output/3}else if(units==="year"){output=output/12}}else{diff=this-that;output=units==="second"?diff/1e3:units==="minute"?diff/6e4:units==="hour"?diff/36e5:units==="day"?(diff-zoneDiff)/864e5:units==="week"?(diff-zoneDiff)/6048e5:diff}return asFloat?output:absRound(output)},from:function(time,withoutSuffix){return moment.duration({to:this,from:time}).locale(this.locale()).humanize(!withoutSuffix)},fromNow:function(withoutSuffix){return this.from(moment(),withoutSuffix)},calendar:function(time){var now=time||moment(),sod=makeAs(now,this).startOf("day"),diff=this.diff(sod,"days",true),format=diff<-6?"sameElse":diff<-1?"lastWeek":diff<0?"lastDay":diff<1?"sameDay":diff<2?"nextDay":diff<7?"nextWeek":"sameElse";return this.format(this.localeData().calendar(format,this,moment(now)))},isLeapYear:function(){return isLeapYear(this.year())},isDST:function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},day:function(input){var day=this._isUTC?this._d.getUTCDay():this._d.getDay();if(input!=null){input=parseWeekday(input,this.localeData());return this.add(input-day,"d")}else{return day}},month:makeAccessor("Month",true),startOf:function(units){units=normalizeUnits(units);switch(units){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}if(units==="week"){this.weekday(0)}else if(units==="isoWeek"){this.isoWeekday(1)}if(units==="quarter"){this.month(Math.floor(this.month()/3)*3)}return this},endOf:function(units){units=normalizeUnits(units);if(units===undefined||units==="millisecond"){return this}return this.startOf(units).add(1,units==="isoWeek"?"week":units).subtract(1,"ms")},isAfter:function(input,units){var inputMs;units=normalizeUnits(typeof units!=="undefined"?units:"millisecond");if(units==="millisecond"){input=moment.isMoment(input)?input:moment(input);return+this>+input}else{inputMs=moment.isMoment(input)?+input:+moment(input);return inputMs<+this.clone().startOf(units)}},isBefore:function(input,units){var inputMs;units=normalizeUnits(typeof units!=="undefined"?units:"millisecond");if(units==="millisecond"){input=moment.isMoment(input)?input:moment(input);return+this<+input}else{inputMs=moment.isMoment(input)?+input:+moment(input);return+this.clone().endOf(units)this?this:other}),zone:deprecate("moment().zone is deprecated, use moment().utcOffset instead. "+"https://github.com/moment/moment/issues/1779",function(input,keepLocalTime){if(input!=null){if(typeof input!=="string"){input=-input}this.utcOffset(input,keepLocalTime);return this}else{return-this.utcOffset()}}),utcOffset:function(input,keepLocalTime){var offset=this._offset||0,localAdjust;if(input!=null){if(typeof input==="string"){input=utcOffsetFromString(input)}if(Math.abs(input)<16){input=input*60}if(!this._isUTC&&keepLocalTime){localAdjust=this._dateUtcOffset()}this._offset=input;this._isUTC=true;if(localAdjust!=null){this.add(localAdjust,"m")}if(offset!==input){if(!keepLocalTime||this._changeInProgress){addOrSubtractDurationFromMoment(this,moment.duration(input-offset,"m"),1,false)}else if(!this._changeInProgress){this._changeInProgress=true;moment.updateOffset(this,true);this._changeInProgress=null}}return this}else{return this._isUTC?offset:this._dateUtcOffset()}},isLocal:function(){return!this._isUTC},isUtcOffset:function(){return this._isUTC},isUtc:function(){return this._isUTC&&this._offset===0},zoneAbbr:function(){return this._isUTC?"UTC":""},zoneName:function(){return this._isUTC?"Coordinated Universal Time":""},parseZone:function(){if(this._tzm){this.utcOffset(this._tzm)}else if(typeof this._i==="string"){this.utcOffset(utcOffsetFromString(this._i))}return this},hasAlignedHourOffset:function(input){if(!input){input=0}else{input=moment(input).utcOffset()}return(this.utcOffset()-input)%60===0},daysInMonth:function(){return daysInMonth(this.year(),this.month())},dayOfYear:function(input){var dayOfYear=round((moment(this).startOf("day")-moment(this).startOf("year"))/864e5)+1;return input==null?dayOfYear:this.add(input-dayOfYear,"d")},quarter:function(input){return input==null?Math.ceil((this.month()+1)/3):this.month((input-1)*3+this.month()%3)},weekYear:function(input){var year=weekOfYear(this,this.localeData()._week.dow,this.localeData()._week.doy).year;return input==null?year:this.add(input-year,"y")},isoWeekYear:function(input){var year=weekOfYear(this,1,4).year;return input==null?year:this.add(input-year,"y")},week:function(input){var week=this.localeData().week(this);return input==null?week:this.add((input-week)*7,"d")},isoWeek:function(input){var week=weekOfYear(this,1,4).week;return input==null?week:this.add((input-week)*7,"d")},weekday:function(input){var weekday=(this.day()+7-this.localeData()._week.dow)%7;return input==null?weekday:this.add(input-weekday,"d")},isoWeekday:function(input){return input==null?this.day()||7:this.day(this.day()%7?input:input-7)},isoWeeksInYear:function(){return weeksInYear(this.year(),1,4)},weeksInYear:function(){var weekInfo=this.localeData()._week;return weeksInYear(this.year(),weekInfo.dow,weekInfo.doy)},get:function(units){units=normalizeUnits(units);return this[units]()},set:function(units,value){var unit;if(typeof units==="object"){for(unit in units){this.set(unit,units[unit])}}else{units=normalizeUnits(units);if(typeof this[units]==="function"){this[units](value)}}return this},locale:function(key){var newLocaleData;if(key===undefined){return this._locale._abbr}else{newLocaleData=moment.localeData(key);if(newLocaleData!=null){this._locale=newLocaleData}return this}},lang:deprecate("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(key){if(key===undefined){return this.localeData()}else{return this.locale(key)}}),localeData:function(){return this._locale},_dateUtcOffset:function(){return-Math.round(this._d.getTimezoneOffset()/15)*15}});function rawMonthSetter(mom,value){var dayOfMonth;if(typeof value==="string"){value=mom.localeData().monthsParse(value);if(typeof value!=="number"){return mom}}dayOfMonth=Math.min(mom.date(),daysInMonth(mom.year(),value));mom._d["set"+(mom._isUTC?"UTC":"")+"Month"](value,dayOfMonth);return mom}function rawGetter(mom,unit){return mom._d["get"+(mom._isUTC?"UTC":"")+unit]()}function rawSetter(mom,unit,value){if(unit==="Month"){return rawMonthSetter(mom,value)}else{return mom._d["set"+(mom._isUTC?"UTC":"")+unit](value)}}function makeAccessor(unit,keepTime){return function(value){if(value!=null){rawSetter(this,unit,value);moment.updateOffset(this,keepTime);return this}else{return rawGetter(this,unit)}}}moment.fn.millisecond=moment.fn.milliseconds=makeAccessor("Milliseconds",false);moment.fn.second=moment.fn.seconds=makeAccessor("Seconds",false);moment.fn.minute=moment.fn.minutes=makeAccessor("Minutes",false);moment.fn.hour=moment.fn.hours=makeAccessor("Hours",true);moment.fn.date=makeAccessor("Date",true);moment.fn.dates=deprecate("dates accessor is deprecated. Use date instead.",makeAccessor("Date",true));moment.fn.year=makeAccessor("FullYear",true);moment.fn.years=deprecate("years accessor is deprecated. Use year instead.",makeAccessor("FullYear",true));moment.fn.days=moment.fn.day;moment.fn.months=moment.fn.month;moment.fn.weeks=moment.fn.week;moment.fn.isoWeeks=moment.fn.isoWeek;moment.fn.quarters=moment.fn.quarter;moment.fn.toJSON=moment.fn.toISOString;moment.fn.isUTC=moment.fn.isUtc;function daysToYears(days){return days*400/146097}function yearsToDays(years){return years*146097/400}extend(moment.duration.fn=Duration.prototype,{_bubble:function(){var milliseconds=this._milliseconds,days=this._days,months=this._months,data=this._data,seconds,minutes,hours,years=0;data.milliseconds=milliseconds%1e3;seconds=absRound(milliseconds/1e3);data.seconds=seconds%60;minutes=absRound(seconds/60);data.minutes=minutes%60;hours=absRound(minutes/60);data.hours=hours%24;days+=absRound(hours/24);years=absRound(daysToYears(days));days-=absRound(yearsToDays(years));months+=absRound(days/30);days%=30;years+=absRound(months/12);months%=12;data.days=days;data.months=months;data.years=years},abs:function(){this._milliseconds=Math.abs(this._milliseconds);this._days=Math.abs(this._days);this._months=Math.abs(this._months);this._data.milliseconds=Math.abs(this._data.milliseconds);this._data.seconds=Math.abs(this._data.seconds);this._data.minutes=Math.abs(this._data.minutes);this._data.hours=Math.abs(this._data.hours);this._data.months=Math.abs(this._data.months);this._data.years=Math.abs(this._data.years);return this},weeks:function(){return absRound(this.days()/7)},valueOf:function(){return this._milliseconds+this._days*864e5+this._months%12*2592e6+toInt(this._months/12)*31536e6},humanize:function(withSuffix){var output=relativeTime(this,!withSuffix,this.localeData());if(withSuffix){output=this.localeData().pastFuture(+this,output)}return this.localeData().postformat(output)},add:function(input,val){var dur=moment.duration(input,val);this._milliseconds+=dur._milliseconds;this._days+=dur._days;this._months+=dur._months;this._bubble();return this},subtract:function(input,val){var dur=moment.duration(input,val);this._milliseconds-=dur._milliseconds;this._days-=dur._days;this._months-=dur._months;this._bubble();return this},get:function(units){units=normalizeUnits(units);return this[units.toLowerCase()+"s"]()},as:function(units){var days,months;units=normalizeUnits(units);if(units==="month"||units==="year"){days=this._days+this._milliseconds/864e5;months=this._months+daysToYears(days)*12;return units==="month"?months:months/12}else{days=this._days+Math.round(yearsToDays(this._months/12));switch(units){case"week":return days/7+this._milliseconds/6048e5;case"day":return days+this._milliseconds/864e5;case"hour":return days*24+this._milliseconds/36e5;case"minute":return days*24*60+this._milliseconds/6e4;case"second":return days*24*60*60+this._milliseconds/1e3;case"millisecond":return Math.floor(days*24*60*60*1e3)+this._milliseconds;default:throw new Error("Unknown unit "+units)}}},lang:moment.fn.lang,locale:moment.fn.locale,toIsoString:deprecate("toIsoString() is deprecated. Please use toISOString() instead "+"(notice the capitals)",function(){return this.toISOString()}),toISOString:function(){var years=Math.abs(this.years()),months=Math.abs(this.months()),days=Math.abs(this.days()),hours=Math.abs(this.hours()),minutes=Math.abs(this.minutes()),seconds=Math.abs(this.seconds()+this.milliseconds()/1e3);if(!this.asSeconds()){return"P0D"}return(this.asSeconds()<0?"-":"")+"P"+(years?years+"Y":"")+(months?months+"M":"")+(days?days+"D":"")+(hours||minutes||seconds?"T":"")+(hours?hours+"H":"")+(minutes?minutes+"M":"")+(seconds?seconds+"S":"")},localeData:function(){return this._locale},toJSON:function(){return this.toISOString()}});moment.duration.fn.toString=moment.duration.fn.toISOString;function makeDurationGetter(name){moment.duration.fn[name]=function(){return this._data[name]}}for(i in unitMillisecondFactors){if(hasOwnProp(unitMillisecondFactors,i)){makeDurationGetter(i.toLowerCase())}}moment.duration.fn.asMilliseconds=function(){return this.as("ms")};moment.duration.fn.asSeconds=function(){return this.as("s")};moment.duration.fn.asMinutes=function(){return this.as("m")};moment.duration.fn.asHours=function(){return this.as("h")};moment.duration.fn.asDays=function(){return this.as("d")};moment.duration.fn.asWeeks=function(){return this.as("weeks")};moment.duration.fn.asMonths=function(){return this.as("M")};moment.duration.fn.asYears=function(){return this.as("y")};moment.locale("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(number){var b=number%10,output=toInt(number%100/10)===1?"th":b===1?"st":b===2?"nd":b===3?"rd":"th";return number+output}});function makeGlobal(shouldDeprecate){if(typeof ender!=="undefined"){return}oldGlobalMoment=globalScope.moment;if(shouldDeprecate){globalScope.moment=deprecate("Accessing Moment through the global scope is "+"deprecated, and will be removed in an upcoming "+"release.",moment)}else{globalScope.moment=moment}}if(hasModule){module.exports=moment}else if(typeof define==="function"&&define.amd){define(function(require,exports,module){if(module.config&&module.config()&&module.config().noGlobal===true){globalScope.moment=oldGlobalMoment}return moment});makeGlobal(true)}else{makeGlobal()}}).call(this); \ No newline at end of file diff --git a/homeassistant/components/frontend/www_static/polymer/more-infos/more-info-sun.html b/homeassistant/components/frontend/www_static/polymer/more-infos/more-info-sun.html index 96c92357d1b..8a2969db371 100644 --- a/homeassistant/components/frontend/www_static/polymer/more-infos/more-info-sun.html +++ b/homeassistant/components/frontend/www_static/polymer/more-infos/more-info-sun.html @@ -11,38 +11,43 @@
- Rising + Rising
- {{stateObj.attributes.next_rising | HATimeStripDate}} + {{rising | formatTime}}
- Setting + Setting
- {{stateObj.attributes.next_setting | HATimeStripDate}} + {{setting | formatTime}}
From 040dd3c40999c517d1cd8963e709aa36315a4b14 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Wed, 29 Apr 2015 08:18:53 -0700 Subject: [PATCH 05/11] Strip microseconds on state.last_updated --- homeassistant/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/homeassistant/__init__.py b/homeassistant/__init__.py index 7d6a1f03d00..301a403193d 100644 --- a/homeassistant/__init__.py +++ b/homeassistant/__init__.py @@ -496,7 +496,8 @@ class State(object): self.entity_id = entity_id.lower() self.state = state self.attributes = attributes or {} - self.last_updated = last_updated or date_util.utcnow() + self.last_updated = date_util.strip_microseconds( + last_updated or date_util.utcnow()) # Strip microsecond from last_changed else we cannot guarantee # state == State.from_dict(state.as_dict()) From ef470de3ca5c9f703079739a60b081516e9b50bc Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Wed, 29 Apr 2015 09:01:27 -0700 Subject: [PATCH 06/11] Update coveragerc to hide latest device components --- .coveragerc | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.coveragerc b/.coveragerc index 4b317feb12c..2e9ee27dcb5 100644 --- a/.coveragerc +++ b/.coveragerc @@ -11,6 +11,9 @@ omit = homeassistant/components/zwave.py homeassistant/components/*/zwave.py + homeassistant/components/modbus.py + homeassistant/components/*/modbus.py + homeassistant/components/*/tellstick.py homeassistant/components/*/vera.py @@ -23,6 +26,8 @@ omit = homeassistant/components/sensor/mysensors.py homeassistant/components/notify/pushbullet.py homeassistant/components/notify/pushover.py + homeassistant/components/notify/instapush.py + homeassistant/components/notify/nma.py homeassistant/components/media_player/cast.py homeassistant/components/device_tracker/luci.py homeassistant/components/device_tracker/tomato.py From fd67e47128ff4237027ccb239ea92e9666c0b594 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Wed, 29 Apr 2015 22:26:54 -0700 Subject: [PATCH 07/11] Add tests for device_sun_light_trigger --- .../custom_components/device_tracker/test.py | 4 + tests/helpers.py | 34 ++++- ...test_component_device_sun_light_trigger.py | 127 ++++++++++++++++++ tests/test_component_device_tracker.py | 2 + 4 files changed, 166 insertions(+), 1 deletion(-) create mode 100644 tests/test_component_device_sun_light_trigger.py diff --git a/tests/config/custom_components/device_tracker/test.py b/tests/config/custom_components/device_tracker/test.py index 481892a9a67..635d400316f 100644 --- a/tests/config/custom_components/device_tracker/test.py +++ b/tests/config/custom_components/device_tracker/test.py @@ -26,6 +26,10 @@ class MockScanner(object): """ Make a device leave the house. """ self.devices_home.remove(device) + def reset(self): + """ Resets which devices are home. """ + self.devices_home = [] + def scan_devices(self): """ Returns a list of fake devices. """ diff --git a/tests/helpers.py b/tests/helpers.py index 33b4468cfac..f9ccfac94c9 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -5,10 +5,14 @@ tests.helper Helper method for writing tests. """ import os +from datetime import timedelta import homeassistant as ha +import homeassistant.util.dt as dt_util from homeassistant.helpers.entity import ToggleEntity -from homeassistant.const import STATE_ON, STATE_OFF, DEVICE_DEFAULT_NAME +from homeassistant.const import ( + STATE_ON, STATE_OFF, DEVICE_DEFAULT_NAME, EVENT_TIME_CHANGED) +from homeassistant.components import sun def get_test_config_dir(): @@ -20,6 +24,8 @@ def get_test_home_assistant(): """ Returns a Home Assistant object pointing at test config dir. """ hass = ha.HomeAssistant() hass.config.config_dir = get_test_config_dir() + hass.config.latitude = 32.87336 + hass.config.longitude = -117.22743 return hass @@ -37,6 +43,32 @@ def mock_service(hass, domain, service): return calls +def trigger_device_tracker_scan(hass): + """ Triggers the device tracker to scan. """ + hass.bus.fire( + EVENT_TIME_CHANGED, + {'now': + dt_util.utcnow().replace(second=0) + timedelta(hours=1)}) + + +def ensure_sun_risen(hass): + """ Trigger sun to rise if below horizon. """ + if not sun.is_on(hass): + hass.bus.fire( + EVENT_TIME_CHANGED, + {'now': + sun.next_rising_utc(hass) + timedelta(seconds=10)}) + + +def ensure_sun_set(hass): + """ Trigger sun to set if above horizon. """ + if sun.is_on(hass): + hass.bus.fire( + EVENT_TIME_CHANGED, + {'now': + sun.next_setting_utc(hass) + timedelta(seconds=10)}) + + class MockModule(object): """ Provides a fake module. """ diff --git a/tests/test_component_device_sun_light_trigger.py b/tests/test_component_device_sun_light_trigger.py new file mode 100644 index 00000000000..7a05f63099f --- /dev/null +++ b/tests/test_component_device_sun_light_trigger.py @@ -0,0 +1,127 @@ +""" +tests.test_component_device_sun_light_trigger +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tests device sun light trigger component. +""" +# pylint: disable=too-many-public-methods,protected-access +import os +import unittest + +import homeassistant.loader as loader +from homeassistant.const import CONF_PLATFORM +from homeassistant.components import ( + device_tracker, light, sun, device_sun_light_trigger) + + +from helpers import ( + get_test_home_assistant, ensure_sun_risen, ensure_sun_set, + trigger_device_tracker_scan) + + +KNOWN_DEV_PATH = None + + +def setUpModule(): # pylint: disable=invalid-name + """ Initalizes a Home Assistant server. """ + global KNOWN_DEV_PATH + + hass = get_test_home_assistant() + + loader.prepare(hass) + KNOWN_DEV_PATH = hass.config.path( + device_tracker.KNOWN_DEVICES_FILE) + + hass.stop() + + with open(KNOWN_DEV_PATH, 'w') as fil: + fil.write('device,name,track,picture\n') + fil.write('DEV1,device 1,1,http://example.com/dev1.jpg\n') + fil.write('DEV2,device 2,1,http://example.com/dev2.jpg\n') + + +def tearDownModule(): # pylint: disable=invalid-name + """ Stops the Home Assistant server. """ + os.remove(KNOWN_DEV_PATH) + + +class TestDeviceSunLightTrigger(unittest.TestCase): + """ Test the device sun light trigger module. """ + + def setUp(self): # pylint: disable=invalid-name + self.hass = get_test_home_assistant() + + self.scanner = loader.get_component( + 'device_tracker.test').get_scanner(None, None) + + self.scanner.reset() + self.scanner.come_home('DEV1') + + loader.get_component('light.test').init() + + device_tracker.setup(self.hass, { + device_tracker.DOMAIN: {CONF_PLATFORM: 'test'} + }) + + light.setup(self.hass, { + light.DOMAIN: {CONF_PLATFORM: 'test'} + }) + + sun.setup(self.hass, {}) + + def tearDown(self): # pylint: disable=invalid-name + """ Stop down stuff we started. """ + self.hass.stop() + + def test_lights_on_when_sun_sets(self): + """ Test lights go on when there is someone home and the sun sets. """ + + device_sun_light_trigger.setup( + self.hass, {device_sun_light_trigger.DOMAIN: {}}) + + ensure_sun_risen(self.hass) + + light.turn_off(self.hass) + + self.hass.pool.block_till_done() + + ensure_sun_set(self.hass) + + self.hass.pool.block_till_done() + + self.assertTrue(light.is_on(self.hass)) + + def test_lights_turn_off_when_everyone_leaves(self): + """ Test lights turn off when everyone leaves the house. """ + light.turn_on(self.hass) + + self.hass.pool.block_till_done() + + device_sun_light_trigger.setup( + self.hass, {device_sun_light_trigger.DOMAIN: {}}) + + self.scanner.leave_home('DEV1') + + trigger_device_tracker_scan(self.hass) + + self.hass.pool.block_till_done() + + self.assertFalse(light.is_on(self.hass)) + + def test_lights_turn_on_when_coming_home_after_sun_set(self): + """ Test lights turn on when coming home after sun set. """ + light.turn_off(self.hass) + + ensure_sun_set(self.hass) + + self.hass.pool.block_till_done() + + device_sun_light_trigger.setup( + self.hass, {device_sun_light_trigger.DOMAIN: {}}) + + self.scanner.come_home('DEV2') + trigger_device_tracker_scan(self.hass) + + self.hass.pool.block_till_done() + + self.assertTrue(light.is_on(self.hass)) diff --git a/tests/test_component_device_tracker.py b/tests/test_component_device_tracker.py index 74af55fdc66..038b2363e7b 100644 --- a/tests/test_component_device_tracker.py +++ b/tests/test_component_device_tracker.py @@ -81,6 +81,8 @@ class TestComponentsDeviceTracker(unittest.TestCase): scanner = loader.get_component( 'device_tracker.test').get_scanner(None, None) + scanner.reset() + scanner.come_home('DEV1') scanner.come_home('DEV2') From cf5278b7e9f6f60f9abe36c438a73c6933387348 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Wed, 29 Apr 2015 23:21:31 -0700 Subject: [PATCH 08/11] Add tests for recorder component --- homeassistant/__init__.py | 14 +++++- homeassistant/components/recorder.py | 7 +++ tests/test_component_recorder.py | 70 ++++++++++++++++++++++++++++ tests/test_core.py | 6 ++- 4 files changed, 95 insertions(+), 2 deletions(-) create mode 100644 tests/test_component_recorder.py diff --git a/homeassistant/__init__.py b/homeassistant/__init__.py index 301a403193d..2beb749ec6b 100644 --- a/homeassistant/__init__.py +++ b/homeassistant/__init__.py @@ -376,6 +376,13 @@ class Event(object): return "".format(self.event_type, str(self.origin)[0]) + def __eq__(self, other): + return (self.__class__ == other.__class__ and + self.event_type == other.event_type and + self.data == other.data and + self.origin == other.origin and + self.time_fired == other.time_fired) + class EventBus(object): """ Class that allows different components to communicate via services @@ -398,6 +405,9 @@ class EventBus(object): def fire(self, event_type, event_data=None, origin=EventOrigin.local): """ Fire an event. """ + if not self._pool.running: + raise HomeAssistantError('Home Assistant has shut down.') + with self._lock: # Copy the list of the current listeners because some listeners # remove themselves as a listener while being executed which @@ -898,7 +908,9 @@ class Timer(threading.Thread): last_fired_on_second = now.second - self.hass.bus.fire(EVENT_TIME_CHANGED, {ATTR_NOW: now}) + # Event might have been set while sleeping + if not self._stop_event.isSet(): + self.hass.bus.fire(EVENT_TIME_CHANGED, {ATTR_NOW: now}) class Config(object): diff --git a/homeassistant/components/recorder.py b/homeassistant/components/recorder.py index 4f0a76cf18a..717b6514bb4 100644 --- a/homeassistant/components/recorder.py +++ b/homeassistant/components/recorder.py @@ -189,9 +189,11 @@ class Recorder(threading.Thread): if event == self.quit_object: self._close_run() self._close_connection() + self.queue.task_done() return elif event.event_type == EVENT_TIME_CHANGED: + self.queue.task_done() continue elif event.event_type == EVENT_STATE_CHANGED: @@ -199,6 +201,7 @@ class Recorder(threading.Thread): event.data['entity_id'], event.data.get('new_state')) self.record_event(event) + self.queue.task_done() def event_listener(self, event): """ Listens for new events on the EventBus and puts them @@ -266,6 +269,10 @@ class Recorder(threading.Thread): "Error querying the database using: %s", sql_query) return [] + def block_till_done(self): + """ Blocks till all events processed. """ + self.queue.join() + def _setup_connection(self): """ Ensure database is ready to fly. """ db_path = self.hass.config.path(DB_FILE) diff --git a/tests/test_component_recorder.py b/tests/test_component_recorder.py new file mode 100644 index 00000000000..68c63b637d0 --- /dev/null +++ b/tests/test_component_recorder.py @@ -0,0 +1,70 @@ +""" +tests.test_component_recorder +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tests Recorder component. +""" +# pylint: disable=too-many-public-methods,protected-access +import unittest +import os + +from homeassistant.const import MATCH_ALL +from homeassistant.components import recorder + +from helpers import get_test_home_assistant + + +class TestRecorder(unittest.TestCase): + """ Test the chromecast module. """ + + def setUp(self): # pylint: disable=invalid-name + self.hass = get_test_home_assistant() + recorder.setup(self.hass, {}) + self.hass.start() + recorder._INSTANCE.block_till_done() + + def tearDown(self): # pylint: disable=invalid-name + """ Stop down stuff we started. """ + self.hass.stop() + recorder._INSTANCE.block_till_done() + os.remove(self.hass.config.path(recorder.DB_FILE)) + + def test_saving_state(self): + """ Tests saving and restoring a state. """ + entity_id = 'test.recorder' + state = 'restoring_from_db' + attributes = {'test_attr': 5, 'test_attr_10': 'nice'} + + self.hass.states.set(entity_id, state, attributes) + + self.hass.pool.block_till_done() + recorder._INSTANCE.block_till_done() + + states = recorder.query_states('SELECT * FROM states') + + self.assertEqual(1, len(states)) + self.assertEqual(self.hass.states.get(entity_id), states[0]) + + def test_saving_event(self): + """ Tests saving and restoring an event. """ + event_type = 'EVENT_TEST' + event_data = {'test_attr': 5, 'test_attr_10': 'nice'} + + events = [] + + def event_listener(event): + """ Records events from eventbus. """ + if event.event_type == event_type: + events.append(event) + + self.hass.bus.listen(MATCH_ALL, event_listener) + + self.hass.bus.fire(event_type, event_data) + + self.hass.pool.block_till_done() + recorder._INSTANCE.block_till_done() + + db_events = recorder.query_events( + 'SELECT * FROM events WHERE event_type = ?', (event_type, )) + + self.assertEqual(events, db_events) diff --git a/tests/test_core.py b/tests/test_core.py index b450479f2d9..58052fe43f0 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -30,7 +30,11 @@ class TestHomeAssistant(unittest.TestCase): def tearDown(self): # pylint: disable=invalid-name """ Stop down stuff we started. """ - self.hass.stop() + try: + self.hass.stop() + except ha.HomeAssistantError: + # Already stopped after the block till stopped test + pass def test_get_config_path(self): """ Test get_config_path method. """ From 17cc9a43bb303284dd6c5711e4c80eac23cde8e1 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Thu, 30 Apr 2015 21:03:01 -0700 Subject: [PATCH 09/11] Add tests for history component --- homeassistant/__init__.py | 6 +- homeassistant/components/history.py | 2 +- tests/helpers.py | 25 +++++- tests/test_component_history.py | 134 ++++++++++++++++++++++++++++ 4 files changed, 163 insertions(+), 4 deletions(-) create mode 100644 tests/test_component_history.py diff --git a/homeassistant/__init__.py b/homeassistant/__init__.py index 2beb749ec6b..6a7b328ba40 100644 --- a/homeassistant/__init__.py +++ b/homeassistant/__init__.py @@ -910,7 +910,11 @@ class Timer(threading.Thread): # Event might have been set while sleeping if not self._stop_event.isSet(): - self.hass.bus.fire(EVENT_TIME_CHANGED, {ATTR_NOW: now}) + try: + self.hass.bus.fire(EVENT_TIME_CHANGED, {ATTR_NOW: now}) + except HomeAssistantError: + # HA raises error if firing event after it has shut down + break class Config(object): diff --git a/homeassistant/components/history.py b/homeassistant/components/history.py index 2717cdccd7f..14be60fa97e 100644 --- a/homeassistant/components/history.py +++ b/homeassistant/components/history.py @@ -23,7 +23,7 @@ def last_5_states(entity_id): query = """ SELECT * FROM states WHERE entity_id=? AND last_changed=last_updated - ORDER BY last_changed DESC LIMIT 0, 5 + ORDER BY state_id DESC LIMIT 0, 5 """ return recorder.query_states(query, (entity_id, )) diff --git a/tests/helpers.py b/tests/helpers.py index f9ccfac94c9..c6799defe21 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -11,7 +11,8 @@ import homeassistant as ha import homeassistant.util.dt as dt_util from homeassistant.helpers.entity import ToggleEntity from homeassistant.const import ( - STATE_ON, STATE_OFF, DEVICE_DEFAULT_NAME, EVENT_TIME_CHANGED) + STATE_ON, STATE_OFF, DEVICE_DEFAULT_NAME, EVENT_TIME_CHANGED, + EVENT_STATE_CHANGED) from homeassistant.components import sun @@ -20,9 +21,17 @@ def get_test_config_dir(): return os.path.join(os.path.dirname(__file__), "config") -def get_test_home_assistant(): +def get_test_home_assistant(num_threads=None): """ Returns a Home Assistant object pointing at test config dir. """ + if num_threads: + orig_num_threads = ha.MIN_WORKER_THREAD + ha.MIN_WORKER_THREAD = num_threads + hass = ha.HomeAssistant() + + if num_threads: + ha.MIN_WORKER_THREAD = orig_num_threads + hass.config.config_dir = get_test_config_dir() hass.config.latitude = 32.87336 hass.config.longitude = -117.22743 @@ -69,6 +78,18 @@ def ensure_sun_set(hass): sun.next_setting_utc(hass) + timedelta(seconds=10)}) +def mock_state_change_event(hass, new_state, old_state=None): + event_data = { + 'entity_id': new_state.entity_id, + 'new_state': new_state, + } + + if old_state: + event_data['old_state'] = old_state + + hass.bus.fire(EVENT_STATE_CHANGED, event_data) + + class MockModule(object): """ Provides a fake module. """ diff --git a/tests/test_component_history.py b/tests/test_component_history.py new file mode 100644 index 00000000000..86d91c14f22 --- /dev/null +++ b/tests/test_component_history.py @@ -0,0 +1,134 @@ +""" +tests.test_component_history +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tests the history component. +""" +# pylint: disable=protected-access,too-many-public-methods +import time +import os +import unittest + +import homeassistant as ha +import homeassistant.util.dt as dt_util +from homeassistant.components import history, recorder, http + +from helpers import get_test_home_assistant, mock_state_change_event + + +class TestComponentHistory(unittest.TestCase): + """ Tests homeassistant.components.history module. """ + + def setUp(self): # pylint: disable=invalid-name + """ Init needed objects. """ + self.hass = get_test_home_assistant(1) + self.init_rec = False + + def tearDown(self): # pylint: disable=invalid-name + """ Stop down stuff we started. """ + self.hass.stop() + + if self.init_rec: + recorder._INSTANCE.block_till_done() + os.remove(self.hass.config.path(recorder.DB_FILE)) + + def init_recorder(self): + recorder.setup(self.hass, {}) + self.hass.start() + recorder._INSTANCE.block_till_done() + self.init_rec = True + + def test_setup(self): + """ Test setup method of history. """ + http.setup(self.hass, {http.DOMAIN: {}}) + self.assertTrue(history.setup(self.hass, {})) + + def test_last_5_states(self): + """ Test retrieving the last 5 states. """ + self.init_recorder() + states = [] + + entity_id = 'test.last_5_states' + + for i in range(7): + self.hass.states.set(entity_id, "State {}".format(i)) + + if i > 1: + states.append(self.hass.states.get(entity_id)) + + self.hass.pool.block_till_done() + recorder._INSTANCE.block_till_done() + + self.assertEqual( + list(reversed(states)), history.last_5_states(entity_id)) + + def test_get_states(self): + """ Test getting states at a specific point in time. """ + self.init_recorder() + states = [] + + # Create 10 states for 5 different entities + # After the first 5, sleep a second and save the time + # history.get_states takes the latest states BEFORE point X + + for i in range(10): + state = ha.State( + 'test.point_in_time_{}'.format(i % 5), + "State {}".format(i), + {'attribute_test': i}) + + mock_state_change_event(self.hass, state) + self.hass.pool.block_till_done() + recorder._INSTANCE.block_till_done() + + if i < 5: + states.append(state) + + if i == 4: + time.sleep(1) + point = dt_util.utcnow() + + self.assertEqual( + states, + sorted( + history.get_states(point), key=lambda state: state.entity_id)) + + # Test get_state here because we have a DB setup + self.assertEqual( + states[0], history.get_state(point, states[0].entity_id)) + + def test_state_changes_during_period(self): + self.init_recorder() + entity_id = 'media_player.test' + + def set_state(state): + self.hass.states.set(entity_id, state) + self.hass.pool.block_till_done() + recorder._INSTANCE.block_till_done() + + return self.hass.states.get(entity_id) + + set_state('idle') + set_state('YouTube') + + start = dt_util.utcnow() + + time.sleep(1) + + states = [ + set_state('idle'), + set_state('Netflix'), + set_state('Plex'), + set_state('YouTube'), + ] + + time.sleep(1) + + end = dt_util.utcnow() + + set_state('Netflix') + set_state('Plex') + + self.assertEqual( + {entity_id: states}, + history.state_changes_during_period(start, end, entity_id)) From 2cad421de939d9089f68564e6c29b08817d58fcf Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Thu, 30 Apr 2015 21:47:20 -0700 Subject: [PATCH 10/11] Add tests for logbook component --- tests/test_component_logbook.py | 95 +++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 tests/test_component_logbook.py diff --git a/tests/test_component_logbook.py b/tests/test_component_logbook.py new file mode 100644 index 00000000000..99b38de1085 --- /dev/null +++ b/tests/test_component_logbook.py @@ -0,0 +1,95 @@ +""" +tests.test_component_logbook +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tests the logbook component. +""" +# pylint: disable=protected-access,too-many-public-methods +import unittest +from datetime import timedelta + +import homeassistant as ha +from homeassistant.const import ( + EVENT_STATE_CHANGED, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP) +import homeassistant.util.dt as dt_util +from homeassistant.components import logbook, http + +from helpers import get_test_home_assistant + + +class TestComponentHistory(unittest.TestCase): + """ Tests homeassistant.components.history module. """ + + def test_setup(self): + """ Test setup method. """ + try: + hass = get_test_home_assistant() + http.setup(hass, {}) + self.assertTrue(logbook.setup(hass, {})) + finally: + hass.stop() + + def test_humanify_filter_sensor(self): + """ Test humanify filter too frequent sensor values. """ + entity_id = 'sensor.bla' + + pointA = dt_util.strip_microseconds(dt_util.utcnow().replace(minute=2)) + pointB = pointA.replace(minute=5) + pointC = pointA + timedelta(minutes=logbook.GROUP_BY_MINUTES) + + eventA = self.create_state_changed_event(pointA, entity_id, 10) + eventB = self.create_state_changed_event(pointB, entity_id, 20) + eventC = self.create_state_changed_event(pointC, entity_id, 30) + + entries = list(logbook.humanify((eventA, eventB, eventC))) + + self.assertEqual(2, len(entries)) + self.assert_entry( + entries[0], pointB, 'bla', domain='sensor', entity_id=entity_id) + + self.assert_entry( + entries[1], pointC, 'bla', domain='sensor', entity_id=entity_id) + + def test_home_assistant_start_stop_grouped(self): + """ Tests if home assistant start and stop events are grouped if + occuring in the same minute. """ + entries = list(logbook.humanify(( + ha.Event(EVENT_HOMEASSISTANT_STOP), + ha.Event(EVENT_HOMEASSISTANT_START), + ))) + + self.assertEqual(1, len(entries)) + self.assert_entry( + entries[0], name='Home Assistant', message='restarted', + domain=ha.DOMAIN) + + def assert_entry(self, entry, when=None, name=None, message=None, + domain=None, entity_id=None): + """ Asserts an entry is what is expected """ + if when: + self.assertEqual(when, entry.when) + + if name: + self.assertEqual(name, entry.name) + + if message: + self.assertEqual(message, entry.message) + + if domain: + self.assertEqual(domain, entry.domain) + + if entity_id: + self.assertEqual(entity_id, entry.entity_id) + + def create_state_changed_event(self, event_time_fired, entity_id, state): + """ Create state changed event. """ + + # Logbook only cares about state change events that + # contain an old state but will not actually act on it. + state = ha.State(entity_id, state).as_dict() + + return ha.Event(EVENT_STATE_CHANGED, { + 'entity_id': entity_id, + 'old_state': state, + 'new_state': state, + }, time_fired=event_time_fired) From 29e376a66e988d29fae7ac5fbbdfe0975fe1fcfd Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Thu, 30 Apr 2015 21:59:24 -0700 Subject: [PATCH 11/11] Assign unique ports for history and logbook tests --- tests/test_component_history.py | 5 ++++- tests/test_component_logbook.py | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/test_component_history.py b/tests/test_component_history.py index 86d91c14f22..b6ae8dab33f 100644 --- a/tests/test_component_history.py +++ b/tests/test_component_history.py @@ -15,6 +15,8 @@ from homeassistant.components import history, recorder, http from helpers import get_test_home_assistant, mock_state_change_event +SERVER_PORT = 8126 + class TestComponentHistory(unittest.TestCase): """ Tests homeassistant.components.history module. """ @@ -40,7 +42,8 @@ class TestComponentHistory(unittest.TestCase): def test_setup(self): """ Test setup method of history. """ - http.setup(self.hass, {http.DOMAIN: {}}) + http.setup(self.hass, { + http.DOMAIN: {http.CONF_SERVER_PORT: SERVER_PORT}}) self.assertTrue(history.setup(self.hass, {})) def test_last_5_states(self): diff --git a/tests/test_component_logbook.py b/tests/test_component_logbook.py index 99b38de1085..2f8f6b8c513 100644 --- a/tests/test_component_logbook.py +++ b/tests/test_component_logbook.py @@ -16,6 +16,8 @@ from homeassistant.components import logbook, http from helpers import get_test_home_assistant +SERVER_PORT = 8127 + class TestComponentHistory(unittest.TestCase): """ Tests homeassistant.components.history module. """ @@ -24,7 +26,8 @@ class TestComponentHistory(unittest.TestCase): """ Test setup method. """ try: hass = get_test_home_assistant() - http.setup(hass, {}) + http.setup(hass, { + http.DOMAIN: {http.CONF_SERVER_PORT: SERVER_PORT}}) self.assertTrue(logbook.setup(hass, {})) finally: hass.stop()