Compare commits
8 Commits
feature/ap
...
otto/quali
| Author | SHA1 | Date | |
|---|---|---|---|
| 8841a68c8d | |||
| 6540d62ff7 | |||
| 6b1e2ad0dc | |||
| 6bba8f5947 | |||
| 009d4b68cb | |||
| 9016dbad18 | |||
| d81ebf399c | |||
| 43fb8fac2e |
1
app/__init__.py
Normal file
1
app/__init__.py
Normal file
@@ -0,0 +1 @@
|
|||||||
|
"""SillyHome Next application package."""
|
||||||
1
app/api/__init__.py
Normal file
1
app/api/__init__.py
Normal file
@@ -0,0 +1 @@
|
|||||||
|
"""API package."""
|
||||||
1
app/api/v1/__init__.py
Normal file
1
app/api/v1/__init__.py
Normal file
@@ -0,0 +1 @@
|
|||||||
|
"""Version 1 API package."""
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import List, Sequence
|
from collections.abc import Sequence
|
||||||
|
|
||||||
from fastapi import APIRouter
|
from fastapi import APIRouter, Depends
|
||||||
|
|
||||||
|
from app.dependencies import get_ha_reader
|
||||||
from app.ha.models import HaEntitySummary
|
from app.ha.models import HaEntitySummary
|
||||||
|
from app.ha.reader import HaReader
|
||||||
|
|
||||||
router = APIRouter(prefix="/v1", tags=["entities"])
|
router = APIRouter(prefix="/v1", tags=["entities"])
|
||||||
|
|
||||||
@@ -13,7 +15,7 @@ router = APIRouter(prefix="/v1", tags=["entities"])
|
|||||||
"/entities",
|
"/entities",
|
||||||
summary="Home-Assistant-Entities auflisten",
|
summary="Home-Assistant-Entities auflisten",
|
||||||
description="Gibt eine kompakte Zusammenfassung aller erreichbaren HA-Entitäten zurück.",
|
description="Gibt eine kompakte Zusammenfassung aller erreichbaren HA-Entitäten zurück.",
|
||||||
response_model=List[HaEntitySummary],
|
response_model=list[HaEntitySummary],
|
||||||
)
|
)
|
||||||
def list_entities() -> Sequence[HaEntitySummary]:
|
def list_entities(reader: HaReader = Depends(get_ha_reader)) -> Sequence[HaEntitySummary]:
|
||||||
raise NotImplementedError("Integration mit dem HA-Client folgt in separatem Issue.")
|
return reader.read_entities()
|
||||||
|
|||||||
21
app/config.py
Normal file
21
app/config.py
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Settings:
|
||||||
|
ha_url: str | None = None
|
||||||
|
ha_token: str | None = None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ha_configured(self) -> bool:
|
||||||
|
return bool(self.ha_url and self.ha_token)
|
||||||
|
|
||||||
|
|
||||||
|
def load_settings() -> Settings:
|
||||||
|
return Settings(
|
||||||
|
ha_url=os.getenv("SILLYHOME_HA_URL") or os.getenv("HA_URL"),
|
||||||
|
ha_token=os.getenv("SILLYHOME_HA_TOKEN") or os.getenv("HA_TOKEN"),
|
||||||
|
)
|
||||||
15
app/dependencies.py
Normal file
15
app/dependencies.py
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import HTTPException, Request, status
|
||||||
|
|
||||||
|
from app.ha.reader import HaReader
|
||||||
|
|
||||||
|
|
||||||
|
def get_ha_reader(request: Request) -> HaReader:
|
||||||
|
reader = getattr(request.app.state, "ha_reader", None)
|
||||||
|
if not isinstance(reader, HaReader):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||||
|
detail="Home Assistant is not configured.",
|
||||||
|
)
|
||||||
|
return reader
|
||||||
1
app/ha/__init__.py
Normal file
1
app/ha/__init__.py
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# sillyhome-next.ha
|
||||||
38
app/ha/client.py
Normal file
38
app/ha/client.py
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class HaClientSettings:
|
||||||
|
url: str
|
||||||
|
token: str
|
||||||
|
timeout_seconds: int = 10
|
||||||
|
|
||||||
|
|
||||||
|
class HaClient:
|
||||||
|
def __init__(self, settings: HaClientSettings) -> None:
|
||||||
|
self._settings = settings
|
||||||
|
self._session = requests.Session()
|
||||||
|
self._session.headers.update({
|
||||||
|
"Authorization": f"Bearer {settings.token}",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
})
|
||||||
|
|
||||||
|
def list_entities(self) -> list[dict[str, Any]]:
|
||||||
|
response = self._session.get(
|
||||||
|
f"{self._settings.url}/api/states",
|
||||||
|
timeout=self._settings.timeout_seconds,
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
payload = response.json()
|
||||||
|
if not isinstance(payload, list):
|
||||||
|
msg = "Home Assistant states response must be a list."
|
||||||
|
raise TypeError(msg)
|
||||||
|
return payload
|
||||||
19
app/ha/models.py
Normal file
19
app/ha/models.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class HaState(BaseModel):
|
||||||
|
entity_id: str
|
||||||
|
state: str
|
||||||
|
attributes: dict[str, object] | None = None
|
||||||
|
last_changed: str | None = None
|
||||||
|
last_updated: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class HaEntitySummary(BaseModel):
|
||||||
|
entity_id: str
|
||||||
|
domain: str
|
||||||
|
state_class: str | None = None
|
||||||
|
device_class: str | None = None
|
||||||
|
unit_of_measurement: str | None = None
|
||||||
39
app/ha/reader.py
Normal file
39
app/ha/reader.py
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.ha.client import HaClient
|
||||||
|
from app.ha.models import HaEntitySummary
|
||||||
|
|
||||||
|
|
||||||
|
class HaReader:
|
||||||
|
def __init__(self, client: HaClient) -> None:
|
||||||
|
self._client = client
|
||||||
|
|
||||||
|
def read_entities(self) -> Sequence[HaEntitySummary]:
|
||||||
|
entities = self._client.list_entities()
|
||||||
|
summaries: list[HaEntitySummary] = []
|
||||||
|
for item in entities:
|
||||||
|
entity_id = item.get("entity_id", "")
|
||||||
|
if "." not in entity_id:
|
||||||
|
continue
|
||||||
|
domain = entity_id.split(".", 1)[0]
|
||||||
|
raw_attributes = item.get("attributes") or {}
|
||||||
|
attributes: dict[str, Any] = raw_attributes if isinstance(raw_attributes, dict) else {}
|
||||||
|
summaries.append(
|
||||||
|
HaEntitySummary(
|
||||||
|
entity_id=entity_id,
|
||||||
|
domain=domain,
|
||||||
|
state_class=_optional_str(attributes.get("state_class")),
|
||||||
|
device_class=_optional_str(attributes.get("device_class")),
|
||||||
|
unit_of_measurement=_optional_str(attributes.get("unit_of_measurement")),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return summaries
|
||||||
|
|
||||||
|
|
||||||
|
def _optional_str(value: object) -> str | None:
|
||||||
|
if value is None or value == "":
|
||||||
|
return None
|
||||||
|
return str(value)
|
||||||
28
app/main.py
28
app/main.py
@@ -1,12 +1,40 @@
|
|||||||
|
from collections.abc import AsyncIterator
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
|
||||||
|
from app.api.v1.entities import router as entities_router
|
||||||
|
from app.config import load_settings
|
||||||
|
from app.ha.client import HaClient, HaClientSettings
|
||||||
|
from app.ha.reader import HaReader
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||||
|
settings = load_settings()
|
||||||
|
app.state.settings = settings
|
||||||
|
if settings.ha_configured:
|
||||||
|
client = HaClient(
|
||||||
|
settings=HaClientSettings(
|
||||||
|
url=settings.ha_url or "",
|
||||||
|
token=settings.ha_token or "",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
app.state.ha_reader = HaReader(client=client)
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="SillyHome Next API",
|
title="SillyHome Next API",
|
||||||
description="Lokales Smart-Home-Intelligenzsystem für Home Assistant.",
|
description="Lokales Smart-Home-Intelligenzsystem für Home Assistant.",
|
||||||
version="0.1.0",
|
version="0.1.0",
|
||||||
|
lifespan=lifespan,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
app.include_router(entities_router)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/health")
|
@app.get("/health")
|
||||||
def health() -> dict[str, str]:
|
def health() -> dict[str, str]:
|
||||||
return {"status": "ok"}
|
return {"status": "ok"}
|
||||||
|
|||||||
1
app/rules/__init__.py
Normal file
1
app/rules/__init__.py
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# sillyhome-next.rules
|
||||||
15
app/rules/heating.py
Normal file
15
app/rules/heating.py
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from app.ha.models import HaEntitySummary
|
||||||
|
from app.rules.recommender import Rule
|
||||||
|
|
||||||
|
|
||||||
|
class HeatingRule(Rule):
|
||||||
|
def matches(self, entities: Sequence[HaEntitySummary]) -> bool:
|
||||||
|
domains = {item.domain for item in entities}
|
||||||
|
return "climate" in domains or "sensor" in domains
|
||||||
|
|
||||||
|
def recommendation(self, entities: Sequence[HaEntitySummary]) -> str:
|
||||||
|
return "Prüfe Heizungsregelung: Aktiviere energiesparenden Modus bei Abwesenheit."
|
||||||
25
app/rules/recommender.py
Normal file
25
app/rules/recommender.py
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from app.ha.models import HaEntitySummary
|
||||||
|
|
||||||
|
|
||||||
|
class Rule:
|
||||||
|
def matches(self, entities: Sequence[HaEntitySummary]) -> bool:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def recommendation(self, entities: Sequence[HaEntitySummary]) -> str:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
|
||||||
|
class Recommender:
|
||||||
|
def __init__(self, rules: Sequence[Rule]) -> None:
|
||||||
|
self._rules = rules
|
||||||
|
|
||||||
|
def run(self, entities: Sequence[HaEntitySummary]) -> list[str]:
|
||||||
|
results: list[str] = []
|
||||||
|
for rule in self._rules:
|
||||||
|
if rule.matches(entities):
|
||||||
|
results.append(rule.recommendation(entities))
|
||||||
|
return results
|
||||||
@@ -7,10 +7,12 @@ dependencies = [
|
|||||||
"fastapi>=0.110.0",
|
"fastapi>=0.110.0",
|
||||||
"uvicorn[standard]>=0.29.0",
|
"uvicorn[standard]>=0.29.0",
|
||||||
"pydantic>=2.6.0",
|
"pydantic>=2.6.0",
|
||||||
|
"requests>=2.31.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
dev = [
|
dev = [
|
||||||
|
"httpx2>=2.3.0",
|
||||||
"pytest>=8.0.0",
|
"pytest>=8.0.0",
|
||||||
"ruff>=0.4.0",
|
"ruff>=0.4.0",
|
||||||
"mypy>=1.9.0",
|
"mypy>=1.9.0",
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import requests
|
import requests
|
||||||
import json
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
p = Path('/root/.openclaw/secrets/gitea.env')
|
p = Path('/root/.openclaw/secrets/gitea.env')
|
||||||
|
|||||||
@@ -1,10 +1,46 @@
|
|||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.ha.models import HaEntitySummary
|
||||||
|
from app.ha.reader import HaReader
|
||||||
from app.main import app
|
from app.main import app
|
||||||
|
|
||||||
client = TestClient(app)
|
|
||||||
|
class FakeHaReader(HaReader):
|
||||||
|
def __init__(self) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def read_entities(self) -> Sequence[HaEntitySummary]:
|
||||||
|
return [HaEntitySummary(entity_id="sensor.temperature", domain="sensor")]
|
||||||
|
|
||||||
|
|
||||||
def test_openapi_docs_are_available() -> None:
|
def test_openapi_docs_are_available() -> None:
|
||||||
response = client.get("/docs")
|
with TestClient(app) as client:
|
||||||
|
response = client.get("/docs")
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert "SillyHome Next API" in response.text
|
assert "SillyHome Next API" in response.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_entities_returns_reader_data() -> None:
|
||||||
|
with TestClient(app) as client:
|
||||||
|
app.state.ha_reader = FakeHaReader()
|
||||||
|
response = client.get("/v1/entities")
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == [
|
||||||
|
{
|
||||||
|
"entity_id": "sensor.temperature",
|
||||||
|
"domain": "sensor",
|
||||||
|
"state_class": None,
|
||||||
|
"device_class": None,
|
||||||
|
"unit_of_measurement": None,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_entities_returns_503_without_home_assistant_config() -> None:
|
||||||
|
with TestClient(app) as client:
|
||||||
|
if hasattr(app.state, "ha_reader"):
|
||||||
|
delattr(app.state, "ha_reader")
|
||||||
|
response = client.get("/v1/entities")
|
||||||
|
assert response.status_code == 503
|
||||||
|
|||||||
37
tests/ha/test_ha_reader.py
Normal file
37
tests/ha/test_ha_reader.py
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app.ha.client import HaClient, HaClientSettings
|
||||||
|
from app.ha.reader import HaReader
|
||||||
|
|
||||||
|
|
||||||
|
class FakeHaClient(HaClient):
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__(HaClientSettings(url="http://test", token="token"))
|
||||||
|
|
||||||
|
def list_entities(self) -> list[dict[str, object]]:
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"entity_id": "sensor.temperature",
|
||||||
|
"state": "21.5",
|
||||||
|
"attributes": {
|
||||||
|
"state_class": "measurement",
|
||||||
|
"device_class": "temperature",
|
||||||
|
"unit_of_measurement": "°C",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"entity_id": "light.living_room",
|
||||||
|
"state": "on",
|
||||||
|
"attributes": {},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_ha_reader_returns_summaries() -> None:
|
||||||
|
reader = HaReader(FakeHaClient())
|
||||||
|
summaries = reader.read_entities()
|
||||||
|
assert len(summaries) == 2
|
||||||
|
domains = {summary.domain for summary in summaries}
|
||||||
|
assert domains == {"sensor", "light"}
|
||||||
|
sensor = next(item for item in summaries if item.entity_id == "sensor.temperature")
|
||||||
|
assert sensor.unit_of_measurement == "°C"
|
||||||
26
tests/rules/test_heating.py
Normal file
26
tests/rules/test_heating.py
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app.ha.models import HaEntitySummary
|
||||||
|
from app.rules.heating import HeatingRule
|
||||||
|
from app.rules.recommender import Recommender
|
||||||
|
|
||||||
|
|
||||||
|
def _sensor(entity_id: str) -> HaEntitySummary:
|
||||||
|
return HaEntitySummary(entity_id=entity_id, domain="sensor")
|
||||||
|
|
||||||
|
|
||||||
|
def _climate(entity_id: str) -> HaEntitySummary:
|
||||||
|
return HaEntitySummary(entity_id=entity_id, domain="climate")
|
||||||
|
|
||||||
|
|
||||||
|
def test_heating_rule_triggers() -> None:
|
||||||
|
rule = HeatingRule()
|
||||||
|
assert rule.matches([_climate("climate.living_room")])
|
||||||
|
assert rule.matches([_sensor("sensor.temperature_living")])
|
||||||
|
|
||||||
|
|
||||||
|
def test_recommender_uses_rule() -> None:
|
||||||
|
recommender = Recommender(rules=[HeatingRule()])
|
||||||
|
assert recommender.run([_climate("climate.living_room")]) == [
|
||||||
|
"Prüfe Heizungsregelung: Aktiviere energiesparenden Modus bei Abwesenheit."
|
||||||
|
]
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
from app.main import app
|
|
||||||
|
|
||||||
client = TestClient(app)
|
from app.main import app
|
||||||
|
|
||||||
|
|
||||||
def test_health_returns_ok() -> None:
|
def test_health_returns_ok() -> None:
|
||||||
response = client.get("/health")
|
with TestClient(app) as client:
|
||||||
|
response = client.get("/health")
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert response.json() == {"status": "ok"}
|
assert response.json() == {"status": "ok"}
|
||||||
|
|||||||
Reference in New Issue
Block a user