Merge pull request #113 from balloob/refactor-utc
Refactor to use UTC internally
This commit is contained in:
commit
a752bc012c
32 files changed
+1029
-196
No files matched your search
+58
-17
@@ -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):
|
||||
@@ -352,6 +376,13 @@ class Event(object):
|
||||
return "<Event {}[{}]>".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
|
||||
@@ -374,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
|
||||
@@ -472,13 +506,14 @@ 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 = 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())
|
||||
# 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 +545,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 +561,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 +583,7 @@ class State(object):
|
||||
|
||||
return "<state {}={}{} @ {}>".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 +620,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 +882,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():
|
||||
@@ -873,7 +908,13 @@ 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():
|
||||
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):
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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 = []
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
""" DO NOT MODIFY. Auto-generated by build_frontend script """
|
||||
VERSION = "93774c7a1643c7e3f9cbbb1554b36683"
|
||||
VERSION = "fdfcc1c10ff8713976c482931769a8e6"
|
||||
@@ -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 <template bind/repeat>")}catch(g){return void console.error("Invalid expression syntax: "+a,g)}return function(a,b,c){var d=f.getBinding(a,e,c);return f.scopeIdent&&d&&(b.polymerExpressionScopeIdent_=f.scopeIdent,f.indexIdent&&(b.polymerExpressionIndexIdent_=f.indexIdent)),d}}function c(a){var b=q[a];if(!b){var c=new j;esprima.parse(a,c),b=new l(c),q[a]=b}return b}function d(a){this.value=a,this.valueFn_=void 0}function e(a){this.name=a,this.path=Path.get(a)}function f(a,b,c){this.computed="["==c,this.dynamicDeps="function"==typeof a||a.dynamicDeps||this.computed&&!(b instanceof d),this.simplePath=!this.dynamicDeps&&(b instanceof e||b instanceof d)&&(a instanceof f||a instanceof e),this.object=this.simplePath?a:i(a),this.property=!this.computed||this.simplePath?b:i(b)}function g(a,b){this.name=a,this.args=[];for(var c=0;c<b.length;c++)this.args[c]=i(b[c])}function h(){throw Error("Not Implemented")}function i(a){return"function"==typeof a?a:a.valueFn()}function j(){this.expression=null,this.filters=[],this.deps={},this.currentPath=void 0,this.scopeIdent=void 0,this.indexIdent=void 0,this.dynamicDeps=!1}function k(a){this.value_=a}function l(a){if(this.scopeIdent=a.scopeIdent,this.indexIdent=a.indexIdent,!a.expression)throw Error("No expression found.");this.expression=a.expression,i(this.expression),this.filters=a.filters,this.dynamicDeps=a.dynamicDeps}function m(a){return String(a).replace(/[A-Z]/g,function(a){return"-"+a.toLowerCase()})}function n(a,b){for(;a[t]&&!Object.prototype.hasOwnProperty.call(a,b);)a=a[t];return a}function o(a){switch(a){case"":return!1;case"false":case"null":case"true":return!0}return isNaN(Number(a))?!1:!0}function p(){}var q=Object.create(null);d.prototype={valueFn:function(){if(!this.valueFn_){var a=this.value;this.valueFn_=function(){return a}}return this.valueFn_}},e.prototype={valueFn:function(){if(!this.valueFn_){var a=(this.name,this.path);this.valueFn_=function(b,c){return c&&c.addPath(b,a),a.getValueFrom(b)}}return this.valueFn_},setValue:function(a,b){return 1==this.path.length&&(a=n(a,this.path[0])),this.path.setValueFrom(a,b)}},f.prototype={get fullPath(){if(!this.fullPath_){var a=this.object instanceof f?this.object.fullPath.slice():[this.object.name];a.push(this.property instanceof e?this.property.name:this.property.value),this.fullPath_=Path.get(a)}return this.fullPath_},valueFn:function(){if(!this.valueFn_){var a=this.object;if(this.simplePath){var b=this.fullPath;this.valueFn_=function(a,c){return c&&c.addPath(a,b),b.getValueFrom(a)}}else if(this.computed){var c=this.property;this.valueFn_=function(b,d,e){var f=a(b,d,e),g=c(b,d,e);return d&&d.addPath(f,[g]),f?f[g]:void 0}}else{var b=Path.get(this.property.name);this.valueFn_=function(c,d,e){var f=a(c,d,e);return d&&d.addPath(f,b),b.getValueFrom(f)}}}return this.valueFn_},setValue:function(a,b){if(this.simplePath)return this.fullPath.setValueFrom(a,b),b;var c=this.object(a),d=this.property instanceof e?this.property.name:this.property(a);return c[d]=b}},g.prototype={transform:function(a,b,c,d,e){var f=a,g=f[this.name];if(!g&&(g=c[this.name],!g))return void console.error("Cannot find function or filter: "+this.name);if(d?g=g.toModel:"function"==typeof g.toDOM&&(g=g.toDOM),"function"!=typeof g)return void console.error("Cannot find function or filter: "+this.name);for(var h=e||[],j=0;j<this.args.length;j++)h.push(i(this.args[j])(a,b,c));return g.apply(f,h)}};var r={"+":function(a){return+a},"-":function(a){return-a},"!":function(a){return!a}},s={"+":function(a,b){return a+b},"-":function(a,b){return a-b},"*":function(a,b){return a*b},"/":function(a,b){return a/b},"%":function(a,b){return a%b},"<":function(a,b){return b>a},">":function(a,b){return a>b},"<=":function(a,b){return b>=a},">=":function(a,b){return a>=b},"==":function(a,b){return a==b},"!=":function(a,b){return a!=b},"===":function(a,b){return a===b},"!==":function(a,b){return a!==b},"&&":function(a,b){return a&&b},"||":function(a,b){return a||b}};j.prototype={createUnaryExpression:function(a,b){if(!r[a])throw Error("Disallowed operator: "+a);return b=i(b),function(c,d,e){return r[a](b(c,d,e))}},createBinaryExpression:function(a,b,c){if(!s[a])throw Error("Disallowed operator: "+a);switch(b=i(b),c=i(c),a){case"||":return this.dynamicDeps=!0,function(a,d,e){return b(a,d,e)||c(a,d,e)};case"&&":return this.dynamicDeps=!0,function(a,d,e){return b(a,d,e)&&c(a,d,e)}}return functiLine truncated
|
||||
|
||||
if(this.removeAttribute("value"),c)return j(this,"value",b);var e=b,f=m(this,"value",e);return j(this,"value",e.open(k(this,"value",d))),t(this,a,f)},HTMLOptionElement.prototype.bind=function(a,b,c){if("value"!==a)return HTMLElement.prototype.bind.call(this,a,b,c);if(this.removeAttribute("value"),c)return q(this,b);var d=b,e=m(this,"value",d);return q(this,d.open(r(this))),t(this,a,e)},HTMLSelectElement.prototype.bind=function(a,c,d){if("selectedindex"===a&&(a="selectedIndex"),"selectedIndex"!==a&&"value"!==a)return HTMLElement.prototype.bind.call(this,a,c,d);if(this.removeAttribute(a),d)return j(this,a,c);var e=c,f=m(this,a,e);return j(this,a,e.open(k(this,a))),b(this,a,f)}}(this),function(a){"use strict";function b(a){if(!a)throw new Error("Assertion failed")}function c(a){for(var b;b=a.parentNode;)a=b;return a}function d(a,b){if(b){for(var d,e="#"+b;!d&&(a=c(a),a.protoContent_?d=a.protoContent_.querySelector(e):a.getElementById&&(d=a.getElementById(b)),!d&&a.templateCreator_);)a=a.templateCreator_;return d}}function e(a){return"template"==a.tagName&&"http://www.w3.org/2000/svg"==a.namespaceURI}function f(a){return"TEMPLATE"==a.tagName&&"http://www.w3.org/1999/xhtml"==a.namespaceURI}function g(a){return Boolean(L[a.tagName]&&a.hasAttribute("template"))}function h(a){return void 0===a.isTemplate_&&(a.isTemplate_="TEMPLATE"==a.tagName||g(a)),a.isTemplate_}function i(a,b){var c=a.querySelectorAll(N);h(a)&&b(a),G(c,b)}function j(a){function b(a){HTMLTemplateElement.decorate(a)||j(a.content)}i(a,b)}function k(a,b){Object.getOwnPropertyNames(b).forEach(function(c){Object.defineProperty(a,c,Object.getOwnPropertyDescriptor(b,c))})}function l(a){var b=a.ownerDocument;if(!b.defaultView)return b;var c=b.templateContentsOwner_;if(!c){for(c=b.implementation.createHTMLDocument("");c.lastChild;)c.removeChild(c.lastChild);b.templateContentsOwner_=c}return c}function m(a){if(!a.stagingDocument_){var b=a.ownerDocument;if(!b.stagingDocument_){b.stagingDocument_=b.implementation.createHTMLDocument(""),b.stagingDocument_.isStagingDocument=!0;var c=b.stagingDocument_.createElement("base");c.href=document.baseURI,b.stagingDocument_.head.appendChild(c),b.stagingDocument_.stagingDocument_=b.stagingDocument_}a.stagingDocument_=b.stagingDocument_}return a.stagingDocument_}function n(a){var b=a.ownerDocument.createElement("template");a.parentNode.insertBefore(b,a);for(var c=a.attributes,d=c.length;d-->0;){var e=c[d];K[e.name]&&("template"!==e.name&&b.setAttribute(e.name,e.value),a.removeAttribute(e.name))}return b}function o(a){var b=a.ownerDocument.createElement("template");a.parentNode.insertBefore(b,a);for(var c=a.attributes,d=c.length;d-->0;){var e=c[d];b.setAttribute(e.name,e.value),a.removeAttribute(e.name)}return a.parentNode.removeChild(a),b}function p(a,b,c){var d=a.content;if(c)return void d.appendChild(b);for(var e;e=b.firstChild;)d.appendChild(e)}function q(a){P?a.__proto__=HTMLTemplateElement.prototype:k(a,HTMLTemplateElement.prototype)}function r(a){a.setModelFn_||(a.setModelFn_=function(){a.setModelFnScheduled_=!1;var b=z(a,a.delegate_&&a.delegate_.prepareBinding);w(a,b,a.model_)}),a.setModelFnScheduled_||(a.setModelFnScheduled_=!0,Observer.runEOM_(a.setModelFn_))}function s(a,b,c,d){if(a&&a.length){for(var e,f=a.length,g=0,h=0,i=0,j=!0;f>h;){var g=a.indexOf("{{",h),k=a.indexOf("[[",h),l=!1,m="}}";if(k>=0&&(0>g||g>k)&&(g=k,l=!0,m="]]"),i=0>g?-1:a.indexOf(m,g+2),0>i){if(!e)return;e.push(a.slice(h));break}e=e||[],e.push(a.slice(h,g));var n=a.slice(g+2,i).trim();e.push(l),j=j&&l;var o=d&&d(n,b,c);e.push(null==o?Path.get(n):null),e.push(o),h=i+2}return h===f&&e.push(""),e.hasOnePath=5===e.length,e.isSimplePath=e.hasOnePath&&""==e[0]&&""==e[4],e.onlyOneTime=j,e.combinator=function(a){for(var b=e[0],c=1;c<e.length;c+=4){var d=e.hasOnePath?a:a[(c-1)/4];void 0!==d&&(b+=d),b+=e[c+3]}return b},e}}function t(a,b,c,d){if(b.hasOnePath){var e=b[3],f=e?e(d,c,!0):b[2].getValueFrom(d);return b.isSimplePath?f:b.combinator(f)}for(var g=[],h=1;h<b.length;h+=4){var e=b[h+2];g[(h-1)/4]=e?e(d,c):b[h+1].getValueFrom(d)}return b.combinator(g)}function u(a,b,c,d){var e=b[3],f=e?e(d,c,!1):new PathObserver(d,b[2]);return b.isSimplePath?f:new ObserverTransform(f,b.combinator)}function v(a,b,c,d){if(b.onlyOneTime)return t(a,b,c,d);if(b.hasOnePath)return u(a,b,c,d);for(var e=new CompoundObserver,f=1;f<b.length;f+=4){var g=b[f],h=b[f+2];if(h){var i=h(d,c,g);g?e.addPath(i):e.addObserver(i)}else{var j=b[f+1];g?e.addPath(j.getValueFrom(d)):e.addPath(d,j)}}return new ObserverTransform(e,b.combinator)}function w(a,b,c,d){for(var e=0;e<b.length;e+=2){var f=b[e],g=b[e+1],h=v(f,g,a,c),i=a.bind(f,h,g.onlyOneTime);i&&d&&d.push(i)}if(a.bindFinished(),b.isTemplate){a.model_=c;var j=a.processBindingDirectives_(b);d&&j&&d.push(j)}}function x(a,b,c){var d=a.getAttribute(b);return s(""==d?"{{}}":d,b,a,c)}function y(a,c){b(a);for(var d=[],e=0;e<a.attributes.length;e++){for(var f=a.attributes[e],g=f.name,i=f.value;"_"===g[0];)g=g.substring(1);if(!h(a)||g!==J&&g!==H&Line truncated
|
||||
b&&b.classList.remove(c),a&&a.classList.add(c)},injectBoundHTML:function(a,b){var c=document.createElement("template");c.innerHTML=a;var d=this.instanceTemplate(c);return b&&(b.textContent="",b.appendChild(d)),d}},c=function(){},d={};b.asyncMethod=b.async,a.api.instance.utils=b,a.nop=c,a.nob=d}(Polymer),function(a){var b=window.WebComponents?WebComponents.flags.log:{},c="on-",d={EVENT_PREFIX:c,addHostListeners:function(){var a=this.eventDelegates;b.events&&Object.keys(a).length>0&&console.log("[%s] addHostListeners:",this.localName,a);for(var c in a){var d=a[c];PolymerGestures.addEventListener(this,c,this.element.getEventHandler(this,this,d))}},dispatchMethod:function(a,c,d){if(a){b.events&&console.group("[%s] dispatch [%s]",a.localName,c);var e="function"==typeof c?c:a[c];e&&e[d?"apply":"call"](a,d),b.events&&console.groupEnd(),Polymer.flush()}}};a.api.instance.events=d,a.addEventListener=function(a,b,c,d){PolymerGestures.addEventListener(wrap(a),b,c,d)},a.removeEventListener=function(a,b,c,d){PolymerGestures.removeEventListener(wrap(a),b,c,d)}}(Polymer),function(a){var b={copyInstanceAttributes:function(){var a=this._instanceAttributes;for(var b in a)this.hasAttribute(b)||this.setAttribute(b,a[b])},takeAttributes:function(){if(this._publishLC)for(var a,b=0,c=this.attributes,d=c.length;(a=c[b])&&d>b;b++)this.attributeToProperty(a.name,a.value)},attributeToProperty:function(b,c){var b=this.propertyForAttribute(b);if(b){if(c&&c.search(a.bindPattern)>=0)return;var d=this[b],c=this.deserializeValue(c,d);c!==d&&(this[b]=c)}},propertyForAttribute:function(a){var b=this._publishLC&&this._publishLC[a];return b},deserializeValue:function(b,c){return a.deserializeValue(b,c)},serializeValue:function(a,b){return"boolean"===b?a?"":void 0:"object"!==b&&"function"!==b&&void 0!==a?a:void 0},reflectPropertyToAttribute:function(a){var b=typeof this[a],c=this.serializeValue(this[a],b);void 0!==c?this.setAttribute(a,c):"boolean"===b&&this.removeAttribute(a)}};a.api.instance.attributes=b}(Polymer),function(a){function b(a,b){return a===b?0!==a||1/a===1/b:f(a)&&f(b)?!0:a!==a&&b!==b}function c(a,b){return void 0===b&&null===a?b:null===b||void 0===b?a:b}var d=window.WebComponents?WebComponents.flags.log:{},e={object:void 0,type:"update",name:void 0,oldValue:void 0},f=Number.isNaN||function(a){return"number"==typeof a&&isNaN(a)},g={createPropertyObserver:function(){var a=this._observeNames;if(a&&a.length){var b=this._propertyObserver=new CompoundObserver(!0);this.registerObserver(b);for(var c,d=0,e=a.length;e>d&&(c=a[d]);d++)b.addPath(this,c),this.observeArrayValue(c,this[c],null)}},openPropertyObserver:function(){this._propertyObserver&&this._propertyObserver.open(this.notifyPropertyChanges,this)},notifyPropertyChanges:function(a,b,c){var d,e,f={};for(var g in b)if(d=c[2*g+1],e=this.observe[d]){var h=b[g],i=a[g];this.observeArrayValue(d,i,h),f[e]||(void 0!==h&&null!==h||void 0!==i&&null!==i)&&(f[e]=!0,this.invokeMethod(e,[h,i,arguments]))}},invokeMethod:function(a,b){var c=this[a]||a;"function"==typeof c&&c.apply(this,b)},deliverChanges:function(){this._propertyObserver&&this._propertyObserver.deliver()},observeArrayValue:function(a,b,c){var e=this.observe[a];if(e&&(Array.isArray(c)&&(d.observe&&console.log("[%s] observeArrayValue: unregister observer [%s]",this.localName,a),this.closeNamedObserver(a+"__array")),Array.isArray(b))){d.observe&&console.log("[%s] observeArrayValue: register observer [%s]",this.localName,a,b);var f=new ArrayObserver(b);f.open(function(a){this.invokeMethod(e,[a])},this),this.registerNamedObserver(a+"__array",f)}},emitPropertyChangeRecord:function(a,c,d){if(!b(c,d)&&(this._propertyChanged(a,c,d),Observer.hasObjectObserve)){var f=this._objectNotifier;f||(f=this._objectNotifier=Object.getNotifier(this)),e.object=this,e.name=a,e.oldValue=d,f.notify(e)}},_propertyChanged:function(a){this.reflect[a]&&this.reflectPropertyToAttribute(a)},bindProperty:function(a,b,d){if(d)return void(this[a]=b);var e=this.element.prototype.computed;if(e&&e[a]){var f=a+"ComputedBoundObservable_";return void(this[f]=b)}return this.bindToAccessor(a,b,c)},bindToAccessor:function(a,c,d){function e(b,c){j[f]=b;var d=j[h];d&&"function"==typeof d.setValue&&d.setValue(b),j.emitPropertyChangeRecord(a,b,c)}var f=a+"_",g=a+"Observable_",h=a+"ComputedBoundObservable_";this[g]=c;var i=this[f],j=this,k=c.open(e);if(d&&!b(i,k)){var l=d(i,k);b(k,l)||(k=l,c.setValue&&c.setValue(k))}e(k,i);var m={close:function(){c.close(),j[g]=void 0,j[h]=void 0}};return this.registerObserver(m),m},createComputedProperties:function(){if(this._computedNames)for(var a=0;a<this._computedNames.length;a++){var b=this._computedNames[a],c=this.computed[b];try{var d=PolymerExpressions.getExpression(c),e=d.getBinding(this,this.element.syntax);this.bindToAccessor(b,e)}catch(f){console.error("Failed to create computed property",f)}}},registerObserver:function(a){return this._observers?void this._observers.push(a):void(this._observers=[a])},closeObservers:function(){if(thiLine truncated
|
||||
b&&b.classList.remove(c),a&&a.classList.add(c)},injectBoundHTML:function(a,b){var c=document.createElement("template");c.innerHTML=a;var d=this.instanceTemplate(c);return b&&(b.textContent="",b.appendChild(d)),d}},c=function(){},d={};b.asyncMethod=b.async,a.api.instance.utils=b,a.nop=c,a.nob=d}(Polymer),function(a){var b=window.WebComponents?WebComponents.flags.log:{},c="on-",d={EVENT_PREFIX:c,addHostListeners:function(){var a=this.eventDelegates;b.events&&Object.keys(a).length>0&&console.log("[%s] addHostListeners:",this.localName,a);for(var c in a){var d=a[c];PolymerGestures.addEventListener(this,c,this.element.getEventHandler(this,this,d))}},dispatchMethod:function(a,c,d){if(a){b.events&&console.group("[%s] dispatch [%s]",a.localName,c);var e="function"==typeof c?c:a[c];e&&e[d?"apply":"call"](a,d),b.events&&console.groupEnd(),Polymer.flush()}}};a.api.instance.events=d,a.addEventListener=function(a,b,c,d){PolymerGestures.addEventListener(wrap(a),b,c,d)},a.removeEventListener=function(a,b,c,d){PolymerGestures.removeEventListener(wrap(a),b,c,d)}}(Polymer),function(a){var b={copyInstanceAttributes:function(){var a=this._instanceAttributes;for(var b in a)this.hasAttribute(b)||this.setAttribute(b,a[b])},takeAttributes:function(){if(this._publishLC)for(var a,b=0,c=this.attributes,d=c.length;(a=c[b])&&d>b;b++)this.attributeToProperty(a.name,a.value)},attributeToProperty:function(b,c){var b=this.propertyForAttribute(b);if(b){if(c&&c.search(a.bindPattern)>=0)return;var d=this[b],c=this.deserializeValue(c,d);c!==d&&(this[b]=c)}},propertyForAttribute:function(a){var b=this._publishLC&&this._publishLC[a];return b},deserializeValue:function(b,c){return a.deserializeValue(b,c)},serializeValue:function(a,b){return"boolean"===b?a?"":void 0:"object"!==b&&"function"!==b&&void 0!==a?a:void 0},reflectPropertyToAttribute:function(a){var b=typeof this[a],c=this.serializeValue(this[a],b);void 0!==c?this.setAttribute(a,c):"boolean"===b&&this.removeAttribute(a)}};a.api.instance.attributes=b}(Polymer),function(a){function b(a,b){return a===b?0!==a||1/a===1/b:f(a)&&f(b)?!0:a!==a&&b!==b}function c(a,b){return void 0===b&&null===a?b:null===b||void 0===b?a:b}var d=window.WebComponents?WebComponents.flags.log:{},e={object:void 0,type:"update",name:void 0,oldValue:void 0},f=Number.isNaN||function(a){return"number"==typeof a&&isNaN(a)},g={createPropertyObserver:function(){var a=this._observeNames;if(a&&a.length){var b=this._propertyObserver=new CompoundObserver(!0);this.registerObserver(b);for(var c,d=0,e=a.length;e>d&&(c=a[d]);d++)b.addPath(this,c),this.observeArrayValue(c,this[c],null)}},openPropertyObserver:function(){this._propertyObserver&&this._propertyObserver.open(this.notifyPropertyChanges,this)},notifyPropertyChanges:function(a,b,c){var d,e,f={};for(var g in b)if(d=c[2*g+1],e=this.observe[d]){var h=b[g],i=a[g];this.observeArrayValue(d,i,h),f[e]||(void 0!==h&&null!==h||void 0!==i&&null!==i)&&(f[e]=!0,this.invokeMethod(e,[h,i,arguments]))}},invokeMethod:function(a,b){var c=this[a]||a;"function"==typeof c&&c.apply(this,b)},deliverChanges:function(){this._propertyObserver&&this._propertyObserver.deliver()},observeArrayValue:function(a,b,c){var e=this.observe[a];if(e&&(Array.isArray(c)&&(d.observe&&console.log("[%s] observeArrayValue: unregister observer [%s]",this.localName,a),this.closeNamedObserver(a+"__array")),Array.isArray(b))){d.observe&&console.log("[%s] observeArrayValue: register observer [%s]",this.localName,a,b);var f=new ArrayObserver(b);f.open(function(a){this.invokeMethod(e,[a])},this),this.registerNamedObserver(a+"__array",f)}},emitPropertyChangeRecord:function(a,c,d){if(!b(c,d)&&(this._propertyChanged(a,c,d),Observer.hasObjectObserve)){var f=this._objectNotifier;f||(f=this._objectNotifier=Object.getNotifier(this)),e.object=this,e.name=a,e.oldValue=d,f.notify(e)}},_propertyChanged:function(a){this.reflect[a]&&this.reflectPropertyToAttribute(a)},bindProperty:function(a,b,d){if(d)return void(this[a]=b);var e=this.element.prototype.computed;if(e&&e[a]){var f=a+"ComputedBoundObservable_";return void(this[f]=b)}return this.bindToAccessor(a,b,c)},bindToAccessor:function(a,c,d){function e(b,c){j[f]=b;var d=j[h];d&&"function"==typeof d.setValue&&d.setValue(b),j.emitPropertyChangeRecord(a,b,c)}var f=a+"_",g=a+"Observable_",h=a+"ComputedBoundObservable_";this[g]=c;var i=this[f],j=this,k=c.open(e);if(d&&!b(i,k)){var l=d(i,k);b(k,l)||(k=l,c.setValue&&c.setValue(k))}e(k,i);var m={close:function(){c.close(),j[g]=void 0,j[h]=void 0}};return this.registerObserver(m),m},createComputedProperties:function(){if(this._computedNames)for(var a=0;a<this._computedNames.length;a++){var b=this._computedNames[a],c=this.computed[b];try{var d=PolymerExpressions.getExpression(c),e=d.getBinding(this,this.element.syntax);this.bindToAccessor(b,e)}catch(f){console.error("Failed to create computed property",f)}}},registerObserver:function(a){return this._observers?void this._observers.push(a):void(this._observers=[a])},closeObservers:function(){if(thiLine truncated
|
||||
|
||||
},ct.prototype.__iterate=function(t,e){var n=this,r=0;return this._iter.__iterate(function(e){return t(e,r++,n)},e)},ct.prototype.__iterator=function(t,e){var n=this._iter.__iterator(wn,e),r=0;return new T(function(){var e=n.next();return e.done?e:b(t,r++,e.value,e)})},t(ft,D),ft.prototype.has=function(t){return this._iter.includes(t)},ft.prototype.__iterate=function(t,e){var n=this;return this._iter.__iterate(function(e){return t(e,e,n)},e)},ft.prototype.__iterator=function(t,e){var n=this._iter.__iterator(wn,e);return new T(function(){var e=n.next();return e.done?e:b(t,e.value,e.value,e)})},t(lt,C),lt.prototype.entrySeq=function(){return this._iter.toSeq()},lt.prototype.__iterate=function(t,e){var n=this;return this._iter.__iterate(function(e){if(e){Ct(e);var r=d(e);return t(r?e.get(1):e[1],r?e.get(0):e[0],n)}},e)},lt.prototype.__iterator=function(t,e){var n=this._iter.__iterator(wn,e);return new T(function(){for(;;){var e=n.next();if(e.done)return e;var r=e.value;if(r){Ct(r);var i=d(r);return b(t,i?r.get(0):r[0],i?r.get(1):r[1],e)}}})},ct.prototype.cacheResult=st.prototype.cacheResult=ft.prototype.cacheResult=lt.prototype.cacheResult=Rt,t(zt,H),zt.prototype.toString=function(){return this.__toString("Map {","}")},zt.prototype.get=function(t,e){return this._root?this._root.get(0,void 0,t,e):e},zt.prototype.set=function(t,e){return Jt(this,t,e)},zt.prototype.setIn=function(t,e){return this.updateIn(t,hn,function(){return e})},zt.prototype.remove=function(t){return Jt(this,t,hn)},zt.prototype.deleteIn=function(t){return this.updateIn(t,function(){return hn})},zt.prototype.update=function(t,e,n){return 1===arguments.length?t(this):this.updateIn([t],e,n)},zt.prototype.updateIn=function(t,e,n){n||(n=e,e=void 0);var r=oe(this,Lt(t),e,n);return r===hn?void 0:r},zt.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):Bt()},zt.prototype.merge=function(){return ne(this,void 0,arguments)},zt.prototype.mergeWith=function(t){var e=an.call(arguments,1);return ne(this,t,e)},zt.prototype.mergeIn=function(t){var e=an.call(arguments,1);return this.updateIn(t,Bt(),function(t){return t.merge.apply(t,e)})},zt.prototype.mergeDeep=function(){return ne(this,re(void 0),arguments)},zt.prototype.mergeDeepWith=function(t){var e=an.call(arguments,1);return ne(this,re(t),e)},zt.prototype.mergeDeepIn=function(t){var e=an.call(arguments,1);return this.updateIn(t,Bt(),function(t){return t.mergeDeep.apply(t,e)})},zt.prototype.sort=function(t){return Ee(It(this,t))},zt.prototype.sortBy=function(t,e){return Ee(It(this,e,t))},zt.prototype.withMutations=function(t){var e=this.asMutable();return t(e),e.wasAltered()?e.__ensureOwner(this.__ownerID):this},zt.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new r)},zt.prototype.asImmutable=function(){return this.__ensureOwner()},zt.prototype.wasAltered=function(){return this.__altered},zt.prototype.__iterator=function(t,e){return new Kt(this,t,e)},zt.prototype.__iterate=function(t,e){var n=this,r=0;return this._root&&this._root.iterate(function(e){return r++,t(e[1],e[0],n)},e),r},zt.prototype.__ensureOwner=function(t){return t===this.__ownerID?this:t?Ft(this.size,this._root,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)},zt.isMap=Pt;var Pn="@@__IMMUTABLE_MAP__@@",qn=zt.prototype;qn[Pn]=!0,qn[sn]=qn.remove,qn.removeIn=qn.deleteIn,qt.prototype.get=function(t,e,n,r){for(var i=this.entries,o=0,u=i.length;u>o;o++)if(J(n,i[o][0]))return i[o][1];return r},qt.prototype.update=function(t,e,r,o,u,a,s){for(var c=u===hn,f=this.entries,l=0,h=f.length;h>l&&!J(o,f[l][0]);l++);var p=h>l;if(p?f[l][1]===u:c)return this;if(n(s),(c||!p)&&n(a),!c||1!==f.length){if(!p&&!c&&f.length>=Wn)return Qt(t,f,o,u);var _=t&&t===this.ownerID,v=_?f:i(f);return p?c?l===h-1?v.pop():v[l]=v.pop():v[l]=[o,u]:v.push([o,u]),_?(this.entries=v,this):new qt(t,v)}},Ut.prototype.get=function(t,e,n,r){void 0===e&&(e=et(n));var i=1<<((0===t?e:e>>>t)&ln),o=this.bitmap;return 0===(o&i)?r:this.nodes[ue(o&i-1)].get(t+cn,e,n,r)},Ut.prototype.update=function(t,e,n,r,i,o,u){void 0===n&&(n=et(r));var a=(0===e?n:n>>>e)&ln,s=1<<a,c=this.bitmap,f=0!==(c&s);if(!f&&i===hn)return this;var l=ue(c&s-1),h=this.nodes,p=f?h[l]:void 0,_=Yt(p,t,e+cn,n,r,i,o,u);if(_===p)return this;if(!f&&_&&h.length>=Vn)return ee(t,h,c,a,_);if(f&&!_&&2===h.length&&Xt(h[1^l]))return h[1^l];if(f&&_&&1===h.length&&Xt(_))return _;var v=t&&t===this.ownerID,d=f?_?c:c^s:c|s,y=f?_?ae(h,l,_,v):ce(h,l,v):se(h,l,_,v);return v?(this.bitmap=d,this.nodes=y,this):new Ut(t,d,y)},Wt.prototype.get=function(t,e,n,r){void 0===e&&(e=et(n));var i=(0===t?e:e>>>t)&ln,o=this.nodes[i];return o?o.get(t+cn,e,n,r):r},Wt.prototype.update=function(t,e,n,r,i,o,u){void 0===n&&(n=et(r));var a=(0===e?n:n>>>e)&ln,s=i===hn,c=this.nodes,f=c[a];if(s&&!f)return this;var l=Yt(f,t,e+cn,n,r,i,o,u);if(l===f)return this;var h=this.count;if(f){if(!l&&(h--,Gn>h))return te(t,c,h,a)}else h++;var p=t&&t===thLine truncated
|
||||
for(var n=-1,r=t.length,i=-1,o=[];++n<r;){var u=t[n];e(u,n,t)&&(o[++i]=u)}return o}function ae(t,e){for(var n=-1,r=t.length,i=So(r);++n<r;)i[n]=e(t[n],n,t);return i}function se(t){for(var e=-1,n=t.length,r=mu;++e<n;){var i=t[e];i>r&&(r=i)}return r}function ce(t){for(var e=-1,n=t.length,r=wu;++e<n;){var i=t[e];r>i&&(r=i)}return r}function fe(t,e,n,r){var i=-1,o=t.length;for(r&&o&&(n=t[++i]);++i<o;)n=e(n,t[i],i,t);return n}function le(t,e,n,r){var i=t.length;for(r&&i&&(n=t[--i]);i--;)n=e(n,t[i],i,t);return n}function he(t,e){for(var n=-1,r=t.length;++n<r;)if(e(t[n],n,t))return!0;return!1}function pe(t){for(var e=t.length,n=0;e--;)n+=+t[e]||0;return n}function _e(t,e){return t===A?e:t}function ve(t,e,n,r){return t!==A&&Wo.call(r,n)?t:e}function de(t,e,n){var r=ja(e);Qo.apply(r,Uu(e));for(var i=-1,o=r.length;++i<o;){var u=r[i],a=t[u],s=n(a,e[u],u,t,e);(s===s?s===a:a!==a)&&(a!==A||u in t)||(t[u]=s)}return t}function ye(t,e){for(var n=-1,r=t.length,i=Fn(r),o=e.length,u=So(o);++n<o;){var a=e[n];i?u[n]=Gn(a,r)?t[a]:A:u[n]=t[a]}return u}function ge(t,e,n){n||(n={});for(var r=-1,i=e.length;++r<i;){var o=e[r];n[o]=t[o]}return n}function me(t,e,n){var r=typeof t;return"function"==r?e===A?t:rn(t,e,n):null==t?ho:"object"==r?ze(t):e===A?mo(t):Pe(t,e)}function we(t,e,n,r,i,o,u){var a;if(n&&(a=i?n(t,r,i):n(t)),a!==A)return a;if(!Ti(t))return t;var s=Ea(t);if(s){if(a=qn(t),!e)return te(t,a)}else{var c=Go.call(t),f=c==Z;if(c!=et&&c!=F&&(!f||i))return $t[c]?Wn(t,c,e):i?t:{};if(a=Un(f?{}:t),!e)return ku(a,t)}o||(o=[]),u||(u=[]);for(var l=o.length;l--;)if(o[l]==t)return u[l];return o.push(t),u.push(a),(s?ee:ke)(t,function(r,i){a[i]=we(r,e,n,i,t,o,u)}),a}function Te(t,e,n){if("function"!=typeof t)throw new jo($);return ru(function(){t.apply(A,n)},e)}function be(t,e){var n=t?t.length:0,r=[];if(!n)return r;var i=-1,o=zn(),u=o==a,s=u&&e.length>=200?Lu(e):null,c=e.length;s&&(o=Zt,u=!1,e=s);t:for(;++i<n;){var f=t[i];if(u&&f===f){for(var l=c;l--;)if(e[l]===f)continue t;r.push(f)}else o(e,f,0)<0&&r.push(f)}return r}function Ee(t,e){var n=!0;return xu(t,function(t,r,i){return n=!!e(t,r,i)}),n}function Oe(t,e,n,r){var i=t.length;for(n=null==n?0:+n||0,0>n&&(n=-n>i?0:i+n),r=r===A||r>i?i:+r||0,0>r&&(r+=i),i=n>r?0:r>>>0,n>>>=0;i>n;)t[n++]=e;return t}function Ie(t,e){var n=[];return xu(t,function(t,r,i){e(t,r,i)&&n.push(t)}),n}function Se(t,e,n,r){var i;return n(t,function(t,n,o){return e(t,n,o)?(i=r?n:t,!1):void 0}),i}function Ae(t,e,n){for(var r=-1,i=t.length,o=-1,u=[];++r<i;){var a=t[r];if(m(a)&&Fn(a.length)&&(Ea(a)||_i(a))){e&&(a=Ae(a,e,n));var s=-1,c=a.length;for(u.length+=c;++s<c;)u[++o]=a[s]}else n||(u[++o]=a)}return u}function Ne(t,e){return Mu(t,e,Pi)}function ke(t,e){return Mu(t,e,ja)}function Ce(t,e){return Ru(t,e,ja)}function xe(t,e){for(var n=-1,r=e.length,i=-1,o=[];++n<r;){var u=e[n];Ia(t[u])&&(o[++i]=u)}return o}function De(t,e,n){if(null!=t){n!==A&&n in nr(t)&&(e=[n]);for(var r=-1,i=e.length;null!=t&&++r<i;)var o=t=t[e[r]];return o}}function Me(t,e,n,r,i,o){if(t===e)return 0!==t||1/t==1/e;var u=typeof t,a=typeof e;return"function"!=u&&"object"!=u&&"function"!=a&&"object"!=a||null==t||null==e?t!==t&&e!==e:Re(t,e,Me,n,r,i,o)}function Re(t,e,n,r,i,o,u){var a=Ea(t),s=Ea(e),c=B,f=B;a||(c=Go.call(t),c==F?c=et:c!=et&&(a=ki(t))),s||(f=Go.call(e),f==F?f=et:f!=et&&(s=ki(e)));var l=c==et,h=f==et,p=c==f;if(p&&!a&&!l)return Mn(t,e,c);if(!i){var _=l&&Wo.call(t,"__wrapped__"),v=h&&Wo.call(e,"__wrapped__");if(_||v)return n(_?t.value():t,v?e.value():e,r,i,o,u)}if(!p)return!1;o||(o=[]),u||(u=[]);for(var d=o.length;d--;)if(o[d]==t)return u[d]==e;o.push(t),u.push(e);var y=(a?Dn:Rn)(t,e,n,r,i,o,u);return o.pop(),u.pop(),y}function je(t,e,n,r,i){for(var o=-1,u=e.length,a=!i;++o<u;)if(a&&r[o]?n[o]!==t[e[o]]:!(e[o]in t))return!1;for(o=-1;++o<u;){var s=e[o],c=t[s],f=n[o];if(a&&r[o])var l=c!==A||s in t;else l=i?i(c,f,s):A,l===A&&(l=Me(f,c,i,!0));if(!l)return!1}return!0}function Le(t,e){var n=-1,r=qu(t),i=Fn(r)?So(r):[];return xu(t,function(t,r,o){i[++n]=e(t,r,o)}),i}function ze(t){var e=ja(t),n=e.length;if(!n)return lo(!0);if(1==n){var r=e[0],i=t[r];if(Bn(i))return function(t){return null==t?!1:t[r]===i&&(i!==A||r in nr(t))}}for(var o=So(n),u=So(n);n--;)i=t[e[n]],o[n]=i,u[n]=Bn(i);return function(t){return null!=t&&je(nr(t),e,o,u)}}function Pe(t,e){var n=Ea(t),r=$n(t)&&Bn(e),i=t+"";return t=rr(t),function(o){if(null==o)return!1;var u=i;if(o=nr(o),!(!n&&r||u in o)){if(o=1==t.length?o:De(o,He(t,0,-1)),null==o)return!1;u=gr(t),o=nr(o)}return o[u]===e?e!==A||u in o:Me(e,o[u],null,!0)}}function qe(t,e,n,r,i){if(!Ti(t))return t;var o=Fn(e.length)&&(Ea(e)||ki(e));if(!o){var u=ja(e);Qo.apply(u,Uu(e))}return ee(u||e,function(a,s){if(u&&(s=a,a=e[s]),m(a))r||(r=[]),i||(i=[]),Ue(t,e,s,qe,n,r,i);else{var c=t[s],f=n?n(c,a,s,t,e):A,l=f===A;l&&(f=a),!o&&f===A||!l&&(f===f?f===c:c!==c)||(t[s]=f)}}),t}function Ue(t,e,n,r,i,o,u){for(var a=o.length,s=e[n];a--;)if(o[a]==s)return void(t[n]=u[a]);var c=t[n],f=i?i(c,s,n,t,e):A,l=f===A;l&&(f=s,Fn(s.length)&&(Ea(s)||ki(s))?f=Ea(Line truncated
|
||||
try{var e=Oi(e=t.Float64Array)&&e,n=new e(new Ho(10),0,1)&&e}catch(r){}return n}(),su=function(){var t={1:0},e=tu&&Oi(e=Do.assign)&&e;try{e(tu(t),"xo")}catch(n){}return!t[1]&&e}(),cu=Oi(cu=So.isArray)&&cu,fu=Oi(fu=Do.create)&&fu,lu=t.isFinite,hu=Oi(hu=Do.keys)&&hu,pu=Co.max,_u=Co.min,vu=Oi(vu=Ao.now)&&vu,du=Oi(du=xo.isFinite)&&du,yu=t.parseInt,gu=Co.random,mu=xo.NEGATIVE_INFINITY,wu=xo.POSITIVE_INFINITY,Tu=Co.pow(2,32)-1,bu=Tu-1,Eu=Tu>>>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()}}(),xu=fn(ke),Du=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(xu),ta=yn(Du,!0),ea=Tn(ee,xu),na=Tn(ne,Du),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 xu(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,xu),sa=Sn(le,Du),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 xn(t,r,e,n,i)}),ha=si(function(t,e){e=e.length?Ae(e):Ri(t);for(var n=-1,r=e.length;++n<r;){var i=e[n];t[i]=xn(t[i],k,t)}return t}),pa=si(function(t,e,n){var r=k|C;if(n.length){var i=T(n,pa.placeholder);r|=R}return xn(e,r,t,n,i)}),_a=vn(D),va=vn(M),da=si(function(t,e){return Te(t,1,e)}),ya=si(function(t,e,n){return Te(t,e,n)}),ga=wn(),ma=wn(!0),wa=In(R),Ta=In(j),ba=si(function(t,e){return xn(t,z,null,null,null,Ae(e))}),Ea=cu||function(t){return m(t)&&Fn(t.length)&&Go.call(t)==B};Nu.dom||(yi=function(t){return!!t&&1===t.nodeType&&m(t)&&!Sa(t)});var Oa=du||function(t){return"number"==typeof t&&lu(t)},Ia=s(/x/)||ou&&!s(ou)?function(t){return Go.call(t)==Z}:s,Sa=Zo?function(t){if(!t||Go.call(t)!=et)return!1;var e=t.valueOf,n=Oi(e)&&(n=Zo(e))&&Zo(n);return n?t==n||Zo(t)==n:Qn(t)}:Qn,Aa=cn(function(t,e,n){return n?de(t,e,n):ku(t,e)}),Na=si(function(t){var e=t[0];return null==e?e:(t.push(_e),Aa.apply(A,t))}),ka=mn(ke),Ca=mn(Ce),xa=bn(Mu),Da=bn(Ru),Ma=En(ke),Ra=En(Ce),ja=hu?function(t){if(t)var e=t.constructor,n=t.length;return"function"==typeof e&&e.prototype===t||"function"!=typeof t&&Fn(n)?tr(t):Ti(t)?hu(t):[]}:tr,La=cn(qe),za=si(function(t,e){if(null==t)return{};if("function"!=typeof e[0]){var e=ae(Ae(e),Ro);return Yn(t,be(Pi(t),e))}var n=rn(e[0],e[1],3);return Xn(t,function(t,e,r){return!n(t,e,r)})}),Pa=si(function(t,e){return null==t?{}:"function"==typeof e[0]?Xn(t,rn(e[0],e[1],3)):Yn(t,Ae(e))}),qa=pn(function(t,e,n){return e=e.toLowerCase(),t+(n?e.charAt(0).toUpperCase()+e.slice(1):e)}),Ua=pn(function(t,e,n){return t+(n?"-":"")+e.toLowerCase()}),Wa=On(),Va=On(!0);8!=yu(Wt+"08")&&(to=function(t,e,n){return(n?Kn(t,e,n):null==e)?e=0:e&&(e=+e),t=io(t),yu(t,e||(jt.test(t)?16:10))});var Ga=pn(function(t,e,n){return t+(n?"_":"")+e.toLowerCase()}),Ka=pn(function(t,e,n){return t+(n?" ":"")+(e.charAt(0).toUpperCase()+e.slice(1))}),$a=si(function(t,e){try{return t.apply(A,e)}catch(n){return wi(n)?n:new No(n)}}),Ha=si(function(t,e){return function(n){return Vn(n,t,e)}}),Fa=si(function(t,e){return function(n){return Vn(t,n,e)}}),Ba=dn(Line truncated
|
||||
e}}(),c=function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(t.__proto__=e)};Object.defineProperty(e,"__esModule",{value:!0});var f=n(4),l=n(1),h=u(l),p=n(2),_=u(p),v=n(3),d=u(v),y=n(9),g=u(y),m=n(14),w=u(m),T=new f.Map,b=function(t){function e(){a(this,e),null!=t&&t.apply(this,arguments)}return c(e,t),s(e,[{key:"all",get:function(){return T.valueSeq().sortBy(r)}},{key:"get",value:function(t){return t=t.toLowerCase(),T.get(t)||null}},{key:"gets",value:function(t){return t=t.map(function(t){return t.toLowerCase()}),T.valueSeq().filter(function(e){return-1!==t.indexOf(e.entityId)}).sortBy(r)}},{key:"entityIDs",get:function(){return T.keySeq().sort()}},{key:"domains",get:function(){return T.keySeq().map(function(t){return t.split(".")[0]}).sort().toOrderedSet()}}]),e}(d["default"]),E=new b;E.dispatchToken=h["default"].register(function(t){switch(t.actionType){case _["default"].ACTION_NEW_STATES:(!g["default"].isStreaming||t.replace)&&(o(t.states,t.replace),E.emitChange());break;case _["default"].ACTION_REMOTE_EVENT_RECEIVED:t.event.event_type===_["default"].REMOTE_EVENT_STATE_CHANGED&&(i(t.event.data.new_state),E.emitChange());break;case _["default"].ACTION_LOG_OUT:T={},E.emitChange()}}),e["default"]=E,t.exports=e["default"]},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;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),u=function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(t.__proto__=e)};Object.defineProperty(e,"__esModule",{value:!0});var a=n(6),s=r(a),c=n(1),f=r(c),l=n(2),h=r(l),p=n(3),_=r(p),v=6e4,d=null,y={},g={},m=function(t){function e(){i(this,e),null!=t&&t.apply(this,arguments)}return u(e,t),o(e,[{key:"isStale",value:function(){var t=void 0===arguments[0]?null:arguments[0],e=null===t?d:y[t]||null;return null===e||(new Date).getTime()-e.getTime()>v}},{key:"get",value:function(t){return g[t]||null}},{key:"all",get:function(){return s["default"].values(g)}}]),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;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),s=function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(t.__proto__=e)};Object.defineProperty(e,"__esModule",{value:!0});var c=n(1),f=o(c),l=n(2),h=o(l),p=n(3),_=o(p),v=4,d=!1,y=[],g=function(t){function e(){u(this,e),null!=t&&t.apply(this,arguments)}return s(e,t),a(e,[{key:"isFetching",get:function(){return!i()}},{key:"initialLoadDone",get:function(){return d}},{key:"componentsLoaded",get:function(){return r(h["default"].ACTION_NEW_LOADED_COMPONENTS)}},{key:"eventsLoaded",get:function(){return r(h["default"].ACTION_NEW_EVENTS)}},{key:"servicesLoaded",get:function(){return r(h["default"].ACTION_NEW_SERVICES)}},{key:"statesLoaded",get:function(){return r(h["default"].ACTION_NEW_STATES)}}]),e}(_["default"]),m=new g;m.dispatchToken=f["default"].register(function(t){switch(t.actionType){case h["default"].ACTION_FETCH_ALL:y=[],m.emitChange();break;case h["default"].ACTION_NEW_LOADED_COMPONENTS:case h["default"].ACTION_NEW_EVENTS:case h["default"].ACTION_NEW_SERVICES:case h["default"].ACTION_NEW_STATES:r(t.actionType)||(y.push(t.actionType),d=d||i(),m.emitChange());break;case h["default"].ACTION_LOG_OUT:d=!1,y=[],m.emitChange()}}),e["default"]=m,t.exports=e["default"]},function(t,e,n){"use strict";var r=function(t){return t&&t.__esModule?t:{"default":t}},i=function(t,e)Line truncated
|
||||
},ct.prototype.__iterate=function(t,e){var n=this,r=0;return this._iter.__iterate(function(e){return t(e,r++,n)},e)},ct.prototype.__iterator=function(t,e){var n=this._iter.__iterator(wn,e),r=0;return new T(function(){var e=n.next();return e.done?e:b(t,r++,e.value,e)})},t(ft,x),ft.prototype.has=function(t){return this._iter.includes(t)},ft.prototype.__iterate=function(t,e){var n=this;return this._iter.__iterate(function(e){return t(e,e,n)},e)},ft.prototype.__iterator=function(t,e){var n=this._iter.__iterator(wn,e);return new T(function(){var e=n.next();return e.done?e:b(t,e.value,e.value,e)})},t(lt,C),lt.prototype.entrySeq=function(){return this._iter.toSeq()},lt.prototype.__iterate=function(t,e){var n=this;return this._iter.__iterate(function(e){if(e){Ct(e);var r=d(e);return t(r?e.get(1):e[1],r?e.get(0):e[0],n)}},e)},lt.prototype.__iterator=function(t,e){var n=this._iter.__iterator(wn,e);return new T(function(){for(;;){var e=n.next();if(e.done)return e;var r=e.value;if(r){Ct(r);var i=d(r);return b(t,i?r.get(0):r[0],i?r.get(1):r[1],e)}}})},ct.prototype.cacheResult=st.prototype.cacheResult=ft.prototype.cacheResult=lt.prototype.cacheResult=Rt,t(zt,H),zt.prototype.toString=function(){return this.__toString("Map {","}")},zt.prototype.get=function(t,e){return this._root?this._root.get(0,void 0,t,e):e},zt.prototype.set=function(t,e){return Jt(this,t,e)},zt.prototype.setIn=function(t,e){return this.updateIn(t,hn,function(){return e})},zt.prototype.remove=function(t){return Jt(this,t,hn)},zt.prototype.deleteIn=function(t){return this.updateIn(t,function(){return hn})},zt.prototype.update=function(t,e,n){return 1===arguments.length?t(this):this.updateIn([t],e,n)},zt.prototype.updateIn=function(t,e,n){n||(n=e,e=void 0);var r=oe(this,Lt(t),e,n);return r===hn?void 0:r},zt.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):Bt()},zt.prototype.merge=function(){return ne(this,void 0,arguments)},zt.prototype.mergeWith=function(t){var e=an.call(arguments,1);return ne(this,t,e)},zt.prototype.mergeIn=function(t){var e=an.call(arguments,1);return this.updateIn(t,Bt(),function(t){return t.merge.apply(t,e)})},zt.prototype.mergeDeep=function(){return ne(this,re(void 0),arguments)},zt.prototype.mergeDeepWith=function(t){var e=an.call(arguments,1);return ne(this,re(t),e)},zt.prototype.mergeDeepIn=function(t){var e=an.call(arguments,1);return this.updateIn(t,Bt(),function(t){return t.mergeDeep.apply(t,e)})},zt.prototype.sort=function(t){return Ee(It(this,t))},zt.prototype.sortBy=function(t,e){return Ee(It(this,e,t))},zt.prototype.withMutations=function(t){var e=this.asMutable();return t(e),e.wasAltered()?e.__ensureOwner(this.__ownerID):this},zt.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new r)},zt.prototype.asImmutable=function(){return this.__ensureOwner()},zt.prototype.wasAltered=function(){return this.__altered},zt.prototype.__iterator=function(t,e){return new Kt(this,t,e)},zt.prototype.__iterate=function(t,e){var n=this,r=0;return this._root&&this._root.iterate(function(e){return r++,t(e[1],e[0],n)},e),r},zt.prototype.__ensureOwner=function(t){return t===this.__ownerID?this:t?Ft(this.size,this._root,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)},zt.isMap=Pt;var Pn="@@__IMMUTABLE_MAP__@@",qn=zt.prototype;qn[Pn]=!0,qn[sn]=qn.remove,qn.removeIn=qn.deleteIn,qt.prototype.get=function(t,e,n,r){for(var i=this.entries,o=0,u=i.length;u>o;o++)if(J(n,i[o][0]))return i[o][1];return r},qt.prototype.update=function(t,e,r,o,u,a,s){for(var c=u===hn,f=this.entries,l=0,h=f.length;h>l&&!J(o,f[l][0]);l++);var p=h>l;if(p?f[l][1]===u:c)return this;if(n(s),(c||!p)&&n(a),!c||1!==f.length){if(!p&&!c&&f.length>=Wn)return Qt(t,f,o,u);var _=t&&t===this.ownerID,v=_?f:i(f);return p?c?l===h-1?v.pop():v[l]=v.pop():v[l]=[o,u]:v.push([o,u]),_?(this.entries=v,this):new qt(t,v)}},Ut.prototype.get=function(t,e,n,r){void 0===e&&(e=et(n));var i=1<<((0===t?e:e>>>t)&ln),o=this.bitmap;return 0===(o&i)?r:this.nodes[ue(o&i-1)].get(t+cn,e,n,r)},Ut.prototype.update=function(t,e,n,r,i,o,u){void 0===n&&(n=et(r));var a=(0===e?n:n>>>e)&ln,s=1<<a,c=this.bitmap,f=0!==(c&s);if(!f&&i===hn)return this;var l=ue(c&s-1),h=this.nodes,p=f?h[l]:void 0,_=Yt(p,t,e+cn,n,r,i,o,u);if(_===p)return this;if(!f&&_&&h.length>=Vn)return ee(t,h,c,a,_);if(f&&!_&&2===h.length&&Xt(h[1^l]))return h[1^l];if(f&&_&&1===h.length&&Xt(_))return _;var v=t&&t===this.ownerID,d=f?_?c:c^s:c|s,y=f?_?ae(h,l,_,v):ce(h,l,v):se(h,l,_,v);return v?(this.bitmap=d,this.nodes=y,this):new Ut(t,d,y)},Wt.prototype.get=function(t,e,n,r){void 0===e&&(e=et(n));var i=(0===t?e:e>>>t)&ln,o=this.nodes[i];return o?o.get(t+cn,e,n,r):r},Wt.prototype.update=function(t,e,n,r,i,o,u){void 0===n&&(n=et(r));var a=(0===e?n:n>>>e)&ln,s=i===hn,c=this.nodes,f=c[a];if(s&&!f)return this;var l=Yt(f,t,e+cn,n,r,i,o,u);if(l===f)return this;var h=this.count;if(f){if(!l&&(h--,Gn>h))return te(t,c,h,a)}else h++;var p=t&&t===thLine truncated
|
||||
for(var n=-1,r=t.length,i=-1,o=[];++n<r;){var u=t[n];e(u,n,t)&&(o[++i]=u)}return o}function ae(t,e){for(var n=-1,r=t.length,i=So(r);++n<r;)i[n]=e(t[n],n,t);return i}function se(t){for(var e=-1,n=t.length,r=mu;++e<n;){var i=t[e];i>r&&(r=i)}return r}function ce(t){for(var e=-1,n=t.length,r=wu;++e<n;){var i=t[e];r>i&&(r=i)}return r}function fe(t,e,n,r){var i=-1,o=t.length;for(r&&o&&(n=t[++i]);++i<o;)n=e(n,t[i],i,t);return n}function le(t,e,n,r){var i=t.length;for(r&&i&&(n=t[--i]);i--;)n=e(n,t[i],i,t);return n}function he(t,e){for(var n=-1,r=t.length;++n<r;)if(e(t[n],n,t))return!0;return!1}function pe(t){for(var e=t.length,n=0;e--;)n+=+t[e]||0;return n}function _e(t,e){return t===A?e:t}function ve(t,e,n,r){return t!==A&&Wo.call(r,n)?t:e}function de(t,e,n){var r=ja(e);Qo.apply(r,Uu(e));for(var i=-1,o=r.length;++i<o;){var u=r[i],a=t[u],s=n(a,e[u],u,t,e);(s===s?s===a:a!==a)&&(a!==A||u in t)||(t[u]=s)}return t}function ye(t,e){for(var n=-1,r=t.length,i=Fn(r),o=e.length,u=So(o);++n<o;){var a=e[n];i?u[n]=Gn(a,r)?t[a]:A:u[n]=t[a]}return u}function ge(t,e,n){n||(n={});for(var r=-1,i=e.length;++r<i;){var o=e[r];n[o]=t[o]}return n}function me(t,e,n){var r=typeof t;return"function"==r?e===A?t:rn(t,e,n):null==t?ho:"object"==r?ze(t):e===A?mo(t):Pe(t,e)}function we(t,e,n,r,i,o,u){var a;if(n&&(a=i?n(t,r,i):n(t)),a!==A)return a;if(!Ti(t))return t;var s=Ea(t);if(s){if(a=qn(t),!e)return te(t,a)}else{var c=Go.call(t),f=c==Z;if(c!=et&&c!=F&&(!f||i))return $t[c]?Wn(t,c,e):i?t:{};if(a=Un(f?{}:t),!e)return ku(a,t)}o||(o=[]),u||(u=[]);for(var l=o.length;l--;)if(o[l]==t)return u[l];return o.push(t),u.push(a),(s?ee:ke)(t,function(r,i){a[i]=we(r,e,n,i,t,o,u)}),a}function Te(t,e,n){if("function"!=typeof t)throw new jo($);return ru(function(){t.apply(A,n)},e)}function be(t,e){var n=t?t.length:0,r=[];if(!n)return r;var i=-1,o=zn(),u=o==a,s=u&&e.length>=200?Lu(e):null,c=e.length;s&&(o=Zt,u=!1,e=s);t:for(;++i<n;){var f=t[i];if(u&&f===f){for(var l=c;l--;)if(e[l]===f)continue t;r.push(f)}else o(e,f,0)<0&&r.push(f)}return r}function Ee(t,e){var n=!0;return Du(t,function(t,r,i){return n=!!e(t,r,i)}),n}function Oe(t,e,n,r){var i=t.length;for(n=null==n?0:+n||0,0>n&&(n=-n>i?0:i+n),r=r===A||r>i?i:+r||0,0>r&&(r+=i),i=n>r?0:r>>>0,n>>>=0;i>n;)t[n++]=e;return t}function Ie(t,e){var n=[];return Du(t,function(t,r,i){e(t,r,i)&&n.push(t)}),n}function Se(t,e,n,r){var i;return n(t,function(t,n,o){return e(t,n,o)?(i=r?n:t,!1):void 0}),i}function Ae(t,e,n){for(var r=-1,i=t.length,o=-1,u=[];++r<i;){var a=t[r];if(m(a)&&Fn(a.length)&&(Ea(a)||_i(a))){e&&(a=Ae(a,e,n));var s=-1,c=a.length;for(u.length+=c;++s<c;)u[++o]=a[s]}else n||(u[++o]=a)}return u}function Ne(t,e){return Mu(t,e,Pi)}function ke(t,e){return Mu(t,e,ja)}function Ce(t,e){return Ru(t,e,ja)}function De(t,e){for(var n=-1,r=e.length,i=-1,o=[];++n<r;){var u=e[n];Ia(t[u])&&(o[++i]=u)}return o}function xe(t,e,n){if(null!=t){n!==A&&n in nr(t)&&(e=[n]);for(var r=-1,i=e.length;null!=t&&++r<i;)var o=t=t[e[r]];return o}}function Me(t,e,n,r,i,o){if(t===e)return 0!==t||1/t==1/e;var u=typeof t,a=typeof e;return"function"!=u&&"object"!=u&&"function"!=a&&"object"!=a||null==t||null==e?t!==t&&e!==e:Re(t,e,Me,n,r,i,o)}function Re(t,e,n,r,i,o,u){var a=Ea(t),s=Ea(e),c=B,f=B;a||(c=Go.call(t),c==F?c=et:c!=et&&(a=ki(t))),s||(f=Go.call(e),f==F?f=et:f!=et&&(s=ki(e)));var l=c==et,h=f==et,p=c==f;if(p&&!a&&!l)return Mn(t,e,c);if(!i){var _=l&&Wo.call(t,"__wrapped__"),v=h&&Wo.call(e,"__wrapped__");if(_||v)return n(_?t.value():t,v?e.value():e,r,i,o,u)}if(!p)return!1;o||(o=[]),u||(u=[]);for(var d=o.length;d--;)if(o[d]==t)return u[d]==e;o.push(t),u.push(e);var y=(a?xn:Rn)(t,e,n,r,i,o,u);return o.pop(),u.pop(),y}function je(t,e,n,r,i){for(var o=-1,u=e.length,a=!i;++o<u;)if(a&&r[o]?n[o]!==t[e[o]]:!(e[o]in t))return!1;for(o=-1;++o<u;){var s=e[o],c=t[s],f=n[o];if(a&&r[o])var l=c!==A||s in t;else l=i?i(c,f,s):A,l===A&&(l=Me(f,c,i,!0));if(!l)return!1}return!0}function Le(t,e){var n=-1,r=qu(t),i=Fn(r)?So(r):[];return Du(t,function(t,r,o){i[++n]=e(t,r,o)}),i}function ze(t){var e=ja(t),n=e.length;if(!n)return lo(!0);if(1==n){var r=e[0],i=t[r];if(Bn(i))return function(t){return null==t?!1:t[r]===i&&(i!==A||r in nr(t))}}for(var o=So(n),u=So(n);n--;)i=t[e[n]],o[n]=i,u[n]=Bn(i);return function(t){return null!=t&&je(nr(t),e,o,u)}}function Pe(t,e){var n=Ea(t),r=$n(t)&&Bn(e),i=t+"";return t=rr(t),function(o){if(null==o)return!1;var u=i;if(o=nr(o),!(!n&&r||u in o)){if(o=1==t.length?o:xe(o,He(t,0,-1)),null==o)return!1;u=gr(t),o=nr(o)}return o[u]===e?e!==A||u in o:Me(e,o[u],null,!0)}}function qe(t,e,n,r,i){if(!Ti(t))return t;var o=Fn(e.length)&&(Ea(e)||ki(e));if(!o){var u=ja(e);Qo.apply(u,Uu(e))}return ee(u||e,function(a,s){if(u&&(s=a,a=e[s]),m(a))r||(r=[]),i||(i=[]),Ue(t,e,s,qe,n,r,i);else{var c=t[s],f=n?n(c,a,s,t,e):A,l=f===A;l&&(f=a),!o&&f===A||!l&&(f===f?f===c:c!==c)||(t[s]=f)}}),t}function Ue(t,e,n,r,i,o,u){for(var a=o.length,s=e[n];a--;)if(o[a]==s)return void(t[n]=u[a]);var c=t[n],f=i?i(c,s,n,t,e):A,l=f===A;l&&(f=s,Fn(s.length)&&(Ea(s)||ki(s))?f=Ea(Line truncated
|
||||
try{var e=Oi(e=t.Float64Array)&&e,n=new e(new Ho(10),0,1)&&e}catch(r){}return n}(),su=function(){var t={1:0},e=tu&&Oi(e=xo.assign)&&e;try{e(tu(t),"xo")}catch(n){}return!t[1]&&e}(),cu=Oi(cu=So.isArray)&&cu,fu=Oi(fu=xo.create)&&fu,lu=t.isFinite,hu=Oi(hu=xo.keys)&&hu,pu=Co.max,_u=Co.min,vu=Oi(vu=Ao.now)&&vu,du=Oi(du=Do.isFinite)&&du,yu=t.parseInt,gu=Co.random,mu=Do.NEGATIVE_INFINITY,wu=Do.POSITIVE_INFINITY,Tu=Co.pow(2,32)-1,bu=Tu-1,Eu=Tu>>>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;++n<r;){var i=e[n];t[i]=Dn(t[i],k,t)}return t}),pa=si(function(t,e,n){var r=k|C;if(n.length){var i=T(n,pa.placeholder);r|=R}return Dn(e,r,t,n,i)}),_a=vn(x),va=vn(M),da=si(function(t,e){return Te(t,1,e)}),ya=si(function(t,e,n){return Te(t,e,n)}),ga=wn(),ma=wn(!0),wa=In(R),Ta=In(j),ba=si(function(t,e){return Dn(t,z,null,null,null,Ae(e))}),Ea=cu||function(t){return m(t)&&Fn(t.length)&&Go.call(t)==B};Nu.dom||(yi=function(t){return!!t&&1===t.nodeType&&m(t)&&!Sa(t)});var Oa=du||function(t){return"number"==typeof t&&lu(t)},Ia=s(/x/)||ou&&!s(ou)?function(t){return Go.call(t)==Z}:s,Sa=Zo?function(t){if(!t||Go.call(t)!=et)return!1;var e=t.valueOf,n=Oi(e)&&(n=Zo(e))&&Zo(n);return n?t==n||Zo(t)==n:Qn(t)}:Qn,Aa=cn(function(t,e,n){return n?de(t,e,n):ku(t,e)}),Na=si(function(t){var e=t[0];return null==e?e:(t.push(_e),Aa.apply(A,t))}),ka=mn(ke),Ca=mn(Ce),Da=bn(Mu),xa=bn(Ru),Ma=En(ke),Ra=En(Ce),ja=hu?function(t){if(t)var e=t.constructor,n=t.length;return"function"==typeof e&&e.prototype===t||"function"!=typeof t&&Fn(n)?tr(t):Ti(t)?hu(t):[]}:tr,La=cn(qe),za=si(function(t,e){if(null==t)return{};if("function"!=typeof e[0]){var e=ae(Ae(e),Ro);return Yn(t,be(Pi(t),e))}var n=rn(e[0],e[1],3);return Xn(t,function(t,e,r){return!n(t,e,r)})}),Pa=si(function(t,e){return null==t?{}:"function"==typeof e[0]?Xn(t,rn(e[0],e[1],3)):Yn(t,Ae(e))}),qa=pn(function(t,e,n){return e=e.toLowerCase(),t+(n?e.charAt(0).toUpperCase()+e.slice(1):e)}),Ua=pn(function(t,e,n){return t+(n?"-":"")+e.toLowerCase()}),Wa=On(),Va=On(!0);8!=yu(Wt+"08")&&(to=function(t,e,n){return(n?Kn(t,e,n):null==e)?e=0:e&&(e=+e),t=io(t),yu(t,e||(jt.test(t)?16:10))});var Ga=pn(function(t,e,n){return t+(n?"_":"")+e.toLowerCase()}),Ka=pn(function(t,e,n){return t+(n?" ":"")+(e.charAt(0).toUpperCase()+e.slice(1))}),$a=si(function(t,e){try{return t.apply(A,e)}catch(n){return wi(n)?n:new No(n)}}),Ha=si(function(t,e){return function(n){return Vn(n,t,e)}}),Fa=si(function(t,e){return function(n){return Vn(t,n,e)}}),Ba=dn(Line truncated
|
||||
e}}(),c=function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(t.__proto__=e)};Object.defineProperty(e,"__esModule",{value:!0});var f=n(4),l=n(1),h=u(l),p=n(2),_=u(p),v=n(3),d=u(v),y=n(9),g=u(y),m=n(14),w=u(m),T=new f.Map,b=function(t){function e(){a(this,e),null!=t&&t.apply(this,arguments)}return c(e,t),s(e,[{key:"all",get:function(){return T.valueSeq().sortBy(r)}},{key:"get",value:function(t){return t=t.toLowerCase(),T.get(t)||null}},{key:"gets",value:function(t){return t=t.map(function(t){return t.toLowerCase()}),T.valueSeq().filter(function(e){return-1!==t.indexOf(e.entityId)}).sortBy(r)}},{key:"entityIDs",get:function(){return T.keySeq().sort()}},{key:"domains",get:function(){return T.keySeq().map(function(t){return t.split(".")[0]}).sort().toOrderedSet()}}]),e}(d["default"]),E=new b;E.dispatchToken=h["default"].register(function(t){switch(t.actionType){case _["default"].ACTION_NEW_STATES:(!g["default"].isStreaming||t.replace)&&(o(t.states,t.replace),E.emitChange());break;case _["default"].ACTION_REMOTE_EVENT_RECEIVED:t.event.event_type===_["default"].REMOTE_EVENT_STATE_CHANGED&&(i(t.event.data.new_state),E.emitChange());break;case _["default"].ACTION_LOG_OUT:T={},E.emitChange()}}),e["default"]=E,t.exports=e["default"]},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;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),u=function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(t.__proto__=e)};Object.defineProperty(e,"__esModule",{value:!0});var a=n(6),s=r(a),c=n(1),f=r(c),l=n(2),h=r(l),p=n(3),_=r(p),v=6e4,d=null,y={},g={},m=function(t){function e(){i(this,e),null!=t&&t.apply(this,arguments)}return u(e,t),o(e,[{key:"isStale",value:function(){var t=void 0===arguments[0]?null:arguments[0],e=null===t?d:y[t]||null;return null===e||(new Date).getTime()-e.getTime()>v}},{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;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),s=function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(t.__proto__=e)};Object.defineProperty(e,"__esModule",{value:!0});var c=n(1),f=o(c),l=n(2),h=o(l),p=n(3),_=o(p),v=4,d=!1,y=[],g=function(t){function e(){u(this,e),null!=t&&t.apply(this,arguments)}return s(e,t),a(e,[{key:"isFetching",get:function(){return!i()}},{key:"initialLoadDone",get:function(){return d}},{key:"componentsLoaded",get:function(){return r(h["default"].ACTION_NEW_LOADED_COMPONENTS)}},{key:"eventsLoaded",get:function(){return r(h["default"].ACTION_NEW_EVENTS)}},{key:"servicesLoaded",get:function(){return r(h["default"].ACTION_NEW_SERVICES)}},{key:"statesLoaded",get:function(){return r(h["default"].ACTION_NEW_STATES)}}]),e}(_["default"]),m=new g;m.dispatchToken=f["default"].register(function(t){switch(t.actionType){case h["default"].ACTION_FETCH_ALL:y=[],m.emitChange();break;case h["default"].ACTION_NEW_LOADED_COMPONENTS:case h["default"].ACTION_NEW_EVENTS:case h["default"].ACTION_NEW_SERVICES:case h["default"].ACTION_NEW_STATES:r(t.actionType)||(y.push(t.actionType),d=d||i(),m.emitChange());break;case h["default"].ACTION_LOG_OUT:d=!1,y=[],m.emitChange()}}),e["default"]=m,t.exports=e["default"]},function(t,e,n){"use strict";var r=function(t){Line truncated
|
||||
|
||||
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(0<m.year()&&m.year()<=9999){if("function"===typeof Date.prototype.toISOString){return this.toDate().toISOString()}else{return formatMoment(m,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}}else{return formatMoment(m,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}},toArray:function(){var m=this;return[m.year(),m.month(),m.date(),m.hours(),m.minutes(),m.seconds(),m.milliseconds()]},isValid:function(){return isValid(this)},isDSTShifted:function(){if(this._a){return this.isValid()&&compareArrays(this._a,(this._isUTC?moment.utc(this._a):moment(this._a)).toArray())>0}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,inputSLine truncated
|
||||
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(0<m.year()&&m.year()<=9999){if("function"===typeof Date.prototype.toISOString){return this.toDate().toISOString()}else{return formatMoment(m,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}}else{return formatMoment(m,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}},toArray:function(){var m=this;return[m.year(),m.month(),m.date(),m.hours(),m.minutes(),m.seconds(),m.milliseconds()]},isValid:function(){return isValid(this)},isDSTShifted:function(){if(this._a){return this.isValid()&&compareArrays(this._a,(this._isUTC?moment.utc(this._a):moment(this._a)).toArray())>0}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,inputSLine truncated
|
||||
@@ -8,16 +8,17 @@
|
||||
</template>
|
||||
<script>
|
||||
(function() {
|
||||
var timeFormatOptions = {hour: 'numeric', minute: '2-digit'};
|
||||
var uiUtil = window.hass.uiUtil;
|
||||
|
||||
Polymer({
|
||||
time: "",
|
||||
|
||||
dateObjChanged: function(oldVal, newVal) {
|
||||
if (!newVal) {
|
||||
if (newVal) {
|
||||
this.time = uiUtil.formatTime(newVal);
|
||||
} else {
|
||||
this.time = "";
|
||||
}
|
||||
|
||||
this.time = newVal.toLocaleTimeString([], timeFormatOptions);
|
||||
},
|
||||
});
|
||||
})();
|
||||
|
||||
+9
-2
@@ -2,7 +2,7 @@
|
||||
|
||||
<link rel="import" href="../resources/moment-js.html">
|
||||
|
||||
<polymer-element name="relative-ha-datetime" attributes="datetime">
|
||||
<polymer-element name="relative-ha-datetime" attributes="datetime datetimeObj">
|
||||
<template>
|
||||
{{ relativeTime }}
|
||||
</template>
|
||||
@@ -34,8 +34,15 @@
|
||||
this.updateRelative();
|
||||
},
|
||||
|
||||
datetimeObjChanged: function(oldVal, newVal) {
|
||||
this.parsedDateTime = newVal;
|
||||
|
||||
this.updateRelative();
|
||||
},
|
||||
|
||||
updateRelative: function() {
|
||||
this.relativeTime = this.parsedDateTime ? moment(this.parsedDateTime).fromNow() : "";
|
||||
this.relativeTime = this.parsedDateTime ?
|
||||
moment(this.parsedDateTime).fromNow() : "";
|
||||
},
|
||||
});
|
||||
})();
|
||||
|
||||
@@ -37,8 +37,8 @@
|
||||
</div>
|
||||
|
||||
<div class="time-ago">
|
||||
<core-tooltip label="{{stateObj.lastChanged}}" position="bottom">
|
||||
<relative-ha-datetime datetime="{{stateObj.lastChanged}}"></relative-ha-datetime>
|
||||
<core-tooltip label="{{stateObj.lastChangedAsDate | formatDateTime}}" position="bottom">
|
||||
<relative-ha-datetime datetimeObj="{{stateObj.lastChangedAsDate}}"></relative-ha-datetime>
|
||||
</core-tooltip>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -11,38 +11,43 @@
|
||||
|
||||
<div layout justified horizontal class='data-entry' id='rising'>
|
||||
<div class='key'>
|
||||
Rising <relative-ha-datetime datetime="{{stateObj.attributes.next_rising}}"></relative-ha-datetime>
|
||||
Rising <relative-ha-datetime datetimeObj="{{rising}}"></relative-ha-datetime>
|
||||
</div>
|
||||
<div class='value'>
|
||||
{{stateObj.attributes.next_rising | HATimeStripDate}}
|
||||
{{rising | formatTime}}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div layout justified horizontal class='data-entry' id='setting'>
|
||||
<div class='key'>
|
||||
Setting <relative-ha-datetime datetime="{{stateObj.attributes.next_setting}}"></relative-ha-datetime>
|
||||
Setting <relative-ha-datetime datetimeObj="{{setting}}"></relative-ha-datetime>
|
||||
</div>
|
||||
<div class='value'>
|
||||
{{stateObj.attributes.next_setting | HATimeStripDate}}
|
||||
{{setting | formatTime}}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
<script>
|
||||
(function() {
|
||||
var parseDateTime = window.hass.util.parseDateTime;
|
||||
|
||||
Polymer({
|
||||
stateObjChanged: function() {
|
||||
var rising = parseDateTime(this.stateObj.attributes.next_rising);
|
||||
var setting = parseDateTime(this.stateObj.attributes.next_setting);
|
||||
rising: null,
|
||||
setting: null,
|
||||
|
||||
if(rising > setting) {
|
||||
stateObjChanged: function() {
|
||||
this.rising = parseDateTime(this.stateObj.attributes.next_rising);
|
||||
this.setting = parseDateTime(this.stateObj.attributes.next_setting);
|
||||
|
||||
if(self.rising > self.setting) {
|
||||
this.$.sunData.appendChild(this.$.rising);
|
||||
} else {
|
||||
this.$.sunData.appendChild(this.$.setting);
|
||||
}
|
||||
}
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</polymer-element>
|
||||
+2
-12
@@ -7,18 +7,6 @@
|
||||
'light', 'group', 'sun', 'configurator', 'thermostat', 'script'
|
||||
];
|
||||
|
||||
// Register some polymer filters
|
||||
|
||||
PolymerExpressions.prototype.HATimeToDate = function(timeString) {
|
||||
if (!timeString) return;
|
||||
|
||||
return window.hass.util.parseDateTime(timeString);
|
||||
};
|
||||
|
||||
PolymerExpressions.prototype.HATimeStripDate = function(timeString) {
|
||||
return (timeString || "").split(' ')[0];
|
||||
};
|
||||
|
||||
// Add some frontend specific helpers to the models
|
||||
Object.defineProperties(window.hass.stateModel.prototype, {
|
||||
// how to render the card for this state
|
||||
@@ -81,3 +69,5 @@
|
||||
window.hass.uiUtil = {};
|
||||
})();
|
||||
</script>
|
||||
|
||||
<link rel="import" href="./moment-js.html">
|
||||
@@ -3,3 +3,22 @@
|
||||
-->
|
||||
|
||||
<script src="../bower_components/moment/moment.js"></script>
|
||||
|
||||
<script>
|
||||
window.hass.uiUtil.formatTime = function(dateObj) {
|
||||
return moment(dateObj).format('LT');
|
||||
};
|
||||
|
||||
window.hass.uiUtil.formatDateTime = function(dateObj) {
|
||||
return moment(dateObj).format('lll');
|
||||
};
|
||||
|
||||
window.hass.uiUtil.formatDate = function(dateObj) {
|
||||
return moment(dateObj).format('ll');
|
||||
};
|
||||
|
||||
PolymerExpressions.prototype.formatTime = window.hass.uiUtil.formatTime;
|
||||
PolymerExpressions.prototype.formatDateTime = window.hass.uiUtil.formatDateTime;
|
||||
PolymerExpressions.prototype.formatDate = window.hass.uiUtil.formatDate;
|
||||
|
||||
</script>
|
||||
@@ -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'
|
||||
@@ -22,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, ))
|
||||
@@ -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')
|
||||
|
||||
|
||||
@@ -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().replace(hour=0, minute=0, second=0)
|
||||
|
||||
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,
|
||||
|
||||
@@ -10,11 +10,11 @@ import threading
|
||||
import queue
|
||||
import sqlite3
|
||||
from datetime import datetime, date
|
||||
import time
|
||||
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 +60,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 +73,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 +114,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 +167,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. """
|
||||
@@ -187,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:
|
||||
@@ -197,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
|
||||
@@ -209,31 +214,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. """
|
||||
@@ -262,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)
|
||||
@@ -282,7 +293,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)
|
||||
|
||||
@@ -297,7 +308,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,
|
||||
@@ -306,7 +317,7 @@ class Recorder(threading.Thread):
|
||||
created integer)
|
||||
""")
|
||||
|
||||
cur.execute("""
|
||||
self.query("""
|
||||
CREATE TABLE events (
|
||||
event_id integer primary key,
|
||||
event_type text,
|
||||
@@ -314,10 +325,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,
|
||||
@@ -327,20 +338,44 @@ 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
|
||||
|
||||
self.query("""
|
||||
ALTER TABLE recorder_runs
|
||||
ADD COLUMN utc_offset integer
|
||||
""")
|
||||
|
||||
self.query("""
|
||||
ALTER TABLE events
|
||||
ADD COLUMN utc_offset integer
|
||||
""")
|
||||
|
||||
self.query("""
|
||||
ALTER TABLE states
|
||||
ADD COLUMN utc_offset integer
|
||||
""")
|
||||
|
||||
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)
|
||||
|
||||
def _close_connection(self):
|
||||
""" Close connection to the database. """
|
||||
_LOGGER.info("Closing database")
|
||||
@@ -357,18 +392,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 date_util.as_utc(datetimestamp.replace(microsecond=0)).timestamp()
|
||||
|
||||
|
||||
def _verify_instance():
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
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.now(pytz.utc)
|
||||
|
||||
|
||||
def now(time_zone=None):
|
||||
""" Get now in specified time zone. """
|
||||
return dt.datetime.now(time_zone or DEFAULT_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.utcfromtimestamp(timestamp).replace(tzinfo=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)
|
||||
@@ -1,6 +1,7 @@
|
||||
# required for Home Assistant core
|
||||
requests>=2.0
|
||||
pyyaml>=3.11
|
||||
pytz>=2015.2
|
||||
|
||||
# optional, needed for specific components
|
||||
|
||||
|
||||
+5
-1
@@ -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
|
||||
@@ -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. """
|
||||
|
||||
|
||||
+55
-2
@@ -5,10 +5,15 @@ 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,
|
||||
EVENT_STATE_CHANGED)
|
||||
from homeassistant.components import sun
|
||||
|
||||
|
||||
def get_test_config_dir():
|
||||
@@ -16,10 +21,20 @@ 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
|
||||
|
||||
return hass
|
||||
|
||||
@@ -37,6 +52,44 @@ 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)})
|
||||
|
||||
|
||||
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. """
|
||||
|
||||
|
||||
@@ -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))
|
||||
@@ -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
|
||||
@@ -80,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')
|
||||
|
||||
@@ -116,7 +119,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.
|
||||
@@ -0,0 +1,137 @@
|
||||
"""
|
||||
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
|
||||
|
||||
SERVER_PORT = 8126
|
||||
|
||||
|
||||
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: {http.CONF_SERVER_PORT: SERVER_PORT}})
|
||||
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))
|
||||
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
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
|
||||
|
||||
SERVER_PORT = 8127
|
||||
|
||||
|
||||
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, {
|
||||
http.DOMAIN: {http.CONF_SERVER_PORT: SERVER_PORT}})
|
||||
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)
|
||||
@@ -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)
|
||||
+12
-13
@@ -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()
|
||||
|
||||
|
||||
+7
-3
@@ -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. """
|
||||
@@ -72,7 +76,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 +92,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)
|
||||
|
||||
@@ -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'],
|
||||
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user