2026-09-19 13:13:29 +03:00
|
|
|
"""Фоновый опрос устройств: быстрое обнаружение недоступности (period = POLL_INTERVAL)."""
|
|
|
|
|
import asyncio
|
|
|
|
|
import logging
|
|
|
|
|
import time
|
|
|
|
|
|
|
|
|
|
from app.config import get_settings
|
2026-09-19 17:01:52 +03:00
|
|
|
from app.services import devices, events, ops
|
2026-09-19 13:13:29 +03:00
|
|
|
|
|
|
|
|
log = logging.getLogger("ros_control.poller")
|
|
|
|
|
|
|
|
|
|
|
2026-09-19 17:01:52 +03:00
|
|
|
async def cycle(last_full: dict[str, float]) -> None:
|
2026-09-19 13:13:29 +03:00
|
|
|
"""Один проход по всем устройствам (параллельно, не более MAX_CONCURRENCY одновременно)."""
|
|
|
|
|
s = get_settings()
|
2026-09-28 12:18:32 +03:00
|
|
|
ids = [d.id for d in await asyncio.to_thread(devices.list_devices)]
|
2026-09-19 13:13:29 +03:00
|
|
|
for gone in set(last_full) - set(ids):
|
|
|
|
|
del last_full[gone]
|
|
|
|
|
sem = asyncio.Semaphore(s.max_concurrency)
|
|
|
|
|
started = time.monotonic()
|
|
|
|
|
|
2026-09-19 17:01:52 +03:00
|
|
|
async def one(device_id: str) -> None:
|
2026-09-19 13:13:29 +03:00
|
|
|
async with sem:
|
|
|
|
|
full = started - last_full.get(device_id, float("-inf")) >= s.update_check_interval
|
|
|
|
|
try:
|
|
|
|
|
await ops.poll_device(device_id, full)
|
|
|
|
|
except LookupError: # удалили во время цикла
|
|
|
|
|
return
|
|
|
|
|
except Exception: # noqa: BLE001 — сбой одного устройства не должен ронять опрос остальных
|
|
|
|
|
log.exception("poll failed: device %s", device_id)
|
|
|
|
|
return
|
|
|
|
|
if full:
|
|
|
|
|
last_full[device_id] = time.monotonic()
|
|
|
|
|
|
|
|
|
|
await asyncio.gather(*(one(i) for i in ids))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def run() -> None:
|
2026-09-19 17:01:52 +03:00
|
|
|
events.set_actor("poller")
|
|
|
|
|
last_full: dict[str, float] = {}
|
2026-09-19 13:13:29 +03:00
|
|
|
interval = get_settings().poll_interval
|
|
|
|
|
while True:
|
|
|
|
|
try:
|
|
|
|
|
await cycle(last_full)
|
|
|
|
|
except Exception: # noqa: BLE001
|
|
|
|
|
log.exception("poll cycle failed")
|
|
|
|
|
await asyncio.sleep(interval)
|