first
This commit is contained in:
53
backend/app/services/scanner.py
Normal file
53
backend/app/services/scanner.py
Normal file
@@ -0,0 +1,53 @@
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from app.database import get_engine
|
||||
from app.ha_client import ha_client, normalize_entity
|
||||
from app.models import EntityCache
|
||||
from app.scan_state import scan_state
|
||||
|
||||
|
||||
async def run_scan():
|
||||
scan_state.start()
|
||||
try:
|
||||
states = await ha_client.fetch_all_states()
|
||||
scan_state.total = len(states)
|
||||
|
||||
# Tenter de récupérer le registry (peut échouer si WS non dispo)
|
||||
registry_map: dict[str, dict] = {}
|
||||
try:
|
||||
registry = await ha_client.fetch_entity_registry()
|
||||
registry_map = {e["entity_id"]: e for e in registry}
|
||||
except Exception:
|
||||
pass # On continue sans registry
|
||||
|
||||
with Session(get_engine()) as session:
|
||||
for i, state in enumerate(states):
|
||||
entity_id = state.get("entity_id", "")
|
||||
reg_entry = registry_map.get(entity_id)
|
||||
normalized = normalize_entity(state, reg_entry)
|
||||
|
||||
existing = session.get(EntityCache, entity_id)
|
||||
if existing:
|
||||
for key, value in normalized.items():
|
||||
if key != "entity_id":
|
||||
setattr(existing, key, value)
|
||||
existing.fetched_at = datetime.utcnow()
|
||||
else:
|
||||
entity = EntityCache(
|
||||
**normalized,
|
||||
fetched_at=datetime.utcnow(),
|
||||
)
|
||||
session.add(entity)
|
||||
|
||||
scan_state.progress = i + 1
|
||||
|
||||
session.commit()
|
||||
|
||||
scan_state.finish(len(states))
|
||||
|
||||
except Exception as e:
|
||||
scan_state.fail(str(e))
|
||||
raise
|
||||
Reference in New Issue
Block a user