# plugins/homeassistant/scheduler.py from __future__ import annotations import asyncio import logging from datetime import datetime, timezone from typing import TYPE_CHECKING from sqlalchemy import select from steward.core.crypto import decrypt_secret from steward.core.scheduler import ScheduledTask from . import client from .models import HomeAssistantConnection from .service import RESOURCE, SOURCE, backup_age_hours, installable, read_snapshot from .updates import advance if TYPE_CHECKING: from quart import Quart logger = logging.getLogger(__name__) # An update under way is followed each tick, with one small read of its entity. TICK_SECONDS = 15 # The whole entity list is a few hundred KB, and updates and backups change rarely. POLL_SECONDS = 300 # A step past this is given up until the next tick, whatever the client's own # timeouts did: a slow drip of bytes can keep each read inside its timeout for ever. STEP_DEADLINE_SECONDS = 60 def make_tick_task(app: "Quart") -> ScheduledTask: busy = asyncio.Lock() async def tick() -> None: if busy.locked(): return async with busy: for step in (poll, advance): try: await asyncio.wait_for(step(app), STEP_DEADLINE_SECONDS) except TimeoutError: logger.warning("Home Assistant %s gave up after %d s", step.__name__, STEP_DEADLINE_SECONDS) return ScheduledTask(name="homeassistant_tick", coro_factory=tick, interval_seconds=TICK_SECONDS, run_on_startup=True) def is_due(connection, now: datetime) -> bool: """Whether to poll. Never after a refusal: another refused request counts toward Home Assistant banning this address.""" if connection.refused: return False if connection.last_polled_at is None: return True return (now - connection.last_polled_at).total_seconds() >= POLL_SECONDS - TICK_SECONDS / 2 async def poll(app: "Quart", transport=None) -> None: from steward.core.alerts import MetricBatch now = datetime.now(timezone.utc) async with app.db_sessionmaker() as session: connection = (await session.execute(select(HomeAssistantConnection))).scalars().first() if connection is None or not is_due(connection, now): return token = decrypt_secret(connection.token, context="Home Assistant token") snapshot, error, refused = None, None, False try: snapshot = read_snapshot(await client.read_states(connection.url, token, connection.verify_tls, transport)) except client.Refused as exc: error, refused = str(exc), True except client.Unreachable as exc: error = str(exc) async with app.db_sessionmaker() as session: async with session.begin(): row = await session.get(HomeAssistantConnection, connection.id) if row is None: # removed while it was being polled return batch = MetricBatch() row.last_polled_at, row.last_error, row.refused = now, error, refused if snapshot is None: batch.add(source_module=SOURCE, resource_name=RESOURCE, metric_name="is_up", value=0.0, recorded_at=now) else: row.last_ok_at = now row.updates, row.backup, row.automation = snapshot["updates"], snapshot["backup"], snapshot["automation"] batch.add(source_module=SOURCE, resource_name=RESOURCE, metric_name="is_up", value=1.0, recorded_at=now) batch.add(source_module=SOURCE, resource_name=RESOURCE, metric_name="updates_waiting", value=len(installable(row)), recorded_at=now) age = backup_age_hours(snapshot["backup"], now) if age is not None: batch.add(source_module=SOURCE, resource_name=RESOURCE, metric_name="backup_age_hours", value=age, recorded_at=now) await batch.record(session)