Пример #1
0
async def async_setup(hass, config):
    """Set up the updater component."""
    if "dev" in current_version:
        # This component only makes sense in release versions
        _LOGGER.info("Running on 'dev', only analytics will be submitted")

    hass.async_create_task(
        discovery.async_load_platform(hass, "binary_sensor", DOMAIN, {},
                                      config))

    config = config.get(DOMAIN, {})
    if config.get(CONF_REPORTING):
        huuid = await hass.async_add_job(_load_uuid, hass)
    else:
        huuid = None

    include_components = config.get(CONF_COMPONENT_REPORTING)

    async def check_new_version(now):
        """Check if a new version is available and report if one is."""
        result = await get_newest_version(hass, huuid, include_components)

        if result is None:
            return

        newest, release_notes = result

        # Skip on dev
        if newest is None or "dev" in current_version:
            return

        # Load data from supervisor on hass.io
        if hass.components.hassio.is_hassio():
            newest = hass.components.hassio.get_homeassistant_version()

        # Validate version
        update_available = False
        if StrictVersion(newest) > StrictVersion(current_version):
            _LOGGER.info(
                "The latest available version of Home Assistant is %s", newest)
            update_available = True
        elif StrictVersion(newest) == StrictVersion(current_version):
            _LOGGER.info(
                "You are on the latest version (%s) of Home Assistant", newest)
        elif StrictVersion(newest) < StrictVersion(current_version):
            _LOGGER.debug(
                "Local version is newer than the latest version (%s)", newest)

        updater = Updater(update_available, newest, release_notes)
        async_dispatcher_send(hass, DISPATCHER_REMOTE_UPDATE, updater)

    # Update daily, start 1 hour after startup
    _dt = dt_util.utcnow() + timedelta(hours=1)
    event.async_track_utc_time_change(hass,
                                      check_new_version,
                                      hour=_dt.hour,
                                      minute=_dt.minute,
                                      second=_dt.second)

    return True
Пример #2
0
    def __init__(self, hass, conf):
        """Initialize the sensor."""
        self.hass = hass
        self._name = conf.get(CONF_NAME)
        self._unit_of_measurement = conf.get(CONF_UNIT_OF_MEASUREMENT)
        self._icon = conf.get(CONF_ICON)
        self._type = conf.get(CONF_TYPE)
        self._rain_factor = conf.get(CONF_RAIN_FACTOR)
        self._lat = conf.get(CONF_LATITUDE)
        self._debug = conf.get(CONF_DEBUG)
        self._lon = conf.get(CONF_LONGITUDE)
        self._api = conf.get(CONF_API_KEY)
        self._max_ev = conf.get(CONF_MAX_EV)
        self._min_ev = conf.get(CONF_MIN_EV)
        self._state = 0.0
        if self._type == TYPE_EV_RAIN_BUCKET:
            self._state = 500.0
        self.reset_data()

        async_track_utc_time_change(hass,
                                    self._async_update_last_day,
                                    hour=23,
                                    minute=58,
                                    second=0)

        async_track_utc_time_change(hass,
                                    self._async_update_every_hour,
                                    minute=0,
                                    second=0)
Пример #3
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Setup the Yr.no sensor."""
    latitude = config.get(CONF_LATITUDE, hass.config.latitude)
    longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
    elevation = config.get(CONF_ELEVATION, hass.config.elevation or 0)

    if None in (latitude, longitude):
        _LOGGER.error("Latitude or longitude not set in Home Assistant config")
        return False

    coordinates = {'lat': str(latitude),
                   'lon': str(longitude),
                   'msl': str(elevation)}

    dev = []
    for sensor_type in config[CONF_MONITORED_CONDITIONS]:
        dev.append(YrSensor(sensor_type))
    yield from async_add_devices(dev)

    weather = YrData(hass, coordinates, dev)
    # Update weather on the hour, spread seconds
    async_track_utc_time_change(hass, weather.async_update,
                                minute=randrange(1, 10),
                                second=randrange(0, 59))
    yield from weather.async_update()
Пример #4
0
def async_setup_scanner_platform(hass: HomeAssistantType, config: ConfigType,
                                 scanner: Any, async_see_device: Callable):
    """Helper method to connect scanner-based platform to device tracker.

    This method is a coroutine.
    """
    interval = config.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)

    # Initial scan of each mac we also tell about host name for config
    seen = set()  # type: Any

    def device_tracker_scan(now: dt_util.dt.datetime):
        """Called when interval matches."""
        found_devices = scanner.scan_devices()

        for mac in found_devices:
            if mac in seen:
                host_name = None
            else:
                host_name = scanner.get_device_name(mac)
                seen.add(mac)
            hass.add_job(async_see_device(mac=mac, host_name=host_name))

    async_track_utc_time_change(
        hass, device_tracker_scan, second=range(0, 60, interval))

    hass.async_add_job(device_tracker_scan, None)
Пример #5
0
    def __init__(self, hass, location, config):
        """Initialize the sun."""
        self._monitored_condtions = config[CONF_MONITORED_CONDITIONS]
        scan_interval = config.get(CONF_SCAN_INTERVAL)
        self.hass = hass
        self.location = location
        # Initialize values for attributes to be reported.
        for a in self._monitored_condtions:
            setattr(self, a, None)
        # Make sure STATE_ATTR_NEXT_RISING & STATE_ATTR_NEXT_SETTING are
        # defined since they are used to calculate state. Initialize them.
        setattr(self, STATE_ATTR_NEXT_RISING, None)
        setattr(self, STATE_ATTR_NEXT_SETTING, None)
        self._state = None
        self._update_position = (
            STATE_ATTR_AZIMUTH in self._monitored_condtions
            or STATE_ATTR_ELEVATION in self._monitored_condtions)

        if self._update_position:
            if scan_interval:
                async_track_time_interval(hass, self.timer_update,
                                          scan_interval)
            else:
                # If scan_interval not specified, use old method of updating
                # once a minute on the half minute (i.e., now == xx:xx:30.)
                async_track_utc_time_change(hass, self.timer_update, second=30)
Пример #6
0
 async def async_added_to_hass(self):
     """Start fetching data."""
     await self._fetch_data()
     async_track_utc_time_change(self.hass,
                                 self._update,
                                 minute=31,
                                 second=0)
Пример #7
0
async def async_setup_platform(hass, config, async_add_entities,
                               discovery_info=None):
    """Set up the Yr.no sensor."""
    elevation = config.get(CONF_ELEVATION, hass.config.elevation or 0)
    forecast = config.get(CONF_FORECAST)
    latitude = config.get(CONF_LATITUDE, hass.config.latitude)
    longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
    name = config.get(CONF_NAME)

    if None in (latitude, longitude):
        _LOGGER.error("Latitude or longitude not set in Home Assistant config")
        return False

    coordinates = {
        'lat': str(latitude),
        'lon': str(longitude),
        'msl': str(elevation),
    }

    dev = []
    for sensor_type in config[CONF_MONITORED_CONDITIONS]:
        dev.append(YrSensor(name, sensor_type))
    async_add_entities(dev)

    weather = YrData(hass, coordinates, forecast, dev)
    async_track_utc_time_change(hass, weather.updating_devices,
                                minute=31, second=0)
    await weather.fetching_data()
Пример #8
0
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    latitude = config.get(CONF_LATITUDE, hass.config.latitude)
    longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
    name = config.get(CONF_NAME)

    # [monitored_conditions](正規化済み)のリスト毎にセンサーを生成
    # エンティティリスト entities に詰める
    entities = []
    for sensor_type in config[CONF_MONITORED_CONDITIONS]:
        entities.append(mySensorEntities(name, sensor_type))

    # 非同期エンティティリストとして登録
    async_add_entities(entities)

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    # データ取得Classを作成
    dataFetcher = myDataFetcher(hass, entities)

    # 時間がパターンと一致した場合に起動する同期リスナーを追加します。
    # (必要か?)
    # http://dev-docs.home-assistant.io/en/master/api/helpers.html
    async_track_utc_time_change(hass, dataFetcher.updating_devices, second=0)

    # 最初の取得と同期、ループの開始
    await dataFetcher.fetching_data()
Пример #9
0
async def async_setup(hass, config):
    """Set up parameters."""

    region_code = config[DOMAIN][CONF_REGION_CODE]
    scan_interval = config[DOMAIN][CONF_SCAN_INTERVAL]

    eon_monitor = EONEnergiemonitor(hass, region_code)
    hass.data[DOMAIN] = eon_monitor

    # Register update every scan_interval minutes, starting now
    # this should even out the load on the servers
    now = dt_util.utcnow()
    async_track_utc_time_change(
        hass,
        eon_monitor.update,
        minute=range(now.minute % scan_interval, 60, scan_interval),
        second=now.second,
    )

    # initial update
    await eon_monitor.update()

    # Load sensors
    hass.async_create_task(
        discovery.async_load_platform(hass, "sensor", DOMAIN, {}, config))

    return True
Пример #10
0
    def start_periodic_update(self):
        """Start periodic data polling."""

        # Register API limit reset
        _LOGGER.debug("register API limit reset")
        async_track_utc_time_change(self._hass,
                                    self.reset_api_limit,
                                    hour=0,
                                    minute=0,
                                    second=0,
                                    local=True)

        @callback
        def sunrise_call_action(now=None):
            """Call action with right context."""
            next_setting = get_location_astral_event_next(
                get_astral_location(self._hass), SUN_EVENT_SUNSET,
                dt_util.utcnow()) + timedelta(hours=1)
            _LOGGER.info(
                f"Good Morning! Time to prepare the day until the sun will set at {next_setting - timedelta(hours=1)}"
            )

            remaining_api_calls = self.get_remaining_API_count()
            delay = (next_setting - dt_util.utcnow()) / (remaining_api_calls -
                                                         1)
            _LOGGER.info(
                f"During the day, there will be {remaining_api_calls} updates delayed by {delay} each"
            )

            # Schedule updates over the day (starting on 0 to process early morning update)
            for i in range(0, remaining_api_calls):
                exec_delay = delay.total_seconds() * i
                exec_time = dt_util.utcnow() + timedelta(seconds=exec_delay)

                _LOGGER.info(
                    f"History update scheduled update at {exec_time.isoformat()}"
                )
                async_call_later(self._hass, exec_delay, self.update_history)

        # Initial sensor update
        if not self._disable_auto_history_fetching:
            _LOGGER.debug("register initial history update in 20 seconds")
            async_call_later(self._hass, 20, self.update_history)

            # Set periodical history update
            _LOGGER.debug("register history update at sunrise")

            # Run history update
            # TEST: async_call_later(self._hass, 30, sunrise_call_action)
            async_track_sunrise(self._hass, sunrise_call_action)

        # Set daily forecast update
        if not self._disable_auto_forecast_fetching:
            _LOGGER.debug("register daily forecast update at 00:00:00")
            async_track_utc_time_change(self._hass,
                                        self.update_forecast,
                                        hour=0,
                                        minute=0,
                                        second=0,
                                        local=True)
Пример #11
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Setup the Yr.no sensor."""
    latitude = config.get(CONF_LATITUDE, hass.config.latitude)
    longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
    elevation = config.get(CONF_ELEVATION, hass.config.elevation or 0)

    if None in (latitude, longitude):
        _LOGGER.error("Latitude or longitude not set in Home Assistant config")
        return False

    coordinates = {
        'lat': str(latitude),
        'lon': str(longitude),
        'msl': str(elevation)
    }

    dev = []
    for sensor_type in config[CONF_MONITORED_CONDITIONS]:
        dev.append(YrSensor(sensor_type))
    yield from async_add_devices(dev)

    weather = YrData(hass, coordinates, dev)
    # Update weather on the hour, spread seconds
    async_track_utc_time_change(hass,
                                weather.async_update,
                                minute=randrange(1, 10),
                                second=randrange(0, 59))
    yield from weather.async_update()
Пример #12
0
async def async_setup_scanner(hass, config, async_see, discovery_info=None):
    """Set up the Niu tracker."""
    _LOGGER.error("setup device tracker")
    controller = hass.data[NIU_DOMAIN]["controller"]
    tracker = NiuDeviceTracker(hass, config, async_see, controller)
    await tracker.update_info()
    async_track_utc_time_change(hass, tracker.update_info, second=59)
    return True
Пример #13
0
async def async_setup_scanner(hass, config, async_see, discovery_info=None):
    """Set up the Tesla tracker."""
    tracker = TeslaDeviceTracker(
        hass, config, async_see, hass.data[TESLA_DOMAIN]["devices"]["devices_tracker"]
    )
    await tracker.update_info()
    async_track_utc_time_change(hass, tracker.update_info, second=range(0, 60, 30))
    return True
Пример #14
0
    def __init__(self, hass, location):
        """Initialize the sun."""
        self.hass = hass
        self.location = location
        self._state = self.next_rising = self.next_setting = None
        self.next_dawn = self.next_dusk = None
        self.next_midnight = self.next_noon = None
        self.solar_elevation = self.solar_azimuth = None

        async_track_utc_time_change(hass, self.timer_update, second=30)
Пример #15
0
    def __init__(self, hass, location):
        """Initialize the sun."""
        self.hass = hass
        self.location = location
        self._state = self.next_rising = self.next_setting = None
        self.next_dawn = self.next_dusk = None
        self.next_midnight = self.next_noon = None
        self.solar_elevation = self.solar_azimuth = None

        async_track_utc_time_change(hass, self.timer_update, second=30)
Пример #16
0
async def async_setup(hass, config):
    """Set up the updater component."""
    if "dev" in current_version:
        # This component only makes sense in release versions
        _LOGGER.info("Running on 'dev', only analytics will be submitted")

    config = config.get(DOMAIN, {})
    if config.get(CONF_REPORTING):
        huuid = await hass.async_add_job(_load_uuid, hass)
    else:
        huuid = None

    include_components = config.get(CONF_COMPONENT_REPORTING)

    async def check_new_version(now):
        """Check if a new version is available and report if one is."""
        result = await get_newest_version(hass, huuid, include_components)

        if result is None:
            return

        newest, releasenotes = result

        # Skip on dev
        if newest is None or "dev" in current_version:
            return

        # Load data from supervisor on hass.io
        if hass.components.hassio.is_hassio():
            newest = hass.components.hassio.get_homeassistant_version()

        # Validate version
        if StrictVersion(newest) > StrictVersion(current_version):
            _LOGGER.info("The latest available version is %s", newest)
            hass.states.async_set(
                ENTITY_ID,
                newest,
                {
                    ATTR_FRIENDLY_NAME: "Update Available",
                    ATTR_RELEASE_NOTES: releasenotes,
                },
            )
        elif StrictVersion(newest) == StrictVersion(current_version):
            _LOGGER.info(
                "You are on the latest version (%s) of Home Assistant", newest)

    # Update daily, start 1 hour after startup
    _dt = dt_util.utcnow() + timedelta(hours=1)
    event.async_track_utc_time_change(hass,
                                      check_new_version,
                                      hour=_dt.hour,
                                      minute=_dt.minute,
                                      second=_dt.second)

    return True
    async def async_added_to_hass(self):
        """Run when entity about to be added to hass."""
        await super().async_added_to_hass()
        state = await self.async_get_last_state()
        if state:
            self._state = state.state

        _dt = dt_util.utcnow() + timedelta(minutes=10)
        event.async_track_utc_time_change(
            self.hass, self.check_new_pullrequests,
            hour=_dt.hour, minute=_dt.minute, second=_dt.second)
Пример #18
0
    def __init__(self, hass):
        """Initialize the event_history."""
        self.hass = hass
        if os.path.exists('/srv/homeassistant/config/event_history.json'):
            with open('/srv/homeassistant/config/event_history.json') as f:
                self._events = json.loads(f.read())
        else:
            self._events = {}
        self._events['started'] = self._events['updated'] = time.time()
        self._save()

        async_track_utc_time_change(hass, self.timer_update, second=30)
Пример #19
0
async def test_periodic_task_wrong_input(hass):
    """Test periodic tasks with wrong input."""
    specific_runs = []

    with pytest.raises(ValueError):
        async_track_utc_time_change(hass,
                                    lambda x: specific_runs.append(1),
                                    hour="/two")

    _send_time_changed(hass, datetime(2014, 5, 2, 0, 0, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 0
Пример #20
0
def async_setup(hass, config):
    """Set up the updater component."""
    if 'dev' in current_version:
        # This component only makes sense in release versions
        _LOGGER.warning("Running on 'dev', only analytics will be submitted")

    config = config.get(DOMAIN, {})
    if config.get(CONF_REPORTING):
        huuid = yield from hass.async_add_job(_load_uuid, hass)
    else:
        huuid = None

    include_components = config.get(CONF_COMPONENT_REPORTING)

    @asyncio.coroutine
    def check_new_version(now):
        """Check if a new version is available and report if one is."""
        result = yield from get_newest_version(hass, huuid, include_components)

        if result is None:
            return

        newest, releasenotes = result

        # Skip on dev
        if newest is None or 'dev' in current_version:
            return

        # Load data from supervisor on hass.io
        if hass.components.hassio.is_hassio():
            newest = hass.components.hassio.get_homeassistant_version()

        # Validate version
        if StrictVersion(newest) > StrictVersion(current_version):
            _LOGGER.info("The latest available version is %s", newest)
            hass.states.async_set(
                ENTITY_ID, newest, {ATTR_FRIENDLY_NAME: 'Update Available',
                                    ATTR_RELEASE_NOTES: releasenotes}
            )
        elif StrictVersion(newest) == StrictVersion(current_version):
            _LOGGER.info(
                "You are on the latest version (%s) of Home Assistant", newest)

    # Update daily, start 1 hour after startup
    _dt = dt_util.utcnow() + timedelta(hours=1)
    event.async_track_utc_time_change(
        hass, check_new_version,
        hour=_dt.hour, minute=_dt.minute, second=_dt.second)

    return True
Пример #21
0
    def __init__(self, hass, entity_id, entity_state_on, entity_state_off,
                 name):

        self.hass = hass
        self._entity_id = entity_id
        self._entity_state_on = entity_state_on
        self._entity_state_off = entity_state_off
        self._name = name
        self._unit_of_measurement = "h"
        self.value = None
        self.count = None
        self.day_value = None
        self.day_count = None
        self.day_value_last = None
        self.day_count_last = None

        self.month_value = None
        self.month_count = None
        self.month_value_last = None
        self.month_count_last = None

        self._m_state = None
        self.start_time = None

        self.update_state()
        async_track_state_change(hass, self._entity_id, self._async_changed)

        async_track_time_interval(hass, self._async_keepalive,
                                  timedelta(seconds=KEEPALIVE_UPDATE_SEC))

        async_track_utc_time_change(hass,
                                    self._async_update_last_day,
                                    hour=0,
                                    minute=0,
                                    second=0)

        @callback
        def start_refresh(*args):
            """Register state tracking."""
            @callback
            def force_refresh(*args):
                """Force the component to refresh."""
                self.async_schedule_update_ha_state(True)

            force_refresh()
            async_track_state_change(self.hass, self._entity_id, force_refresh)

        # Delay first refresh to keep startup fast
        hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_refresh)
Пример #22
0
async def test_periodic_task_wrong_input(hass):
    """Test periodic tasks with wrong input."""
    specific_runs = []

    now = dt_util.utcnow()

    with pytest.raises(ValueError):
        async_track_utc_time_change(
            hass, callback(lambda x: specific_runs.append(x)), hour="/two")

    async_fire_time_changed(
        hass, datetime(now.year + 1, 5, 2, 0, 0, 0, 999999,
                       tzinfo=dt_util.UTC))
    await hass.async_block_till_done()
    assert len(specific_runs) == 0
Пример #23
0
    def _async_setup_periodic_tasks(self) -> None:
        """Prepare periodic tasks."""
        if self.hass.is_stopping or not self._get_session:
            # Home Assistant is shutting down
            return

        # If the db is using a socket connection, we need to keep alive
        # to prevent errors from unexpected disconnects
        if self.dialect_name != SupportedDialect.SQLITE:
            self._keep_alive_listener = async_track_time_interval(
                self.hass, self._async_keep_alive,
                timedelta(seconds=KEEPALIVE_TIME))

        # If the commit interval is not 0, we need to commit periodically
        if self.commit_interval:
            self._commit_listener = async_track_time_interval(
                self.hass, self._async_commit,
                timedelta(seconds=self.commit_interval))

        # Run nightly tasks at 4:12am
        self._nightly_listener = async_track_time_change(
            self.hass, self.async_nightly_tasks, hour=4, minute=12, second=0)

        # Compile short term statistics every 5 minutes
        self._periodic_listener = async_track_utc_time_change(
            self.hass,
            self.async_periodic_statistics,
            minute=range(0, 60, 5),
            second=10)
Пример #24
0
async def test_periodic_task_hour(hass):
    """Test periodic tasks per hour."""
    specific_runs = []

    unsub = async_track_utc_time_change(hass,
                                        lambda x: specific_runs.append(1),
                                        hour="/2",
                                        minute=0,
                                        second=0)

    async_fire_time_changed(hass, datetime(2014, 5, 24, 22, 0, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 1

    async_fire_time_changed(hass, datetime(2014, 5, 24, 23, 0, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 1

    async_fire_time_changed(hass, datetime(2014, 5, 25, 0, 0, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 2

    async_fire_time_changed(hass, datetime(2014, 5, 25, 1, 0, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 2

    async_fire_time_changed(hass, datetime(2014, 5, 25, 2, 0, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 3

    unsub()

    async_fire_time_changed(hass, datetime(2014, 5, 25, 2, 0, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 3
Пример #25
0
    def async_add_entities(self, new_entities, update_before_add=False):
        """Add entities for a single platform async.

        This method must be run in the event loop.
        """
        # handle empty list from component/platform
        if not new_entities:
            return

        tasks = [
            self._async_process_entity(entity, update_before_add)
            for entity in new_entities
        ]

        yield from asyncio.wait(tasks, loop=self.component.hass.loop)
        yield from self.component.async_update_group()

        if self._async_unsub_polling is not None or \
           not any(entity.should_poll for entity
                   in self.platform_entities):
            return

        self._async_unsub_polling = async_track_utc_time_change(
            self.component.hass,
            self._update_entity_states,
            second=range(0, 60, self.scan_interval))
Пример #26
0
async def test_periodic_task_minute(hass):
    """Test periodic tasks per minute."""
    specific_runs = []

    unsub = async_track_utc_time_change(hass,
                                        lambda x: specific_runs.append(1),
                                        minute="/5",
                                        second=0)

    _send_time_changed(hass, datetime(2014, 5, 24, 12, 0, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 1

    _send_time_changed(hass, datetime(2014, 5, 24, 12, 3, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 1

    _send_time_changed(hass, datetime(2014, 5, 24, 12, 5, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 2

    unsub()

    _send_time_changed(hass, datetime(2014, 5, 24, 12, 5, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 2
Пример #27
0
async def test_periodic_task_clock_rollback(hass):
    """Test periodic tasks with the time rolling backwards."""
    specific_runs = []

    unsub = async_track_utc_time_change(hass,
                                        lambda x: specific_runs.append(1),
                                        hour="/2",
                                        minute=0,
                                        second=0)

    _send_time_changed(hass, datetime(2014, 5, 24, 22, 0, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 1

    _send_time_changed(hass, datetime(2014, 5, 24, 23, 0, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 1

    _send_time_changed(hass, datetime(2014, 5, 24, 22, 0, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 2

    _send_time_changed(hass, datetime(2014, 5, 24, 0, 0, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 3

    _send_time_changed(hass, datetime(2014, 5, 25, 2, 0, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 4

    unsub()

    _send_time_changed(hass, datetime(2014, 5, 25, 2, 0, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 4
Пример #28
0
async def test_async_track_time_change(hass):
    """Test tracking time change."""
    wildcard_runs = []
    specific_runs = []

    unsub = async_track_time_change(hass, lambda x: wildcard_runs.append(1))
    unsub_utc = async_track_utc_time_change(hass,
                                            lambda x: specific_runs.append(1),
                                            second=[0, 30])

    _send_time_changed(hass, datetime(2014, 5, 24, 12, 0, 0))
    await hass.async_block_till_done()
    assert len(specific_runs) == 1
    assert len(wildcard_runs) == 1

    _send_time_changed(hass, datetime(2014, 5, 24, 12, 0, 15))
    await hass.async_block_till_done()
    assert len(specific_runs) == 1
    assert len(wildcard_runs) == 2

    _send_time_changed(hass, datetime(2014, 5, 24, 12, 0, 30))
    await hass.async_block_till_done()
    assert len(specific_runs) == 2
    assert len(wildcard_runs) == 3

    unsub()
    unsub_utc()

    _send_time_changed(hass, datetime(2014, 5, 24, 12, 0, 30))
    await hass.async_block_till_done()
    assert len(specific_runs) == 2
    assert len(wildcard_runs) == 3
Пример #29
0
    async def setup_auto_fetch(self):
        try:
            _LOGGER.debug(
                "registering API auto fetching hourly between sun up and sun set"
            )
            location, elevation = get_astral_location(self._hass)
            next_setting = get_location_astral_event_next(
                location, elevation, SUN_EVENT_SUNSET,
                dt_util.utcnow()) + timedelta(hours=1)

            self._finishhour = next_setting.astimezone(
            ).hour  # already one hour ahead
            self._debugData["auto_fetch_end_hour"] = self._finishhour

            self._auto_fetch_tracker = async_track_utc_time_change(
                self._hass,
                self.update_forecast,
                minute=0,
                second=0,
                local=True)
            self._debugData["auto_fetch_timer_object"] = (
                self._auto_fetch_tracker is not None)

            _LOGGER.debug("created auto forecast fetch hourly timer")
            _LOGGER.debug(
                "Remember that even though its every hour, the api will only connect between the hours %s and %s and at midnight",
                self._starthour, self._finishhour)

        except Exception:
            _LOGGER.error("setup_auto_fetch: %s", traceback.format_exc())
Пример #30
0
async def async_setup(hass: HomeAssistantType, config: ConfigType):
    """Set up the device tracker."""
    tracker = await legacy.get_tracker(hass, config)

    legacy_platforms = await setup.async_extract_config(hass, config)

    setup_tasks = [
        legacy_platform.async_setup_legacy(hass, tracker)
        for legacy_platform in legacy_platforms
    ]

    if setup_tasks:
        await asyncio.wait(setup_tasks)

    tracker.async_setup_group()

    async def async_platform_discovered(p_type, info):
        """Load a platform."""
        platform = await setup.async_create_platform_type(
            hass, config, p_type, {})

        if platform is None or platform.type != PLATFORM_TYPE_LEGACY:
            return

        await platform.async_setup_legacy(hass, tracker, info)

    discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered)

    # Clean up stale devices
    async_track_utc_time_change(hass,
                                tracker.async_update_stale,
                                second=range(0, 60, 5))

    async def async_see_service(call):
        """Service to see a device."""
        # Temp workaround for iOS, introduced in 0.65
        data = dict(call.data)
        data.pop("hostname", None)
        data.pop("battery_status", None)
        await tracker.async_see(**data)

    hass.services.async_register(DOMAIN, SERVICE_SEE, async_see_service,
                                 SERVICE_SEE_PAYLOAD_SCHEMA)

    # restore
    await tracker.async_setup_tracked_device()
    return True
Пример #31
0
def async_setup(hass, config):
    """Set up the updater component."""
    if 'dev' in CURRENT_VERSION:
        # This component only makes sense in release versions
        _LOGGER.warning("Running on 'dev', only analytics will be submitted")

    config = config.get(DOMAIN, {})
    if config.get(CONF_REPORTING):
        huuid = yield from hass.async_add_job(_load_uuid, hass)
    else:
        huuid = None

    include_components = config.get(CONF_COMPONENT_REPORTING)

    @asyncio.coroutine
    def check_new_version(now):
        """Check if a new version is available and report if one is."""
        result = yield from get_newest_version(hass, huuid, include_components)

        if result is None:
            return

        newest, releasenotes = result

        if newest is None or 'dev' in CURRENT_VERSION:
            return

        if StrictVersion(newest) > StrictVersion(CURRENT_VERSION):
            _LOGGER.info("The latest available version is %s", newest)
            hass.states.async_set(
                ENTITY_ID, newest, {
                    ATTR_FRIENDLY_NAME: 'Update Available',
                    ATTR_RELEASE_NOTES: releasenotes
                })
        elif StrictVersion(newest) == StrictVersion(CURRENT_VERSION):
            _LOGGER.info(
                "You are on the latest version (%s) of Home Assistant", newest)

    # Update daily, start 1 hour after startup
    _dt = dt_util.utcnow() + timedelta(hours=1)
    event.async_track_utc_time_change(hass,
                                      check_new_version,
                                      hour=_dt.hour,
                                      minute=_dt.minute,
                                      second=_dt.second)

    return True
Пример #32
0
    def __init__(self, hass, location, config):
        """Initialize the sun."""
        self.hass = hass
        self.location = location
        self._state = self.next_rising = self.next_setting = None
        self._attrs = dict.fromkeys(config[CONF_MONITORED_CONDITIONS], None)

        self._update_position = (STATE_ATTR_AZIMUTH in self._attrs
                                 or STATE_ATTR_ELEVATION in self._attrs)
        if self._update_position:
            scan_interval = config.get(CONF_SCAN_INTERVAL)
            if scan_interval:
                async_track_time_interval(hass, self.timer_update,
                                          scan_interval)
            else:
                # If scan_interval not specified, use old method of updating
                # once a minute on the half minute (i.e., time == xx:xx:30.)
                async_track_utc_time_change(hass, self.timer_update, second=30)
Пример #33
0
    def __init__(self, hass, conf):
        """Initialize the sensor."""
        self.hass = hass
        self._name = conf.get(CONF_NAME)
        self._unit_of_measurement = conf.get(CONF_UNIT_OF_MEASUREMENT)
        self._icon = conf.get(CONF_ICON)
        self._type = conf.get(CONF_TYPE)
        self._rain_factor = conf.get(CONF_RAIN_FACTOR)
        self._lat = conf.get(CONF_LATITUDE)
        self._elevation = conf.get(CONF_ELEVATION)
        self._debug = conf.get(CONF_DEBUG)
        self._lon = conf.get(CONF_LONGITUDE)
        self._api = conf.get(CONF_API_KEY)
        self._max_ev = conf.get(CONF_MAX_EV)
        self._min_ev = conf.get(CONF_MIN_EV)
        self._update_lock = asyncio.Lock()
        self._state = 0.0
        if self._type == TYPE_EV_RAIN_BUCKET:
            self._state = 500.0
            self._sensor_id = conf.get(CONF_FAO56_SENSOR)
            self._rain_sensor_id = conf.get(CONF_RAIN_SENSOR)

        if self._type in (TYPE_RAIN, TYPE_RAIN_DAY):
            self._sensor_id = conf.get(CONF_EXTERNAL_SENSOR_RAIN_1h)

        self.reset_data()

        sync_min = 58
        if self._type in (TYPE_EV_FAO56_DAY, TYPE_RAIN_DAY):
            sync_min = 50

        async_track_utc_time_change(hass,
                                    self._async_update_last_day,
                                    hour=23,
                                    minute=sync_min,
                                    second=0)

        if (self._type != TYPE_EV_RAIN_BUCKET):
            async_track_utc_time_change(hass,
                                        self._async_update_every_hour,
                                        minute=0,
                                        second=0)
Пример #34
0
    def async_add_entities(self, new_entities):
        """Add entities for a single platform async.

        This method must be run in the event loop.
        """
        tasks = [self._async_process_entity(entity) for entity in new_entities]

        yield from asyncio.gather(*tasks, loop=self.component.hass.loop)
        yield from self.component.async_update_group()

        if self._async_unsub_polling is not None or \
           not any(entity.should_poll for entity
                   in self.platform_entities):
            return

        self._async_unsub_polling = async_track_utc_time_change(
            self.component.hass, self._update_entity_states,
            second=range(0, 60, self.scan_interval))
Пример #35
0
async def async_setup(hass: HomeAssistantType, config: ConfigType):
    """Set up the device tracker."""
    yaml_path = hass.config.path(YAML_DEVICES)

    conf = config.get(DOMAIN, [])
    conf = conf[0] if conf else {}
    consider_home = conf.get(CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME)

    defaults = conf.get(CONF_NEW_DEVICE_DEFAULTS, {})
    track_new = conf.get(CONF_TRACK_NEW)
    if track_new is None:
        track_new = defaults.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW)

    devices = await async_load_config(yaml_path, hass, consider_home)
    tracker = DeviceTracker(
        hass, consider_home, track_new, defaults, devices)

    async def async_setup_platform(p_type, p_config, disc_info=None):
        """Set up a device tracker platform."""
        platform = await async_prepare_setup_platform(
            hass, config, DOMAIN, p_type)
        if platform is None:
            return

        _LOGGER.info("Setting up %s.%s", DOMAIN, p_type)
        try:
            scanner = None
            setup = None
            if hasattr(platform, 'async_get_scanner'):
                scanner = await platform.async_get_scanner(
                    hass, {DOMAIN: p_config})
            elif hasattr(platform, 'get_scanner'):
                scanner = await hass.async_add_job(
                    platform.get_scanner, hass, {DOMAIN: p_config})
            elif hasattr(platform, 'async_setup_scanner'):
                setup = await platform.async_setup_scanner(
                    hass, p_config, tracker.async_see, disc_info)
            elif hasattr(platform, 'setup_scanner'):
                setup = await hass.async_add_job(
                    platform.setup_scanner, hass, p_config, tracker.see,
                    disc_info)
            elif hasattr(platform, 'async_setup_entry'):
                setup = await platform.async_setup_entry(
                    hass, p_config, tracker.async_see)
            else:
                raise HomeAssistantError("Invalid device_tracker platform.")

            if scanner:
                async_setup_scanner_platform(
                    hass, p_config, scanner, tracker.async_see, p_type)
                return

            if not setup:
                _LOGGER.error("Error setting up platform %s", p_type)
                return

        except Exception:  # pylint: disable=broad-except
            _LOGGER.exception("Error setting up platform %s", p_type)

    hass.data[DOMAIN] = async_setup_platform

    setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config
                   in config_per_platform(config, DOMAIN)]
    if setup_tasks:
        await asyncio.wait(setup_tasks, loop=hass.loop)

    tracker.async_setup_group()

    async def async_platform_discovered(platform, info):
        """Load a platform."""
        await async_setup_platform(platform, {}, disc_info=info)

    discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered)

    # Clean up stale devices
    async_track_utc_time_change(
        hass, tracker.async_update_stale, second=range(0, 60, 5))

    async def async_see_service(call):
        """Service to see a device."""
        # Temp workaround for iOS, introduced in 0.65
        data = dict(call.data)
        data.pop('hostname', None)
        data.pop('battery_status', None)
        await tracker.async_see(**data)

    hass.services.async_register(
        DOMAIN, SERVICE_SEE, async_see_service, SERVICE_SEE_PAYLOAD_SCHEMA)

    # restore
    await tracker.async_setup_tracked_device()
    return True
Пример #36
0
def async_setup(hass: HomeAssistantType, config: ConfigType):
    """Setup device tracker."""
    yaml_path = hass.config.path(YAML_DEVICES)

    try:
        conf = config.get(DOMAIN, [])
    except vol.Invalid as ex:
        async_log_exception(ex, DOMAIN, config, hass)
        return False
    else:
        conf = conf[0] if len(conf) > 0 else {}
        consider_home = conf.get(CONF_CONSIDER_HOME,
                                 timedelta(seconds=DEFAULT_CONSIDER_HOME))
        track_new = conf.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW)

    devices = yield from async_load_config(yaml_path, hass, consider_home)
    tracker = DeviceTracker(hass, consider_home, track_new, devices)

    # update tracked devices
    update_tasks = [device.async_update_ha_state() for device in devices
                    if device.track]
    if update_tasks:
        yield from asyncio.wait(update_tasks, loop=hass.loop)

    @asyncio.coroutine
    def async_setup_platform(p_type, p_config, disc_info=None):
        """Setup a device tracker platform."""
        platform = yield from async_prepare_setup_platform(
            hass, config, DOMAIN, p_type)
        if platform is None:
            return

        try:
            if hasattr(platform, 'get_scanner'):
                scanner = yield from hass.loop.run_in_executor(
                    None, platform.get_scanner, hass, {DOMAIN: p_config})

                if scanner is None:
                    _LOGGER.error('Error setting up platform %s', p_type)
                    return

                yield from async_setup_scanner_platform(
                    hass, p_config, scanner, tracker.async_see)
                return

            ret = yield from hass.loop.run_in_executor(
                None, platform.setup_scanner, hass, p_config, tracker.see)
            if not ret:
                _LOGGER.error('Error setting up platform %s', p_type)
        except Exception:  # pylint: disable=broad-except
            _LOGGER.exception('Error setting up platform %s', p_type)

    setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config
                   in config_per_platform(config, DOMAIN)]
    if setup_tasks:
        yield from asyncio.wait(setup_tasks, loop=hass.loop)

    yield from tracker.async_setup_group()

    @callback
    def async_device_tracker_discovered(service, info):
        """Called when a device tracker platform is discovered."""
        hass.async_add_job(
            async_setup_platform(DISCOVERY_PLATFORMS[service], {}, info))

    discovery.async_listen(
        hass, DISCOVERY_PLATFORMS.keys(), async_device_tracker_discovered)

    # Clean up stale devices
    async_track_utc_time_change(
        hass, tracker.async_update_stale, second=range(0, 60, 5))

    @asyncio.coroutine
    def async_see_service(call):
        """Service to see a device."""
        args = {key: value for key, value in call.data.items() if key in
                (ATTR_MAC, ATTR_DEV_ID, ATTR_HOST_NAME, ATTR_LOCATION_NAME,
                 ATTR_GPS, ATTR_GPS_ACCURACY, ATTR_BATTERY, ATTR_ATTRIBUTES)}
        yield from tracker.async_see(**args)

    descriptions = yield from hass.loop.run_in_executor(
        None, load_yaml_config_file,
        os.path.join(os.path.dirname(__file__), 'services.yaml')
    )
    hass.services.async_register(
        DOMAIN, SERVICE_SEE, async_see_service, descriptions.get(SERVICE_SEE))

    return True
Пример #37
0
 async def async_added_to_hass(self):
     """Start fetching data."""
     await self._fetch_data()
     async_track_utc_time_change(
         self.hass, self._update, minute=31, second=0)
Пример #38
0
 def start_auto_updater(self):
     """Start the autoupdater to update HASS while cover is moving."""
     if self._unsubscribe_auto_updater is None:
         self._unsubscribe_auto_updater = async_track_utc_time_change(
             self.hass, self.auto_updater_hook)
Пример #39
0
def async_setup(hass: HomeAssistantType, config: ConfigType):
    """Set up the device tracker."""
    yaml_path = hass.config.path(YAML_DEVICES)

    conf = config.get(DOMAIN, [])
    conf = conf[0] if conf else {}
    consider_home = conf.get(CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME)
    track_new = conf.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW)

    devices = yield from async_load_config(yaml_path, hass, consider_home)
    tracker = DeviceTracker(hass, consider_home, track_new, devices)

    @asyncio.coroutine
    def async_setup_platform(p_type, p_config, disc_info=None):
        """Set up a device tracker platform."""
        platform = yield from async_prepare_setup_platform(
            hass, config, DOMAIN, p_type)
        if platform is None:
            return

        _LOGGER.info("Setting up %s.%s", DOMAIN, p_type)
        try:
            scanner = None
            setup = None
            if hasattr(platform, 'async_get_scanner'):
                scanner = yield from platform.async_get_scanner(
                    hass, {DOMAIN: p_config})
            elif hasattr(platform, 'get_scanner'):
                scanner = yield from hass.async_add_job(
                    platform.get_scanner, hass, {DOMAIN: p_config})
            elif hasattr(platform, 'async_setup_scanner'):
                setup = yield from platform.async_setup_scanner(
                    hass, p_config, tracker.async_see, disc_info)
            elif hasattr(platform, 'setup_scanner'):
                setup = yield from hass.async_add_job(
                    platform.setup_scanner, hass, p_config, tracker.see,
                    disc_info)
            else:
                raise HomeAssistantError("Invalid device_tracker platform.")

            if scanner:
                async_setup_scanner_platform(
                    hass, p_config, scanner, tracker.async_see, p_type)
                return

            if not setup:
                _LOGGER.error("Error setting up platform %s", p_type)
                return

        except Exception:  # pylint: disable=broad-except
            _LOGGER.exception("Error setting up platform %s", p_type)

    setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config
                   in config_per_platform(config, DOMAIN)]
    if setup_tasks:
        yield from asyncio.wait(setup_tasks, loop=hass.loop)

    tracker.async_setup_group()

    @callback
    def async_device_tracker_discovered(service, info):
        """Handle the discovery of device tracker platforms."""
        hass.async_add_job(
            async_setup_platform(DISCOVERY_PLATFORMS[service], {}, info))

    discovery.async_listen(
        hass, DISCOVERY_PLATFORMS.keys(), async_device_tracker_discovered)

    @asyncio.coroutine
    def async_platform_discovered(platform, info):
        """Load a platform."""
        yield from async_setup_platform(platform, {}, disc_info=info)

    discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered)

    # Clean up stale devices
    async_track_utc_time_change(
        hass, tracker.async_update_stale, second=range(0, 60, 5))

    @asyncio.coroutine
    def async_see_service(call):
        """Service to see a device."""
        args = {key: value for key, value in call.data.items() if key in
                (ATTR_MAC, ATTR_DEV_ID, ATTR_HOST_NAME, ATTR_LOCATION_NAME,
                 ATTR_GPS, ATTR_GPS_ACCURACY, ATTR_BATTERY, ATTR_ATTRIBUTES)}
        yield from tracker.async_see(**args)

    descriptions = yield from hass.async_add_job(
        load_yaml_config_file,
        os.path.join(os.path.dirname(__file__), 'services.yaml')
    )
    hass.services.async_register(
        DOMAIN, SERVICE_SEE, async_see_service, descriptions.get(SERVICE_SEE))

    # restore
    yield from tracker.async_setup_tracked_device()
    return True