mirror of
https://github.com/home-assistant/core.git
synced 2025-07-23 13:17:32 +00:00
Clean up input-datetime (#16000)
This commit is contained in:
parent
2a210607d3
commit
834077190f
@ -4,14 +4,12 @@ Component to offer a way to select a date and / or a time.
|
|||||||
For more details about this component, please refer to the documentation
|
For more details about this component, please refer to the documentation
|
||||||
at https://home-assistant.io/components/input_datetime/
|
at https://home-assistant.io/components/input_datetime/
|
||||||
"""
|
"""
|
||||||
import asyncio
|
|
||||||
import logging
|
import logging
|
||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
|
|
||||||
from homeassistant.const import (
|
from homeassistant.const import ATTR_ENTITY_ID, CONF_ICON, CONF_NAME
|
||||||
ATTR_ENTITY_ID, CONF_ICON, CONF_NAME, STATE_UNKNOWN)
|
|
||||||
import homeassistant.helpers.config_validation as cv
|
import homeassistant.helpers.config_validation as cv
|
||||||
from homeassistant.helpers.entity import Entity
|
from homeassistant.helpers.entity import Entity
|
||||||
from homeassistant.helpers.entity_component import EntityComponent
|
from homeassistant.helpers.entity_component import EntityComponent
|
||||||
@ -39,6 +37,15 @@ SERVICE_SET_DATETIME_SCHEMA = vol.Schema({
|
|||||||
vol.Optional(ATTR_TIME): cv.time,
|
vol.Optional(ATTR_TIME): cv.time,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def has_date_or_time(conf):
|
||||||
|
"""Check at least date or time is true."""
|
||||||
|
if conf[CONF_HAS_DATE] or conf[CONF_HAS_TIME]:
|
||||||
|
return conf
|
||||||
|
|
||||||
|
raise vol.Invalid('Entity needs at least a date or a time')
|
||||||
|
|
||||||
|
|
||||||
CONFIG_SCHEMA = vol.Schema({
|
CONFIG_SCHEMA = vol.Schema({
|
||||||
DOMAIN: vol.Schema({
|
DOMAIN: vol.Schema({
|
||||||
cv.slug: vol.All({
|
cv.slug: vol.All({
|
||||||
@ -47,23 +54,11 @@ CONFIG_SCHEMA = vol.Schema({
|
|||||||
vol.Optional(CONF_HAS_TIME, default=False): cv.boolean,
|
vol.Optional(CONF_HAS_TIME, default=False): cv.boolean,
|
||||||
vol.Optional(CONF_ICON): cv.icon,
|
vol.Optional(CONF_ICON): cv.icon,
|
||||||
vol.Optional(CONF_INITIAL): cv.string,
|
vol.Optional(CONF_INITIAL): cv.string,
|
||||||
}, cv.has_at_least_one_key_value((CONF_HAS_DATE, True),
|
}, has_date_or_time)})
|
||||||
(CONF_HAS_TIME, True)))})
|
|
||||||
}, extra=vol.ALLOW_EXTRA)
|
}, extra=vol.ALLOW_EXTRA)
|
||||||
|
|
||||||
|
|
||||||
@asyncio.coroutine
|
async def async_setup(hass, config):
|
||||||
def async_set_datetime(hass, entity_id, dt_value):
|
|
||||||
"""Set date and / or time of input_datetime."""
|
|
||||||
yield from hass.services.async_call(DOMAIN, SERVICE_SET_DATETIME, {
|
|
||||||
ATTR_ENTITY_ID: entity_id,
|
|
||||||
ATTR_DATE: dt_value.date(),
|
|
||||||
ATTR_TIME: dt_value.time()
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
@asyncio.coroutine
|
|
||||||
def async_setup(hass, config):
|
|
||||||
"""Set up an input datetime."""
|
"""Set up an input datetime."""
|
||||||
component = EntityComponent(_LOGGER, DOMAIN, hass)
|
component = EntityComponent(_LOGGER, DOMAIN, hass)
|
||||||
|
|
||||||
@ -81,32 +76,24 @@ def async_setup(hass, config):
|
|||||||
if not entities:
|
if not entities:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@asyncio.coroutine
|
async def async_set_datetime_service(entity, call):
|
||||||
def async_set_datetime_service(call):
|
|
||||||
"""Handle a call to the input datetime 'set datetime' service."""
|
"""Handle a call to the input datetime 'set datetime' service."""
|
||||||
target_inputs = component.async_extract_from_service(call)
|
time = call.data.get(ATTR_TIME)
|
||||||
|
date = call.data.get(ATTR_DATE)
|
||||||
|
if (entity.has_date and not date) or (entity.has_time and not time):
|
||||||
|
_LOGGER.error("Invalid service data for %s "
|
||||||
|
"input_datetime.set_datetime: %s",
|
||||||
|
entity.entity_id, str(call.data))
|
||||||
|
return
|
||||||
|
|
||||||
tasks = []
|
entity.async_set_datetime(date, time)
|
||||||
for input_datetime in target_inputs:
|
|
||||||
time = call.data.get(ATTR_TIME)
|
|
||||||
date = call.data.get(ATTR_DATE)
|
|
||||||
if (input_datetime.has_date() and not date) or \
|
|
||||||
(input_datetime.has_time() and not time):
|
|
||||||
_LOGGER.error("Invalid service data for "
|
|
||||||
"input_datetime.set_datetime: %s",
|
|
||||||
str(call.data))
|
|
||||||
continue
|
|
||||||
|
|
||||||
tasks.append(input_datetime.async_set_datetime(date, time))
|
component.async_register_entity_service(
|
||||||
|
SERVICE_SET_DATETIME, SERVICE_SET_DATETIME_SCHEMA,
|
||||||
|
async_set_datetime_service
|
||||||
|
)
|
||||||
|
|
||||||
if tasks:
|
await component.async_add_entities(entities)
|
||||||
yield from asyncio.wait(tasks, loop=hass.loop)
|
|
||||||
|
|
||||||
hass.services.async_register(
|
|
||||||
DOMAIN, SERVICE_SET_DATETIME, async_set_datetime_service,
|
|
||||||
schema=SERVICE_SET_DATETIME_SCHEMA)
|
|
||||||
|
|
||||||
yield from component.async_add_entities(entities)
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@ -117,14 +104,13 @@ class InputDatetime(Entity):
|
|||||||
"""Initialize a select input."""
|
"""Initialize a select input."""
|
||||||
self.entity_id = ENTITY_ID_FORMAT.format(object_id)
|
self.entity_id = ENTITY_ID_FORMAT.format(object_id)
|
||||||
self._name = name
|
self._name = name
|
||||||
self._has_date = has_date
|
self.has_date = has_date
|
||||||
self._has_time = has_time
|
self.has_time = has_time
|
||||||
self._icon = icon
|
self._icon = icon
|
||||||
self._initial = initial
|
self._initial = initial
|
||||||
self._current_datetime = None
|
self._current_datetime = None
|
||||||
|
|
||||||
@asyncio.coroutine
|
async def async_added_to_hass(self):
|
||||||
def async_added_to_hass(self):
|
|
||||||
"""Run when entity about to be added."""
|
"""Run when entity about to be added."""
|
||||||
restore_val = None
|
restore_val = None
|
||||||
|
|
||||||
@ -134,27 +120,18 @@ class InputDatetime(Entity):
|
|||||||
|
|
||||||
# Priority 2: Old state
|
# Priority 2: Old state
|
||||||
if restore_val is None:
|
if restore_val is None:
|
||||||
old_state = yield from async_get_last_state(self.hass,
|
old_state = await async_get_last_state(self.hass, self.entity_id)
|
||||||
self.entity_id)
|
|
||||||
if old_state is not None:
|
if old_state is not None:
|
||||||
restore_val = old_state.state
|
restore_val = old_state.state
|
||||||
|
|
||||||
if restore_val is not None:
|
if restore_val is not None:
|
||||||
if not self._has_date:
|
if not self.has_date:
|
||||||
self._current_datetime = dt_util.parse_time(restore_val)
|
self._current_datetime = dt_util.parse_time(restore_val)
|
||||||
elif not self._has_time:
|
elif not self.has_time:
|
||||||
self._current_datetime = dt_util.parse_date(restore_val)
|
self._current_datetime = dt_util.parse_date(restore_val)
|
||||||
else:
|
else:
|
||||||
self._current_datetime = dt_util.parse_datetime(restore_val)
|
self._current_datetime = dt_util.parse_datetime(restore_val)
|
||||||
|
|
||||||
def has_date(self):
|
|
||||||
"""Return whether the input datetime carries a date."""
|
|
||||||
return self._has_date
|
|
||||||
|
|
||||||
def has_time(self):
|
|
||||||
"""Return whether the input datetime carries a time."""
|
|
||||||
return self._has_time
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def should_poll(self):
|
def should_poll(self):
|
||||||
"""If entity should be polled."""
|
"""If entity should be polled."""
|
||||||
@ -173,55 +150,50 @@ class InputDatetime(Entity):
|
|||||||
@property
|
@property
|
||||||
def state(self):
|
def state(self):
|
||||||
"""Return the state of the component."""
|
"""Return the state of the component."""
|
||||||
if self._current_datetime is None:
|
|
||||||
return STATE_UNKNOWN
|
|
||||||
|
|
||||||
return self._current_datetime
|
return self._current_datetime
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def state_attributes(self):
|
def state_attributes(self):
|
||||||
"""Return the state attributes."""
|
"""Return the state attributes."""
|
||||||
attrs = {
|
attrs = {
|
||||||
'has_date': self._has_date,
|
'has_date': self.has_date,
|
||||||
'has_time': self._has_time,
|
'has_time': self.has_time,
|
||||||
}
|
}
|
||||||
|
|
||||||
if self._current_datetime is None:
|
if self._current_datetime is None:
|
||||||
return attrs
|
return attrs
|
||||||
|
|
||||||
if self._has_date and self._current_datetime is not None:
|
if self.has_date and self._current_datetime is not None:
|
||||||
attrs['year'] = self._current_datetime.year
|
attrs['year'] = self._current_datetime.year
|
||||||
attrs['month'] = self._current_datetime.month
|
attrs['month'] = self._current_datetime.month
|
||||||
attrs['day'] = self._current_datetime.day
|
attrs['day'] = self._current_datetime.day
|
||||||
|
|
||||||
if self._has_time and self._current_datetime is not None:
|
if self.has_time and self._current_datetime is not None:
|
||||||
attrs['hour'] = self._current_datetime.hour
|
attrs['hour'] = self._current_datetime.hour
|
||||||
attrs['minute'] = self._current_datetime.minute
|
attrs['minute'] = self._current_datetime.minute
|
||||||
attrs['second'] = self._current_datetime.second
|
attrs['second'] = self._current_datetime.second
|
||||||
|
|
||||||
if self._current_datetime is not None:
|
if not self.has_date:
|
||||||
if not self._has_date:
|
attrs['timestamp'] = self._current_datetime.hour * 3600 + \
|
||||||
attrs['timestamp'] = self._current_datetime.hour * 3600 + \
|
self._current_datetime.minute * 60 + \
|
||||||
self._current_datetime.minute * 60 + \
|
self._current_datetime.second
|
||||||
self._current_datetime.second
|
elif not self.has_time:
|
||||||
elif not self._has_time:
|
extended = datetime.datetime.combine(self._current_datetime,
|
||||||
extended = datetime.datetime.combine(self._current_datetime,
|
datetime.time(0, 0))
|
||||||
datetime.time(0, 0))
|
attrs['timestamp'] = extended.timestamp()
|
||||||
attrs['timestamp'] = extended.timestamp()
|
else:
|
||||||
else:
|
attrs['timestamp'] = self._current_datetime.timestamp()
|
||||||
attrs['timestamp'] = self._current_datetime.timestamp()
|
|
||||||
|
|
||||||
return attrs
|
return attrs
|
||||||
|
|
||||||
@asyncio.coroutine
|
|
||||||
def async_set_datetime(self, date_val, time_val):
|
def async_set_datetime(self, date_val, time_val):
|
||||||
"""Set a new date / time."""
|
"""Set a new date / time."""
|
||||||
if self._has_date and self._has_time and date_val and time_val:
|
if self.has_date and self.has_time and date_val and time_val:
|
||||||
self._current_datetime = datetime.datetime.combine(date_val,
|
self._current_datetime = datetime.datetime.combine(date_val,
|
||||||
time_val)
|
time_val)
|
||||||
elif self._has_date and not self._has_time and date_val:
|
elif self.has_date and not self.has_time and date_val:
|
||||||
self._current_datetime = date_val
|
self._current_datetime = date_val
|
||||||
if self._has_time and not self._has_date and time_val:
|
if self.has_time and not self.has_date and time_val:
|
||||||
self._current_datetime = time_val
|
self._current_datetime = time_val
|
||||||
|
|
||||||
yield from self.async_update_ha_state()
|
self.async_schedule_update_ha_state()
|
||||||
|
@ -60,21 +60,6 @@ def has_at_least_one_key(*keys: str) -> Callable:
|
|||||||
return validate
|
return validate
|
||||||
|
|
||||||
|
|
||||||
def has_at_least_one_key_value(*items: list) -> Callable:
|
|
||||||
"""Validate that at least one (key, value) pair exists."""
|
|
||||||
def validate(obj: Dict) -> Dict:
|
|
||||||
"""Test (key,value) exist in dict."""
|
|
||||||
if not isinstance(obj, dict):
|
|
||||||
raise vol.Invalid('expected dictionary')
|
|
||||||
|
|
||||||
for item in obj.items():
|
|
||||||
if item in items:
|
|
||||||
return obj
|
|
||||||
raise vol.Invalid('must contain one of {}.'.format(str(items)))
|
|
||||||
|
|
||||||
return validate
|
|
||||||
|
|
||||||
|
|
||||||
def boolean(value: Any) -> bool:
|
def boolean(value: Any) -> bool:
|
||||||
"""Validate and coerce a boolean value."""
|
"""Validate and coerce a boolean value."""
|
||||||
if isinstance(value, str):
|
if isinstance(value, str):
|
||||||
|
@ -7,11 +7,20 @@ import datetime
|
|||||||
from homeassistant.core import CoreState, State
|
from homeassistant.core import CoreState, State
|
||||||
from homeassistant.setup import setup_component, async_setup_component
|
from homeassistant.setup import setup_component, async_setup_component
|
||||||
from homeassistant.components.input_datetime import (
|
from homeassistant.components.input_datetime import (
|
||||||
DOMAIN, async_set_datetime)
|
DOMAIN, ATTR_ENTITY_ID, ATTR_DATE, ATTR_TIME, SERVICE_SET_DATETIME)
|
||||||
|
|
||||||
from tests.common import get_test_home_assistant, mock_restore_cache
|
from tests.common import get_test_home_assistant, mock_restore_cache
|
||||||
|
|
||||||
|
|
||||||
|
async def async_set_datetime(hass, entity_id, dt_value):
|
||||||
|
"""Set date and / or time of input_datetime."""
|
||||||
|
await hass.services.async_call(DOMAIN, SERVICE_SET_DATETIME, {
|
||||||
|
ATTR_ENTITY_ID: entity_id,
|
||||||
|
ATTR_DATE: dt_value.date(),
|
||||||
|
ATTR_TIME: dt_value.time()
|
||||||
|
}, blocking=True)
|
||||||
|
|
||||||
|
|
||||||
class TestInputDatetime(unittest.TestCase):
|
class TestInputDatetime(unittest.TestCase):
|
||||||
"""Test the input datetime component."""
|
"""Test the input datetime component."""
|
||||||
|
|
||||||
@ -57,7 +66,6 @@ def test_set_datetime(hass):
|
|||||||
dt_obj = datetime.datetime(2017, 9, 7, 19, 46)
|
dt_obj = datetime.datetime(2017, 9, 7, 19, 46)
|
||||||
|
|
||||||
yield from async_set_datetime(hass, entity_id, dt_obj)
|
yield from async_set_datetime(hass, entity_id, dt_obj)
|
||||||
yield from hass.async_block_till_done()
|
|
||||||
|
|
||||||
state = hass.states.get(entity_id)
|
state = hass.states.get(entity_id)
|
||||||
assert state.state == str(dt_obj)
|
assert state.state == str(dt_obj)
|
||||||
@ -89,7 +97,6 @@ def test_set_datetime_time(hass):
|
|||||||
time_portion = dt_obj.time()
|
time_portion = dt_obj.time()
|
||||||
|
|
||||||
yield from async_set_datetime(hass, entity_id, dt_obj)
|
yield from async_set_datetime(hass, entity_id, dt_obj)
|
||||||
yield from hass.async_block_till_done()
|
|
||||||
|
|
||||||
state = hass.states.get(entity_id)
|
state = hass.states.get(entity_id)
|
||||||
assert state.state == str(time_portion)
|
assert state.state == str(time_portion)
|
||||||
@ -144,7 +151,6 @@ def test_set_datetime_date(hass):
|
|||||||
date_portion = dt_obj.date()
|
date_portion = dt_obj.date()
|
||||||
|
|
||||||
yield from async_set_datetime(hass, entity_id, dt_obj)
|
yield from async_set_datetime(hass, entity_id, dt_obj)
|
||||||
yield from hass.async_block_till_done()
|
|
||||||
|
|
||||||
state = hass.states.get(entity_id)
|
state = hass.states.get(entity_id)
|
||||||
assert state.state == str(date_portion)
|
assert state.state == str(date_portion)
|
||||||
|
@ -523,21 +523,6 @@ def test_has_at_least_one_key():
|
|||||||
schema(value)
|
schema(value)
|
||||||
|
|
||||||
|
|
||||||
def test_has_at_least_one_key_value():
|
|
||||||
"""Test has_at_least_one_key_value validator."""
|
|
||||||
schema = vol.Schema(cv.has_at_least_one_key_value(('drink', 'beer'),
|
|
||||||
('drink', 'soda'),
|
|
||||||
('food', 'maultaschen')))
|
|
||||||
|
|
||||||
for value in (None, [], {}, {'wine': None}, {'drink': 'water'}):
|
|
||||||
with pytest.raises(vol.MultipleInvalid):
|
|
||||||
schema(value)
|
|
||||||
|
|
||||||
for value in ({'drink': 'beer'}, {'food': 'maultaschen'},
|
|
||||||
{'drink': 'soda', 'food': 'maultaschen'}):
|
|
||||||
schema(value)
|
|
||||||
|
|
||||||
|
|
||||||
def test_enum():
|
def test_enum():
|
||||||
"""Test enum validator."""
|
"""Test enum validator."""
|
||||||
class TestEnum(enum.Enum):
|
class TestEnum(enum.Enum):
|
||||||
|
Loading…
x
Reference in New Issue
Block a user