Reset input_* to initial?

I am fully expecting the answer here to be ‘no’ but is it possible to reset an input_* to the initial value defined in it’s configuration?

e.g

input_datetime:
  my_time:
    has_date: False
    initial: 23:00

Is there a way to set the state of input_datetime.my_time to whatever was defined in initial?

what attributes does the device have in the states page?

Well, I looked into it and it doesn’t have a restore value stored in the attributes for you to build an automation off of. Luckily, it looks like a minor change to the input_datetime.py would rectify that.

Copy this file to the custom_components directory in your config. Name it input_datetime.py. It will overwrite what you got, but not it should have a new attribute named ‘initial’. You can use that to set the number back to the initial timestamp.

It’s a bandaide, but it should work. I haven’t tested this either btw… let me know if you have errors.

"""
Component to offer a way to select a date and / or a time.

For more details about this component, please refer to the documentation
at https://home-assistant.io/components/input_datetime/
"""
import logging
import datetime

import voluptuous as vol

from homeassistant.const import ATTR_ENTITY_ID, CONF_ICON, CONF_NAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.restore_state import async_get_last_state
from homeassistant.util import dt as dt_util


_LOGGER = logging.getLogger(__name__)

DOMAIN = 'input_datetime'
ENTITY_ID_FORMAT = DOMAIN + '.{}'

CONF_HAS_DATE = 'has_date'
CONF_HAS_TIME = 'has_time'
CONF_INITIAL = 'initial'

ATTR_DATE = 'date'
ATTR_TIME = 'time'

SERVICE_SET_DATETIME = 'set_datetime'

SERVICE_SET_DATETIME_SCHEMA = vol.Schema({
    vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
    vol.Optional(ATTR_DATE): cv.date,
    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({
    DOMAIN: vol.Schema({
        cv.slug: vol.All({
            vol.Optional(CONF_NAME): cv.string,
            vol.Optional(CONF_HAS_DATE, default=False): cv.boolean,
            vol.Optional(CONF_HAS_TIME, default=False): cv.boolean,
            vol.Optional(CONF_ICON): cv.icon,
            vol.Optional(CONF_INITIAL): cv.string,
        }, has_date_or_time)})
}, extra=vol.ALLOW_EXTRA)


async def async_setup(hass, config):
    """Set up an input datetime."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)

    entities = []

    for object_id, cfg in config[DOMAIN].items():
        name = cfg.get(CONF_NAME)
        has_time = cfg.get(CONF_HAS_TIME)
        has_date = cfg.get(CONF_HAS_DATE)
        icon = cfg.get(CONF_ICON)
        initial = cfg.get(CONF_INITIAL)
        entities.append(InputDatetime(object_id, name,
                                      has_date, has_time, icon, initial))

    if not entities:
        return False

    async def async_set_datetime_service(entity, call):
        """Handle a call to the input datetime 'set datetime' service."""
        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

        entity.async_set_datetime(date, time)

    component.async_register_entity_service(
        SERVICE_SET_DATETIME, SERVICE_SET_DATETIME_SCHEMA,
        async_set_datetime_service
    )

    await component.async_add_entities(entities)
    return True


class InputDatetime(Entity):
    """Representation of a datetime input."""

    def __init__(self, object_id, name, has_date, has_time, icon, initial):
        """Initialize a select input."""
        self.entity_id = ENTITY_ID_FORMAT.format(object_id)
        self._name = name
        self.has_date = has_date
        self.has_time = has_time
        self._icon = icon
        self._initial = initial
        self._current_datetime = None

    async def async_added_to_hass(self):
        """Run when entity about to be added."""
        restore_val = None

        # Priority 1: Initial State
        if self._initial is not None:
            restore_val = self._initial

        # Priority 2: Old state
        if restore_val is None:
            old_state = await async_get_last_state(self.hass, self.entity_id)
            if old_state is not None:
                restore_val = old_state.state

        if restore_val is not None:
            if not self.has_date:
                self._current_datetime = dt_util.parse_time(restore_val)
            elif not self.has_time:
                self._current_datetime = dt_util.parse_date(restore_val)
            else:
                self._current_datetime = dt_util.parse_datetime(restore_val)

    @property
    def should_poll(self):
        """If entity should be polled."""
        return False

    @property
    def name(self):
        """Return the name of the select input."""
        return self._name

    @property
    def icon(self):
        """Return the icon to be used for this entity."""
        return self._icon

    @property
    def state(self):
        """Return the state of the component."""
        return self._current_datetime

    @property
    def state_attributes(self):
        """Return the state attributes."""
        attrs = {
            'has_date': self.has_date,
            'has_time': self.has_time,
        }

        if self._current_datetime is None:
            return attrs

        if self.has_date and self._current_datetime is not None:
            attrs['year'] = self._current_datetime.year
            attrs['month'] = self._current_datetime.month
            attrs['day'] = self._current_datetime.day

        if self.has_time and self._current_datetime is not None:
            attrs['hour'] = self._current_datetime.hour
            attrs['minute'] = self._current_datetime.minute
            attrs['second'] = self._current_datetime.second

        if not self.has_date:
            attrs['timestamp'] = self._current_datetime.hour * 3600 + \
                                    self._current_datetime.minute * 60 + \
                                    self._current_datetime.second
        elif not self.has_time:
            extended = datetime.datetime.combine(self._current_datetime,
                                                 datetime.time(0, 0))
            attrs['timestamp'] = extended.timestamp()
        else:
            attrs['timestamp'] = self._current_datetime.timestamp()

        if self._initial:
            if not self.has_date:
                attrs['initial'] = dt_util.parse_time(self._initial)
            elif not self.has_time:
                attrs['initial'] = dt_util.parse_date(self._initial)
            else:
                attrs['initial'] = dt_util.parse_datetime(self._initial)

        return attrs

    def async_set_datetime(self, date_val, time_val):
        """Set a new date / time."""
        if self.has_date and self.has_time and date_val and time_val:
            self._current_datetime = datetime.datetime.combine(date_val,
                                                               time_val)
        elif self.has_date and not self.has_time and date_val:
            self._current_datetime = date_val
        if self.has_time and not self.has_date and time_val:
            self._current_datetime = time_val

        self.async_schedule_update_ha_state()
1 Like

Nothing that appears to give me what I am after:

{
  "has_date": true,
  "has_time": true,
  "year": 2018,
  "month": 9,
  "day": 6,
  "hour": 8,
  "minute": 0,
  "second": 0,
  "timestamp": 1536217200
}

I just wondered if there might be a secret not-very-well-documented way to get the information seeing as HA must have known it at start-up.

I’m not being snarky, barely a day goes by here when I don’t learn about something that I am sure I have never seen documented. I reckon it is always worth asking.

Wow, thanks, I’ll give it a try.

Sorry but I get this at startup…

2018-09-07 16:57:38 ERROR (MainThread) [homeassistant.setup] Error during setup of component input_datetime
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/homeassistant/setup.py", line 145, in _async_setup_component
    hass, processed_config)
  File "/config/custom_components/input_datetime.py", line 97, in async_setup
    component.async_register_entity_service(
AttributeError: 'EntityComponent' object has no attribute 'async_register_entity_service'

Are you running the most recent build of HA?

I think you may have messed up the copy/paste?

async_register_entity_service should occur at line 91, not 97. Is there some extra junk in the file?

I added a couple of lines of comments at the top between line 1 and 6 the ones with “”" to remind me why I am using the custom component.

I’m running v 0.76.1

(Waiting for some dust to settle on v0.77.x :slight_smile:)

I’m not sure, it should be working. Might want to table this for a bit until I can look at it. I didn’t change anything in that section of code. I just added an attribute to the attributes, somewhere around line 187, if self.initial:.

Maybe this component cannot be overwritten?

just for shits and giggles, try to paste the code without adding comments.

Well, that is interesting, I took out the comments and it didn’t even attempt a restart. Maybe something is not copying across correctly…

I’ll try once more…

Fri Sep 07 2018 17:28:49 GMT+0100 (British Summer Time)

Testing configuration at /config
ERROR:homeassistant.scripts.check_config:BURB
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/homeassistant/scripts/check_config.py", line 207, in check
    res['components'] = check_ha_config_file(hass)
  File "/usr/local/lib/python3.6/site-packages/homeassistant/scripts/check_config.py", line 327, in check_ha_config_file
    hass, config, core_config.get(CONF_PACKAGES, {}), _pack_error)
  File "/usr/local/lib/python3.6/site-packages/homeassistant/config.py", line 596, in merge_packages_config
    component = get_component(hass, comp_name)
  File "/usr/local/lib/python3.6/site-packages/homeassistant/loader.py", line 94, in get_component
    module = importlib.import_module(path)
  File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 674, in exec_module
  File "<frozen importlib._bootstrap_external>", line 781, in get_code
  File "<frozen importlib._bootstrap_external>", line 741, in source_to_code
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/config/custom_components/input_datetime.py", line 208
    2 Replies
            ^
SyntaxError: invalid syntax
Fatal error while loading config: invalid syntax (input_datetime.py, line 208)
Failed config
  General Errors: 
    - invalid syntax (input_datetime.py, line 208)
Successful config (partial)

Ok, it’s restarting now.
Sorry for the running commentary but hassio restarts slowwwwwly :slight_smile:

Same error I’m afraid.
I’ll leave you to look at it at your leisure (or not if you choose not to).

But either way thanks for looking.