Compare commits
23 Commits
b7efae61c4
...
polyfill
| Author | SHA1 | Date | |
|---|---|---|---|
|
5f7af7574c
|
|||
|
0c73e36e82
|
|||
|
01b60671db
|
|||
|
b60fdfced4
|
|||
|
0cd0c6de41
|
|||
|
ecf5aebc3c
|
|||
|
79d87aff6a
|
|||
|
b1e9b201d1
|
|||
|
1eff8a2044
|
|||
|
8fd0921a08
|
|||
|
7304a017c2
|
|||
|
db6da4815c
|
|||
|
54f53705c0
|
|||
|
f8144496b3
|
|||
|
50e7402152
|
|||
|
eb822c0318
|
|||
|
acb5e0a209
|
|||
|
4b196c1278
|
|||
|
7e04991d64
|
|||
|
cc3364068a
|
|||
|
c1cbca39bf
|
|||
|
6271f46019
|
|||
|
6bf8ac3f99
|
230
DOCKER_GUIDE.md
Normal file
230
DOCKER_GUIDE.md
Normal file
@@ -0,0 +1,230 @@
|
||||
# Docker Guide für Home Automation
|
||||
|
||||
Vollständige Anleitung zum Ausführen aller Services mit Docker/finch.
|
||||
|
||||
## Quick Start - Alle Services starten
|
||||
|
||||
### Linux Server (empfohlen - mit Docker Network)
|
||||
|
||||
```bash
|
||||
# 1. Images bauen
|
||||
docker build -t api:dev -f apps/api/Dockerfile .
|
||||
docker build -t ui:dev -f apps/ui/Dockerfile .
|
||||
docker build -t abstraction:dev -f apps/abstraction/Dockerfile .
|
||||
docker build -t simulator:dev -f apps/simulator/Dockerfile .
|
||||
|
||||
# 2. Netzwerk erstellen
|
||||
docker network create home-automation
|
||||
|
||||
# 3. Abstraction Layer (MQTT Worker)
|
||||
docker run -d --name abstraction \
|
||||
--network home-automation \
|
||||
-v $(pwd)/config:/app/config:ro \
|
||||
-e MQTT_BROKER=172.16.2.16 \
|
||||
-e REDIS_HOST=172.23.1.116 \
|
||||
-e REDIS_DB=8 \
|
||||
abstraction:dev
|
||||
|
||||
# 4. API Server
|
||||
docker run -d --name api \
|
||||
--network home-automation \
|
||||
-p 8001:8001 \
|
||||
-v $(pwd)/config:/app/config:ro \
|
||||
-e MQTT_BROKER=172.16.2.16 \
|
||||
-e REDIS_HOST=172.23.1.116 \
|
||||
-e REDIS_DB=8 \
|
||||
api:dev
|
||||
|
||||
# 5. Web UI
|
||||
docker run -d --name ui \
|
||||
--network home-automation \
|
||||
-p 8002:8002 \
|
||||
-e API_BASE=http://api:8001 \
|
||||
ui:dev
|
||||
|
||||
# 6. Device Simulator (optional)
|
||||
docker run -d --name simulator \
|
||||
--network home-automation \
|
||||
-p 8010:8010 \
|
||||
-e MQTT_BROKER=172.16.2.16 \
|
||||
simulator:dev
|
||||
```
|
||||
|
||||
### macOS mit finch/nerdctl (Alternative)
|
||||
|
||||
```bash
|
||||
# Images bauen (wie oben)
|
||||
|
||||
# Abstraction Layer
|
||||
docker run -d --name abstraction \
|
||||
-v $(pwd)/config:/app/config:ro \
|
||||
-e MQTT_BROKER=172.16.2.16 \
|
||||
-e REDIS_HOST=172.23.1.116 \
|
||||
-e REDIS_DB=8 \
|
||||
abstraction:dev
|
||||
|
||||
# API Server
|
||||
docker run -d --name api \
|
||||
-p 8001:8001 \
|
||||
-v $(pwd)/config:/app/config:ro \
|
||||
-e MQTT_BROKER=172.16.2.16 \
|
||||
-e REDIS_HOST=172.23.1.116 \
|
||||
-e REDIS_DB=8 \
|
||||
api:dev
|
||||
|
||||
# Web UI (mit host.docker.internal für macOS)
|
||||
docker run -d --name ui \
|
||||
--add-host=host.docker.internal:host-gateway \
|
||||
-p 8002:8002 \
|
||||
-e API_BASE=http://host.docker.internal:8001 \
|
||||
ui:dev
|
||||
|
||||
# Device Simulator
|
||||
docker run -d --name simulator \
|
||||
-p 8010:8010 \
|
||||
-e MQTT_BROKER=172.16.2.16 \
|
||||
simulator:dev
|
||||
```
|
||||
|
||||
## Zugriff
|
||||
|
||||
- **Web UI**: http://<server-ip>:8002
|
||||
- **API Docs**: http://<server-ip>:8001/docs
|
||||
- **Simulator**: http://<server-ip>:8010
|
||||
|
||||
Auf localhost: `127.0.0.1` oder `localhost`
|
||||
|
||||
## finch/nerdctl Besonderheiten
|
||||
|
||||
### Port-Binding Verhalten (nur macOS/Windows)
|
||||
|
||||
**Standard Docker auf Linux:**
|
||||
- `-p 8001:8001` → bindet auf `0.0.0.0:8001` (von überall erreichbar)
|
||||
|
||||
**finch/nerdctl auf macOS:**
|
||||
- `-p 8001:8001` → bindet auf `127.0.0.1:8001` (nur localhost)
|
||||
- Dies ist ein **Security-Feature** von nerdctl
|
||||
- **Auf Linux-Servern ist das KEIN Problem!**
|
||||
|
||||
### Container-to-Container Kommunikation
|
||||
|
||||
**Linux (empfohlen):**
|
||||
```bash
|
||||
# Docker Network verwenden - Container sprechen sich mit Namen an
|
||||
docker network create home-automation
|
||||
docker run --network home-automation --name api ...
|
||||
docker run --network home-automation -e API_BASE=http://api:8001 ui ...
|
||||
```
|
||||
|
||||
**macOS mit finch:**
|
||||
```bash
|
||||
# host.docker.internal verwenden
|
||||
docker run --add-host=host.docker.internal:host-gateway \
|
||||
-e API_BASE=http://host.docker.internal:8001 ui ...
|
||||
```
|
||||
|
||||
## Container verwalten
|
||||
|
||||
```bash
|
||||
# Alle Container anzeigen
|
||||
docker ps
|
||||
|
||||
# Logs anschauen
|
||||
docker logs api
|
||||
docker logs ui -f # Follow mode
|
||||
|
||||
# Container stoppen
|
||||
docker stop api ui abstraction simulator
|
||||
|
||||
# Container entfernen
|
||||
docker rm api ui abstraction simulator
|
||||
|
||||
# Alles neu starten
|
||||
docker stop api ui abstraction simulator && \
|
||||
docker rm api ui abstraction simulator && \
|
||||
# ... dann Quick Start Befehle von oben
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### UI zeigt "Keine Räume oder Geräte konfiguriert"
|
||||
|
||||
**Problem:** UI kann API nicht erreichen
|
||||
|
||||
**Linux - Lösung:**
|
||||
```bash
|
||||
# Verwende Docker Network
|
||||
docker network create home-automation
|
||||
docker stop ui && docker rm ui
|
||||
docker run -d --name ui \
|
||||
--network home-automation \
|
||||
-p 8002:8002 \
|
||||
-e API_BASE=http://api:8001 \
|
||||
ui:dev
|
||||
```
|
||||
|
||||
**macOS/finch - Lösung:**
|
||||
```bash
|
||||
docker stop ui && docker rm ui
|
||||
docker run -d --name ui \
|
||||
--add-host=host.docker.internal:host-gateway \
|
||||
-p 8002:8002 \
|
||||
-e API_BASE=http://host.docker.internal:8001 \
|
||||
ui:dev
|
||||
```
|
||||
|
||||
### "Connection refused" in Logs
|
||||
|
||||
**Check 1:** Ist die API gestartet?
|
||||
```bash
|
||||
docker ps | grep api
|
||||
curl http://127.0.0.1:8001/health
|
||||
```
|
||||
|
||||
**Check 2:** Hat UI die richtige API_BASE?
|
||||
```bash
|
||||
docker inspect ui | grep API_BASE
|
||||
```
|
||||
|
||||
### Port bereits belegt
|
||||
|
||||
```bash
|
||||
# Prüfe welcher Prozess Port 8001 nutzt
|
||||
lsof -i :8001
|
||||
|
||||
# Oder mit netstat
|
||||
netstat -an | grep 8001
|
||||
|
||||
# Alte Container aufräumen
|
||||
docker ps -a | grep -E "api|ui|abstraction|simulator"
|
||||
docker rm -f <container-id>
|
||||
```
|
||||
|
||||
## Produktiv-Deployment
|
||||
|
||||
Für Produktion auf **Linux-Servern** empfohlen:
|
||||
|
||||
1. **Docker Compose** (siehe `infra/docker-compose.yml`)
|
||||
2. **Docker Network** für Service Discovery (siehe Linux Quick Start oben)
|
||||
3. **Volume Mounts** für Persistenz
|
||||
4. **Health Checks** in Kubernetes/Compose (nicht im Dockerfile)
|
||||
|
||||
### Beispiel mit Docker Network (Linux)
|
||||
|
||||
```bash
|
||||
# Netzwerk erstellen
|
||||
docker network create home-automation
|
||||
|
||||
# Services starten (alle im gleichen Netzwerk)
|
||||
docker run -d --name api --network home-automation \
|
||||
-p 8001:8001 \
|
||||
-v $(pwd)/config:/app/config:ro \
|
||||
api:dev
|
||||
|
||||
docker run -d --name ui --network home-automation \
|
||||
-p 8002:8002 \
|
||||
-e API_BASE=http://api:8001 \
|
||||
ui:dev
|
||||
```
|
||||
|
||||
**Vorteil:** Service Discovery über Container-Namen, keine `--add-host` Tricks nötig.
|
||||
@@ -32,7 +32,7 @@ docker build -t abstraction:dev -f apps/abstraction/Dockerfile .
|
||||
```bash
|
||||
docker run --rm \
|
||||
-v $(pwd)/config:/app/config:ro \
|
||||
-e MQTT_BROKER=172.16.2.16 \
|
||||
-e MQTT_BROKER=172.23.1.102 \
|
||||
-e MQTT_PORT=1883 \
|
||||
-e REDIS_HOST=172.23.1.116 \
|
||||
-e REDIS_PORT=6379 \
|
||||
|
||||
@@ -16,10 +16,14 @@ from aiomqtt import Client
|
||||
from pydantic import ValidationError
|
||||
|
||||
from packages.home_capabilities import LightState, ThermostatState
|
||||
from apps.abstraction.transformation import (
|
||||
transform_abstract_to_vendor,
|
||||
transform_vendor_to_abstract
|
||||
)
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
level=logging.DEBUG,
|
||||
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -38,8 +42,8 @@ def load_config(config_path: Path) -> dict[str, Any]:
|
||||
logger.warning(f"Config file not found: {config_path}, using defaults")
|
||||
return {
|
||||
"mqtt": {
|
||||
"broker": "172.16.2.16",
|
||||
"port": 1883,
|
||||
"broker": os.getenv("MQTT_BROKER", "localhost"),
|
||||
"port": int(os.getenv("MQTT_PORT", "1883")),
|
||||
"client_id": "home-automation-abstraction",
|
||||
"keepalive": 60
|
||||
},
|
||||
@@ -127,6 +131,7 @@ async def handle_abstract_set(
|
||||
mqtt_client: Client,
|
||||
device_id: str,
|
||||
device_type: str,
|
||||
device_technology: str,
|
||||
vendor_topic: str,
|
||||
payload: dict[str, Any]
|
||||
) -> None:
|
||||
@@ -136,21 +141,22 @@ async def handle_abstract_set(
|
||||
mqtt_client: MQTT client instance
|
||||
device_id: Device identifier
|
||||
device_type: Device type (e.g., 'light', 'thermostat')
|
||||
device_technology: Technology identifier (e.g., 'zigbee2mqtt')
|
||||
vendor_topic: Vendor-specific SET topic
|
||||
payload: Message payload
|
||||
"""
|
||||
# Extract actual payload (remove type wrapper if present)
|
||||
vendor_payload = payload.get("payload", payload)
|
||||
abstract_payload = payload.get("payload", payload)
|
||||
|
||||
# Validate payload based on device type
|
||||
try:
|
||||
if device_type == "light":
|
||||
# Validate light SET payload (power and/or brightness)
|
||||
LightState.model_validate(vendor_payload)
|
||||
LightState.model_validate(abstract_payload)
|
||||
elif device_type == "thermostat":
|
||||
# For thermostat SET: only allow mode and target fields
|
||||
allowed_set_fields = {"mode", "target"}
|
||||
invalid_fields = set(vendor_payload.keys()) - allowed_set_fields
|
||||
invalid_fields = set(abstract_payload.keys()) - allowed_set_fields
|
||||
if invalid_fields:
|
||||
logger.warning(
|
||||
f"Thermostat SET {device_id} contains invalid fields {invalid_fields}, "
|
||||
@@ -159,11 +165,14 @@ async def handle_abstract_set(
|
||||
return
|
||||
|
||||
# Validate against ThermostatState (current/battery/window_open are optional)
|
||||
ThermostatState.model_validate(vendor_payload)
|
||||
ThermostatState.model_validate(abstract_payload)
|
||||
except ValidationError as e:
|
||||
logger.error(f"Validation failed for {device_type} SET {device_id}: {e}")
|
||||
return
|
||||
|
||||
# Transform abstract payload to vendor-specific format
|
||||
vendor_payload = transform_abstract_to_vendor(device_type, device_technology, abstract_payload)
|
||||
|
||||
vendor_message = json.dumps(vendor_payload)
|
||||
|
||||
logger.info(f"→ vendor SET {device_id}: {vendor_topic} ← {vendor_message}")
|
||||
@@ -175,6 +184,7 @@ async def handle_vendor_state(
|
||||
redis_client: aioredis.Redis,
|
||||
device_id: str,
|
||||
device_type: str,
|
||||
device_technology: str,
|
||||
payload: dict[str, Any],
|
||||
redis_channel: str = "ui:updates"
|
||||
) -> None:
|
||||
@@ -185,23 +195,27 @@ async def handle_vendor_state(
|
||||
redis_client: Redis client instance
|
||||
device_id: Device identifier
|
||||
device_type: Device type (e.g., 'light', 'thermostat')
|
||||
payload: State payload
|
||||
device_technology: Technology identifier (e.g., 'zigbee2mqtt')
|
||||
payload: State payload (vendor-specific format)
|
||||
redis_channel: Redis channel for UI updates
|
||||
"""
|
||||
# Transform vendor-specific payload to abstract format
|
||||
abstract_payload = transform_vendor_to_abstract(device_type, device_technology, payload)
|
||||
|
||||
# Validate state payload based on device type
|
||||
try:
|
||||
if device_type == "light":
|
||||
LightState.model_validate(payload)
|
||||
LightState.model_validate(abstract_payload)
|
||||
elif device_type == "thermostat":
|
||||
# Validate thermostat state: mode, target, current (required), battery, window_open
|
||||
ThermostatState.model_validate(payload)
|
||||
ThermostatState.model_validate(abstract_payload)
|
||||
except ValidationError as e:
|
||||
logger.error(f"Validation failed for {device_type} STATE {device_id}: {e}")
|
||||
return
|
||||
|
||||
# Publish to abstract state topic (retained)
|
||||
abstract_topic = f"home/{device_type}/{device_id}/state"
|
||||
abstract_message = json.dumps(payload)
|
||||
abstract_message = json.dumps(abstract_payload)
|
||||
|
||||
logger.info(f"← abstract STATE {device_id}: {abstract_topic} → {abstract_message}")
|
||||
await mqtt_client.publish(abstract_topic, abstract_message, qos=1, retain=True)
|
||||
@@ -210,7 +224,7 @@ async def handle_vendor_state(
|
||||
ui_update = {
|
||||
"type": "state",
|
||||
"device_id": device_id,
|
||||
"payload": payload,
|
||||
"payload": abstract_payload,
|
||||
"ts": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
redis_message = json.dumps(ui_update)
|
||||
@@ -227,8 +241,8 @@ async def mqtt_worker(config: dict[str, Any], redis_client: aioredis.Redis) -> N
|
||||
redis_client: Redis client for UI updates
|
||||
"""
|
||||
mqtt_config = config.get("mqtt", {})
|
||||
broker = mqtt_config.get("broker", "172.16.2.16")
|
||||
port = mqtt_config.get("port", 1883)
|
||||
broker = os.getenv("MQTT_BROKER") or mqtt_config.get("broker", "localhost")
|
||||
port = int(os.getenv("MQTT_PORT", mqtt_config.get("port", 1883)))
|
||||
client_id = mqtt_config.get("client_id", "home-automation-abstraction")
|
||||
# Append a short suffix (ENV override possible) so multiple processes don't collide
|
||||
client_suffix = os.environ.get("MQTT_CLIENT_ID_SUFFIX") or uuid.uuid4().hex[:6]
|
||||
@@ -297,8 +311,9 @@ async def mqtt_worker(config: dict[str, Any], redis_client: aioredis.Redis) -> N
|
||||
if device_id in devices:
|
||||
device = devices[device_id]
|
||||
vendor_topic = device["topics"]["set"]
|
||||
device_technology = device.get("technology", "unknown")
|
||||
await handle_abstract_set(
|
||||
client, device_id, device_type, vendor_topic, payload
|
||||
client, device_id, device_type, device_technology, vendor_topic, payload
|
||||
)
|
||||
|
||||
# Check if this is a vendor STATE message
|
||||
@@ -306,8 +321,10 @@ async def mqtt_worker(config: dict[str, Any], redis_client: aioredis.Redis) -> N
|
||||
# Find device by vendor state topic
|
||||
for device_id, device in devices.items():
|
||||
if topic == device["topics"]["state"]:
|
||||
device_technology = device.get("technology", "unknown")
|
||||
await handle_vendor_state(
|
||||
client, redis_client, device_id, device["type"], payload, redis_channel
|
||||
client, redis_client, device_id, device["type"],
|
||||
device_technology, payload, redis_channel
|
||||
)
|
||||
break
|
||||
|
||||
|
||||
237
apps/abstraction/transformation.py
Normal file
237
apps/abstraction/transformation.py
Normal file
@@ -0,0 +1,237 @@
|
||||
"""Payload transformation functions for vendor-specific device communication.
|
||||
|
||||
This module implements a registry-pattern for vendor-specific transformations:
|
||||
- Each (device_type, technology, direction) tuple maps to a specific handler function
|
||||
- Handlers transform payloads between abstract and vendor-specific formats
|
||||
- Unknown combinations fall back to pass-through (no transformation)
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Any, Callable
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# HANDLER FUNCTIONS: simulator technology
|
||||
# ============================================================================
|
||||
|
||||
def _transform_light_simulator_to_vendor(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Transform abstract light payload to simulator format.
|
||||
|
||||
Simulator uses same format as abstract protocol (no transformation needed).
|
||||
"""
|
||||
return payload
|
||||
|
||||
|
||||
def _transform_light_simulator_to_abstract(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Transform simulator light payload to abstract format.
|
||||
|
||||
Simulator uses same format as abstract protocol (no transformation needed).
|
||||
"""
|
||||
return payload
|
||||
|
||||
|
||||
def _transform_thermostat_simulator_to_vendor(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Transform abstract thermostat payload to simulator format.
|
||||
|
||||
Simulator uses same format as abstract protocol (no transformation needed).
|
||||
"""
|
||||
return payload
|
||||
|
||||
|
||||
def _transform_thermostat_simulator_to_abstract(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Transform simulator thermostat payload to abstract format.
|
||||
|
||||
Simulator uses same format as abstract protocol (no transformation needed).
|
||||
"""
|
||||
return payload
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# HANDLER FUNCTIONS: zigbee2mqtt technology
|
||||
# ============================================================================
|
||||
|
||||
def _transform_light_zigbee2mqtt_to_vendor(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Transform abstract light payload to zigbee2mqtt format.
|
||||
|
||||
Transformations:
|
||||
- power: 'on'/'off' -> state: 'ON'/'OFF'
|
||||
- brightness: 0-100 -> brightness: 0-254
|
||||
|
||||
Example:
|
||||
- Abstract: {'power': 'on', 'brightness': 100}
|
||||
- zigbee2mqtt: {'state': 'ON', 'brightness': 254}
|
||||
"""
|
||||
vendor_payload = payload.copy()
|
||||
|
||||
# Transform power -> state with uppercase values
|
||||
if "power" in vendor_payload:
|
||||
power_value = vendor_payload.pop("power")
|
||||
vendor_payload["state"] = power_value.upper() if isinstance(power_value, str) else power_value
|
||||
|
||||
# Transform brightness: 0-100 (%) -> 0-254 (zigbee2mqtt range)
|
||||
if "brightness" in vendor_payload:
|
||||
abstract_brightness = vendor_payload["brightness"]
|
||||
if isinstance(abstract_brightness, (int, float)):
|
||||
# Convert percentage (0-100) to zigbee2mqtt range (0-254)
|
||||
vendor_payload["brightness"] = round(abstract_brightness * 254 / 100)
|
||||
|
||||
return vendor_payload
|
||||
|
||||
|
||||
def _transform_light_zigbee2mqtt_to_abstract(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Transform zigbee2mqtt light payload to abstract format.
|
||||
|
||||
Transformations:
|
||||
- state: 'ON'/'OFF' -> power: 'on'/'off'
|
||||
- brightness: 0-254 -> brightness: 0-100
|
||||
|
||||
Example:
|
||||
- zigbee2mqtt: {'state': 'ON', 'brightness': 254}
|
||||
- Abstract: {'power': 'on', 'brightness': 100}
|
||||
"""
|
||||
abstract_payload = payload.copy()
|
||||
|
||||
# Transform state -> power with lowercase values
|
||||
if "state" in abstract_payload:
|
||||
state_value = abstract_payload.pop("state")
|
||||
abstract_payload["power"] = state_value.lower() if isinstance(state_value, str) else state_value
|
||||
|
||||
# Transform brightness: 0-254 (zigbee2mqtt range) -> 0-100 (%)
|
||||
if "brightness" in abstract_payload:
|
||||
vendor_brightness = abstract_payload["brightness"]
|
||||
if isinstance(vendor_brightness, (int, float)):
|
||||
# Convert zigbee2mqtt range (0-254) to percentage (0-100)
|
||||
abstract_payload["brightness"] = round(vendor_brightness * 100 / 254)
|
||||
|
||||
return abstract_payload
|
||||
|
||||
|
||||
def _transform_thermostat_zigbee2mqtt_to_vendor(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Transform abstract thermostat payload to zigbee2mqtt format.
|
||||
|
||||
zigbee2mqtt uses same format as abstract protocol (no transformation needed).
|
||||
"""
|
||||
return payload
|
||||
|
||||
|
||||
def _transform_thermostat_zigbee2mqtt_to_abstract(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Transform zigbee2mqtt thermostat payload to abstract format.
|
||||
|
||||
zigbee2mqtt uses same format as abstract protocol (no transformation needed).
|
||||
"""
|
||||
return payload
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# REGISTRY: Maps (device_type, technology, direction) -> handler function
|
||||
# ============================================================================
|
||||
|
||||
TransformHandler = Callable[[dict[str, Any]], dict[str, Any]]
|
||||
|
||||
TRANSFORM_HANDLERS: dict[tuple[str, str, str], TransformHandler] = {
|
||||
# Light transformations
|
||||
("light", "simulator", "to_vendor"): _transform_light_simulator_to_vendor,
|
||||
("light", "simulator", "to_abstract"): _transform_light_simulator_to_abstract,
|
||||
("light", "zigbee2mqtt", "to_vendor"): _transform_light_zigbee2mqtt_to_vendor,
|
||||
("light", "zigbee2mqtt", "to_abstract"): _transform_light_zigbee2mqtt_to_abstract,
|
||||
|
||||
# Thermostat transformations
|
||||
("thermostat", "simulator", "to_vendor"): _transform_thermostat_simulator_to_vendor,
|
||||
("thermostat", "simulator", "to_abstract"): _transform_thermostat_simulator_to_abstract,
|
||||
("thermostat", "zigbee2mqtt", "to_vendor"): _transform_thermostat_zigbee2mqtt_to_vendor,
|
||||
("thermostat", "zigbee2mqtt", "to_abstract"): _transform_thermostat_zigbee2mqtt_to_abstract,
|
||||
}
|
||||
|
||||
|
||||
def _get_transform_handler(
|
||||
device_type: str,
|
||||
device_technology: str,
|
||||
direction: str
|
||||
) -> TransformHandler:
|
||||
"""Get transformation handler for given device type, technology and direction.
|
||||
|
||||
Args:
|
||||
device_type: Type of device (e.g., "light", "thermostat")
|
||||
device_technology: Technology/vendor (e.g., "simulator", "zigbee2mqtt")
|
||||
direction: Transformation direction ("to_vendor" or "to_abstract")
|
||||
|
||||
Returns:
|
||||
Handler function for transformation, or pass-through if not found
|
||||
"""
|
||||
key = (device_type, device_technology, direction)
|
||||
handler = TRANSFORM_HANDLERS.get(key)
|
||||
|
||||
if handler is None:
|
||||
logger.warning(
|
||||
f"No transformation handler for {key}, using pass-through. "
|
||||
f"Available: {list(TRANSFORM_HANDLERS.keys())}"
|
||||
)
|
||||
return lambda payload: payload # Pass-through fallback
|
||||
|
||||
return handler
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# PUBLIC API: Main transformation functions
|
||||
# ============================================================================
|
||||
|
||||
def transform_abstract_to_vendor(
|
||||
device_type: str,
|
||||
device_technology: str,
|
||||
abstract_payload: dict[str, Any]
|
||||
) -> dict[str, Any]:
|
||||
"""Transform abstract payload to vendor-specific format.
|
||||
|
||||
Args:
|
||||
device_type: Type of device (e.g., "light", "thermostat")
|
||||
device_technology: Technology/vendor (e.g., "simulator", "zigbee2mqtt")
|
||||
abstract_payload: Payload in abstract home protocol format
|
||||
|
||||
Returns:
|
||||
Payload in vendor-specific format
|
||||
"""
|
||||
logger.debug(
|
||||
f"transform_abstract_to_vendor IN: type={device_type}, tech={device_technology}, "
|
||||
f"payload={abstract_payload}"
|
||||
)
|
||||
|
||||
handler = _get_transform_handler(device_type, device_technology, "to_vendor")
|
||||
vendor_payload = handler(abstract_payload)
|
||||
|
||||
logger.debug(
|
||||
f"transform_abstract_to_vendor OUT: type={device_type}, tech={device_technology}, "
|
||||
f"payload={vendor_payload}"
|
||||
)
|
||||
return vendor_payload
|
||||
|
||||
|
||||
def transform_vendor_to_abstract(
|
||||
device_type: str,
|
||||
device_technology: str,
|
||||
vendor_payload: dict[str, Any]
|
||||
) -> dict[str, Any]:
|
||||
"""Transform vendor-specific payload to abstract format.
|
||||
|
||||
Args:
|
||||
device_type: Type of device (e.g., "light", "thermostat")
|
||||
device_technology: Technology/vendor (e.g., "simulator", "zigbee2mqtt")
|
||||
vendor_payload: Payload in vendor-specific format
|
||||
|
||||
Returns:
|
||||
Payload in abstract home protocol format
|
||||
"""
|
||||
logger.debug(
|
||||
f"transform_vendor_to_abstract IN: type={device_type}, tech={device_technology}, "
|
||||
f"payload={vendor_payload}"
|
||||
)
|
||||
|
||||
handler = _get_transform_handler(device_type, device_technology, "to_abstract")
|
||||
abstract_payload = handler(vendor_payload)
|
||||
|
||||
logger.debug(
|
||||
f"transform_vendor_to_abstract OUT: type={device_type}, tech={device_technology}, "
|
||||
f"payload={abstract_payload}"
|
||||
)
|
||||
return abstract_payload
|
||||
@@ -42,7 +42,7 @@ docker build -t api:dev -f apps/api/Dockerfile .
|
||||
```bash
|
||||
docker run --rm -p 8001:8001 \
|
||||
-v $(pwd)/config:/app/config:ro \
|
||||
-e MQTT_BROKER=172.16.2.16 \
|
||||
-e MQTT_BROKER=172.23.1.102 \
|
||||
-e MQTT_PORT=1883 \
|
||||
-e REDIS_HOST=172.23.1.116 \
|
||||
-e REDIS_PORT=6379 \
|
||||
@@ -51,6 +51,23 @@ docker run --rm -p 8001:8001 \
|
||||
api:dev
|
||||
```
|
||||
|
||||
**Mit Docker Network (empfohlen für Linux):**
|
||||
```bash
|
||||
docker network create home-automation
|
||||
docker run --rm -p 8001:8001 \
|
||||
--network home-automation \
|
||||
--name api \
|
||||
-v $(pwd)/config:/app/config:ro \
|
||||
-e MQTT_BROKER=172.16.2.16 \
|
||||
-e REDIS_HOST=172.23.1.116 \
|
||||
-e REDIS_DB=8 \
|
||||
api:dev
|
||||
```
|
||||
|
||||
**Hinweise:**
|
||||
- **Linux**: Port wird auf `0.0.0.0:8001` gebunden (von überall erreichbar)
|
||||
- **macOS/finch**: Port wird auf `127.0.0.1:8001` gebunden (nur localhost)
|
||||
|
||||
#### Environment Variables
|
||||
|
||||
| Variable | Default | Description |
|
||||
|
||||
212
apps/api/main.py
212
apps/api/main.py
@@ -19,6 +19,13 @@ from packages.home_capabilities import LIGHT_VERSION, THERMOSTAT_VERSION, LightS
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# In-memory cache for last known device states
|
||||
# Will be populated from Redis pub/sub messages
|
||||
device_states: dict[str, dict[str, Any]] = {}
|
||||
|
||||
# Background task reference
|
||||
background_task: asyncio.Task | None = None
|
||||
|
||||
app = FastAPI(
|
||||
title="Home Automation API",
|
||||
description="API for home automation system",
|
||||
@@ -30,6 +37,7 @@ app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=[
|
||||
"http://localhost:8002",
|
||||
"http://172.19.1.11:8002",
|
||||
"http://127.0.0.1:8002",
|
||||
],
|
||||
allow_credentials=True,
|
||||
@@ -48,6 +56,77 @@ async def health() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
async def redis_state_listener():
|
||||
"""Background task that listens to Redis pub/sub and updates state cache."""
|
||||
redis_client = None
|
||||
pubsub = None
|
||||
|
||||
try:
|
||||
redis_url, redis_channel = get_redis_settings()
|
||||
logger.info(f"Starting Redis state listener for channel {redis_channel}")
|
||||
|
||||
redis_client = await aioredis.from_url(redis_url, decode_responses=True)
|
||||
pubsub = redis_client.pubsub()
|
||||
await pubsub.subscribe(redis_channel)
|
||||
|
||||
logger.info("Redis state listener connected")
|
||||
|
||||
while True:
|
||||
try:
|
||||
message = await asyncio.wait_for(
|
||||
pubsub.get_message(ignore_subscribe_messages=True),
|
||||
timeout=1.0
|
||||
)
|
||||
|
||||
if message and message["type"] == "message":
|
||||
data = message["data"]
|
||||
try:
|
||||
state_data = json.loads(data)
|
||||
if state_data.get("type") == "state" and state_data.get("device_id"):
|
||||
device_id = state_data["device_id"]
|
||||
payload = state_data.get("payload", {})
|
||||
device_states[device_id] = payload
|
||||
logger.debug(f"Updated state cache for {device_id}: {payload}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to parse state data: {e}")
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
pass # No message, continue
|
||||
|
||||
except asyncio.CancelledError:
|
||||
logger.info("Redis state listener cancelled")
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Redis state listener error: {e}")
|
||||
finally:
|
||||
if pubsub:
|
||||
await pubsub.unsubscribe(redis_channel)
|
||||
await pubsub.close()
|
||||
if redis_client:
|
||||
await redis_client.close()
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup_event():
|
||||
"""Start background tasks on application startup."""
|
||||
global background_task
|
||||
background_task = asyncio.create_task(redis_state_listener())
|
||||
logger.info("Started background Redis state listener")
|
||||
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def shutdown_event():
|
||||
"""Clean up background tasks on application shutdown."""
|
||||
global background_task
|
||||
if background_task:
|
||||
background_task.cancel()
|
||||
try:
|
||||
await background_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
logger.info("Stopped background Redis state listener")
|
||||
|
||||
|
||||
@app.get("/spec")
|
||||
async def spec() -> dict[str, dict[str, str]]:
|
||||
"""Capability specification endpoint.
|
||||
@@ -181,6 +260,16 @@ async def get_devices() -> list[DeviceInfo]:
|
||||
]
|
||||
|
||||
|
||||
@app.get("/devices/states")
|
||||
async def get_device_states() -> dict[str, dict[str, Any]]:
|
||||
"""Get current states of all devices from in-memory cache.
|
||||
|
||||
Returns:
|
||||
dict: Dictionary mapping device_id to state payload
|
||||
"""
|
||||
return device_states
|
||||
|
||||
|
||||
@app.get("/layout")
|
||||
async def get_layout() -> dict[str, Any]:
|
||||
"""Get UI layout configuration.
|
||||
@@ -286,7 +375,13 @@ async def set_device(device_id: str, request: SetDeviceRequest) -> dict[str, str
|
||||
|
||||
|
||||
async def event_generator(request: Request) -> AsyncGenerator[str, None]:
|
||||
"""Generate SSE events from Redis Pub/Sub.
|
||||
"""Generate SSE events from Redis Pub/Sub with Safari compatibility.
|
||||
|
||||
Safari-compatible features:
|
||||
- Immediate retry hint on connection
|
||||
- Regular heartbeats every 15s (comment-only, no data)
|
||||
- Proper flushing after each yield
|
||||
- Graceful disconnect handling
|
||||
|
||||
Args:
|
||||
request: FastAPI request object for disconnect detection
|
||||
@@ -294,70 +389,125 @@ async def event_generator(request: Request) -> AsyncGenerator[str, None]:
|
||||
Yields:
|
||||
str: SSE formatted event strings
|
||||
"""
|
||||
redis_url, redis_channel = get_redis_settings()
|
||||
redis_client = await aioredis.from_url(redis_url, decode_responses=True)
|
||||
pubsub = redis_client.pubsub()
|
||||
redis_client = None
|
||||
pubsub = None
|
||||
|
||||
try:
|
||||
await pubsub.subscribe(redis_channel)
|
||||
# Send retry hint immediately for EventSource reconnect behavior
|
||||
yield "retry: 2500\n\n"
|
||||
|
||||
# Create heartbeat task
|
||||
# Try to connect to Redis
|
||||
redis_url, redis_channel = get_redis_settings()
|
||||
try:
|
||||
redis_client = await aioredis.from_url(redis_url, decode_responses=True)
|
||||
pubsub = redis_client.pubsub()
|
||||
await pubsub.subscribe(redis_channel)
|
||||
logger.info(f"SSE client connected, subscribed to {redis_channel}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Redis unavailable, running in heartbeat-only mode: {e}")
|
||||
redis_client = None
|
||||
pubsub = None
|
||||
|
||||
# Heartbeat tracking
|
||||
last_heartbeat = asyncio.get_event_loop().time()
|
||||
heartbeat_interval = 15 # Safari-friendly: shorter interval
|
||||
|
||||
while True:
|
||||
# Check if client disconnected
|
||||
if await request.is_disconnected():
|
||||
logger.info("SSE client disconnected")
|
||||
break
|
||||
|
||||
# Get message with timeout for heartbeat
|
||||
try:
|
||||
message = await asyncio.wait_for(
|
||||
pubsub.get_message(ignore_subscribe_messages=True),
|
||||
timeout=1.0
|
||||
)
|
||||
|
||||
if message and message["type"] == "message":
|
||||
# Send data event
|
||||
data = message["data"]
|
||||
yield f"event: message\ndata: {data}\n\n"
|
||||
last_heartbeat = asyncio.get_event_loop().time()
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
# Try to get message from Redis (if available)
|
||||
if pubsub:
|
||||
try:
|
||||
message = await asyncio.wait_for(
|
||||
pubsub.get_message(ignore_subscribe_messages=True),
|
||||
timeout=0.1
|
||||
)
|
||||
|
||||
if message and message["type"] == "message":
|
||||
data = message["data"]
|
||||
logger.debug(f"Sending SSE message: {data[:100]}...")
|
||||
|
||||
# Update in-memory cache with latest state
|
||||
try:
|
||||
state_data = json.loads(data)
|
||||
if state_data.get("type") == "state" and state_data.get("device_id"):
|
||||
device_states[state_data["device_id"]] = state_data.get("payload", {})
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to parse state data for cache: {e}")
|
||||
|
||||
yield f"event: message\ndata: {data}\n\n"
|
||||
last_heartbeat = asyncio.get_event_loop().time()
|
||||
continue # Skip sleep, check for more messages immediately
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
pass # No message, continue to heartbeat check
|
||||
except Exception as e:
|
||||
logger.error(f"Redis error: {e}")
|
||||
# Continue with heartbeats even if Redis fails
|
||||
|
||||
# Send heartbeat every 25 seconds
|
||||
# Sleep briefly to avoid busy loop
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
# Send heartbeat if interval elapsed
|
||||
current_time = asyncio.get_event_loop().time()
|
||||
if current_time - last_heartbeat >= 25:
|
||||
yield "event: ping\ndata: heartbeat\n\n"
|
||||
if current_time - last_heartbeat >= heartbeat_interval:
|
||||
# Comment-style ping (Safari-compatible, no event type)
|
||||
yield ": ping\n\n"
|
||||
last_heartbeat = current_time
|
||||
|
||||
except asyncio.CancelledError:
|
||||
logger.info("SSE connection cancelled by client")
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"SSE error: {e}")
|
||||
raise
|
||||
finally:
|
||||
await pubsub.unsubscribe(redis_channel)
|
||||
await pubsub.close()
|
||||
await redis_client.close()
|
||||
# Cleanup Redis connection
|
||||
if pubsub:
|
||||
try:
|
||||
await pubsub.unsubscribe(redis_channel)
|
||||
await pubsub.aclose()
|
||||
except Exception as e:
|
||||
logger.error(f"Error closing pubsub: {e}")
|
||||
|
||||
if redis_client:
|
||||
try:
|
||||
await redis_client.aclose()
|
||||
except Exception as e:
|
||||
logger.error(f"Error closing redis: {e}")
|
||||
|
||||
logger.info("SSE connection closed")
|
||||
|
||||
|
||||
@app.get("/realtime")
|
||||
async def realtime_events(request: Request) -> StreamingResponse:
|
||||
"""Server-Sent Events endpoint for real-time updates.
|
||||
|
||||
Safari-compatible SSE implementation:
|
||||
- Immediate retry hint (2.5s reconnect delay)
|
||||
- Heartbeat every 15s using comment syntax ": ping"
|
||||
- Proper Cache-Control headers
|
||||
- No buffering (nginx compatibility)
|
||||
- Graceful Redis fallback (heartbeat-only mode)
|
||||
|
||||
Args:
|
||||
request: FastAPI request object
|
||||
|
||||
Returns:
|
||||
StreamingResponse: SSE stream of Redis messages
|
||||
StreamingResponse: SSE stream with Redis messages and heartbeats
|
||||
"""
|
||||
return StreamingResponse(
|
||||
event_generator(request),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no", # Disable nginx buffering
|
||||
}
|
||||
)
|
||||
|
||||
return {"message": f"Command sent to {device_id}"}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
|
||||
@@ -53,12 +53,20 @@ docker build -t simulator:dev -f apps/simulator/Dockerfile .
|
||||
|
||||
```bash
|
||||
docker run --rm -p 8010:8010 \
|
||||
-e MQTT_BROKER=172.16.2.16 \
|
||||
-e MQTT_BROKER=172.23.1.102 \
|
||||
-e MQTT_PORT=1883 \
|
||||
-e SIM_PORT=8010 \
|
||||
simulator:dev
|
||||
```
|
||||
|
||||
**Mit Docker Network (optional):**
|
||||
```bash
|
||||
docker run --rm -p 8010:8010 \
|
||||
--name simulator \
|
||||
-e MQTT_BROKER=172.23.1.102 \
|
||||
simulator:dev
|
||||
```
|
||||
|
||||
#### Environment Variables
|
||||
|
||||
| Variable | Default | Description |
|
||||
|
||||
@@ -37,14 +37,32 @@ docker build -t ui:dev -f apps/ui/Dockerfile .
|
||||
|
||||
#### Run Container
|
||||
|
||||
**Linux Server (empfohlen):**
|
||||
```bash
|
||||
# Mit Docker Network für Container-to-Container Kommunikation
|
||||
docker run --rm -p 8002:8002 \
|
||||
-e UI_PORT=8002 \
|
||||
-e API_BASE=http://localhost:8001 \
|
||||
-e API_BASE=http://172.19.1.11:8001 \
|
||||
-e BASE_PATH=/ \
|
||||
ui:dev
|
||||
```
|
||||
|
||||
**macOS mit finch/nerdctl:**
|
||||
```bash
|
||||
docker run --rm -p 8002:8002 \
|
||||
--add-host=host.docker.internal:host-gateway \
|
||||
-e UI_PORT=8002 \
|
||||
-e API_BASE=http://host.docker.internal:8001 \
|
||||
-e BASE_PATH=/ \
|
||||
ui:dev
|
||||
```
|
||||
|
||||
**Hinweise:**
|
||||
- **Linux**: Verwende Docker Network und Service-Namen (`http://api:8001`)
|
||||
- **macOS/finch**: Verwende `host.docker.internal` mit `--add-host` flag
|
||||
- Die UI macht Server-Side API-Aufrufe beim Rendern der Seite
|
||||
- Browser-seitige Realtime-Updates (SSE) gehen direkt vom Browser zur API
|
||||
|
||||
#### Environment Variables
|
||||
|
||||
| Variable | Default | Description |
|
||||
|
||||
@@ -29,6 +29,16 @@
|
||||
padding: 2rem;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
|
||||
margin-bottom: 2rem;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 1rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.header-content {
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
@@ -36,6 +46,65 @@
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.header-buttons {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.refresh-btn,
|
||||
.collapse-all-btn {
|
||||
padding: 0.75rem;
|
||||
background: #667eea;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
min-height: 44px;
|
||||
min-width: 44px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.refresh-btn:hover,
|
||||
.collapse-all-btn:hover {
|
||||
background: #5568d3;
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.refresh-btn:active,
|
||||
.collapse-all-btn:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.refresh-icon {
|
||||
font-size: 1.5rem;
|
||||
line-height: 1;
|
||||
transition: transform 0.3s;
|
||||
}
|
||||
|
||||
.refresh-icon.spinning {
|
||||
animation: spin 0.6s linear;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.collapse-all-icon {
|
||||
font-size: 1.25rem;
|
||||
transition: transform 0.3s;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.collapse-all-icon.collapsed {
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
|
||||
.status {
|
||||
display: inline-block;
|
||||
padding: 0.25rem 0.75rem;
|
||||
@@ -55,14 +124,69 @@
|
||||
}
|
||||
|
||||
.room {
|
||||
margin-bottom: 2rem;
|
||||
background: white;
|
||||
border-radius: 20px;
|
||||
margin-bottom: 1rem;
|
||||
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
|
||||
overflow: hidden;
|
||||
transition: box-shadow 0.2s;
|
||||
}
|
||||
|
||||
.room:hover {
|
||||
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.room-header {
|
||||
padding: 1.5rem 2rem;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
background: white;
|
||||
transition: background-color 0.2s;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.room-header:hover {
|
||||
background: #f8f9fa;
|
||||
}
|
||||
|
||||
.room-header:active {
|
||||
background: #e9ecef;
|
||||
}
|
||||
|
||||
.room-title {
|
||||
color: white;
|
||||
color: #333;
|
||||
font-size: 1.5rem;
|
||||
margin-bottom: 1rem;
|
||||
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
|
||||
font-weight: 700;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.room-toggle {
|
||||
font-size: 1.5rem;
|
||||
color: #667eea;
|
||||
transition: transform 0.3s;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.room-toggle.collapsed {
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
|
||||
.room-content {
|
||||
padding: 0 2rem 2rem 2rem;
|
||||
max-height: 5000px;
|
||||
overflow: hidden;
|
||||
transition: max-height 0.3s ease-out, padding 0.3s ease-out;
|
||||
}
|
||||
|
||||
.room-content.collapsed {
|
||||
max-height: 0;
|
||||
padding-top: 0;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.devices {
|
||||
@@ -379,16 +503,30 @@
|
||||
<body>
|
||||
<div class="container">
|
||||
<header>
|
||||
<h1>🏠 Home Automation</h1>
|
||||
<p>Realtime Status: <span class="status disconnected" id="connection-status">Verbinde...</span></p>
|
||||
<div class="header-content">
|
||||
<h1>🏠 Home Automation</h1>
|
||||
<p>Realtime Status: <span class="status disconnected" id="connection-status">Verbinde...</span></p>
|
||||
</div>
|
||||
<div class="header-buttons">
|
||||
<button class="refresh-btn" onclick="refreshPage()" title="Seite aktualisieren">
|
||||
<span class="refresh-icon" id="refresh-icon">↻</span>
|
||||
</button>
|
||||
<button class="collapse-all-btn" onclick="toggleAllRooms()" title="Alle Räume ein-/ausklappen">
|
||||
<span class="collapse-all-icon" id="collapse-all-icon">▼</span>
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{% if rooms %}
|
||||
{% for room in rooms %}
|
||||
<section class="room">
|
||||
<h2 class="room-title">{{ room.name }}</h2>
|
||||
<div class="room-header" onclick="toggleRoom('room-{{ loop.index }}')">
|
||||
<h2 class="room-title">{{ room.name }}</h2>
|
||||
<span class="room-toggle" id="toggle-room-{{ loop.index }}">▼</span>
|
||||
</div>
|
||||
|
||||
<div class="devices">
|
||||
<div class="room-content" id="room-{{ loop.index }}">
|
||||
<div class="devices">
|
||||
{% for device in room.devices %}
|
||||
<div class="device-card" data-device-id="{{ device.device_id }}">
|
||||
<div class="device-header">
|
||||
@@ -500,6 +638,7 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{% endfor %}
|
||||
@@ -519,14 +658,106 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Toggle room visibility
|
||||
function toggleRoom(roomId) {
|
||||
const content = document.getElementById(roomId);
|
||||
const toggle = document.getElementById(`toggle-${roomId}`);
|
||||
|
||||
if (content && toggle) {
|
||||
content.classList.toggle('collapsed');
|
||||
toggle.classList.toggle('collapsed');
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh page with animation
|
||||
function refreshPage() {
|
||||
const icon = document.getElementById('refresh-icon');
|
||||
icon.classList.add('spinning');
|
||||
|
||||
// Reload page after brief animation
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 300);
|
||||
}
|
||||
|
||||
// Toggle all rooms
|
||||
function toggleAllRooms() {
|
||||
const allContents = document.querySelectorAll('.room-content');
|
||||
const allToggles = document.querySelectorAll('.room-toggle');
|
||||
const buttonIcon = document.getElementById('collapse-all-icon');
|
||||
|
||||
// Check if any room is expanded
|
||||
const anyExpanded = Array.from(allContents).some(content => !content.classList.contains('collapsed'));
|
||||
|
||||
if (anyExpanded) {
|
||||
// Collapse all
|
||||
allContents.forEach(content => content.classList.add('collapsed'));
|
||||
allToggles.forEach(toggle => toggle.classList.add('collapsed'));
|
||||
buttonIcon.classList.add('collapsed');
|
||||
} else {
|
||||
// Expand all
|
||||
allContents.forEach(content => content.classList.remove('collapsed'));
|
||||
allToggles.forEach(toggle => toggle.classList.remove('collapsed'));
|
||||
buttonIcon.classList.remove('collapsed');
|
||||
}
|
||||
}
|
||||
|
||||
// Set room icons based on room name
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const roomTitles = document.querySelectorAll('.room-title');
|
||||
roomTitles.forEach(title => {
|
||||
const roomName = title.textContent.trim().toLowerCase();
|
||||
let icon = '🏠'; // Default
|
||||
|
||||
if (roomName.includes('wohn') || roomName.includes('living')) icon = '🛋️';
|
||||
else if (roomName.includes('schlaf') || roomName.includes('bed')) icon = '🛏️';
|
||||
else if (roomName.includes('küch') || roomName.includes('kitchen')) icon = '🍳';
|
||||
else if (roomName.includes('bad') || roomName.includes('bath')) icon = '🛁';
|
||||
else if (roomName.includes('büro') || roomName.includes('office')) icon = '💼';
|
||||
else if (roomName.includes('kind') || roomName.includes('child')) icon = '🧸';
|
||||
else if (roomName.includes('garten') || roomName.includes('garden')) icon = '🌿';
|
||||
else if (roomName.includes('garage')) icon = '🚗';
|
||||
else if (roomName.includes('keller') || roomName.includes('basement')) icon = '📦';
|
||||
else if (roomName.includes('dach') || roomName.includes('attic')) icon = '🏚️';
|
||||
|
||||
// Replace the ::before pseudo-element with actual emoji
|
||||
const originalText = title.textContent.trim();
|
||||
title.innerHTML = `${icon} ${originalText}`;
|
||||
});
|
||||
});
|
||||
|
||||
// Clean up SSE connection before page unload
|
||||
window.addEventListener('beforeunload', () => {
|
||||
if (eventSource) {
|
||||
console.log('Closing SSE connection before unload');
|
||||
eventSource.close();
|
||||
eventSource = null;
|
||||
}
|
||||
});
|
||||
|
||||
// API_BASE injected from backend (supports Docker/K8s environments)
|
||||
window.API_BASE = '{{ api_base }}';
|
||||
window.RUNTIME_CONFIG = window.RUNTIME_CONFIG || {};
|
||||
|
||||
// Helper function to construct API URLs
|
||||
function api(url) {
|
||||
return `${window.API_BASE}${url}`;
|
||||
}
|
||||
|
||||
// iOS/Safari Polyfill laden (nur wenn nötig)
|
||||
(function() {
|
||||
var isIOS = /iP(hone|od|ad)/.test(navigator.platform) ||
|
||||
(navigator.userAgent.includes("Mac") && "ontouchend" in document);
|
||||
if (isIOS && typeof window.EventSourcePolyfill === "undefined") {
|
||||
var s = document.createElement("script");
|
||||
s.src = "https://cdn.jsdelivr.net/npm/event-source-polyfill@1.0.31/src/eventsource.min.js";
|
||||
s.onerror = function() {
|
||||
console.warn("EventSource polyfill konnte nicht geladen werden");
|
||||
};
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
})();
|
||||
|
||||
let eventSource = null;
|
||||
let currentState = {};
|
||||
let thermostatTargets = {};
|
||||
@@ -634,7 +865,6 @@
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
thermostatTargets[deviceId] = newTarget;
|
||||
console.log(`Sent target ${newTarget} to ${deviceId}`);
|
||||
addEvent({
|
||||
action: 'target_adjusted',
|
||||
@@ -699,6 +929,8 @@
|
||||
toggleButton.textContent = 'Einschalten';
|
||||
toggleButton.className = 'toggle-button off';
|
||||
}
|
||||
// Force reflow for iOS Safari
|
||||
void toggleButton.offsetHeight;
|
||||
}
|
||||
|
||||
// Update brightness display and slider
|
||||
@@ -782,77 +1014,179 @@
|
||||
}
|
||||
}
|
||||
|
||||
// Connect to SSE
|
||||
function connectSSE() {
|
||||
eventSource = new EventSource(api('/realtime'));
|
||||
// Safari/iOS-kompatibler SSE Client mit Auto-Reconnect
|
||||
let reconnectDelay = 2500;
|
||||
let reconnectTimer = null;
|
||||
|
||||
// Global handleSSE function für SSE-Nachrichten
|
||||
window.handleSSE = function(data) {
|
||||
console.log('SSE message:', data);
|
||||
|
||||
eventSource.onopen = () => {
|
||||
console.log('SSE connected');
|
||||
document.getElementById('connection-status').textContent = 'Verbunden';
|
||||
document.getElementById('connection-status').className = 'status connected';
|
||||
};
|
||||
addEvent(data);
|
||||
|
||||
eventSource.addEventListener('message', (e) => {
|
||||
const data = JSON.parse(e.data);
|
||||
console.log('SSE message:', data);
|
||||
|
||||
addEvent(data);
|
||||
|
||||
// Update device state
|
||||
if (data.type === 'state' && data.device_id && data.payload) {
|
||||
const card = document.querySelector(`[data-device-id="${data.device_id}"]`);
|
||||
|
||||
// Check if it's a light
|
||||
if (data.payload.power !== undefined) {
|
||||
updateDeviceUI(
|
||||
data.device_id,
|
||||
data.payload.power,
|
||||
data.payload.brightness
|
||||
);
|
||||
}
|
||||
|
||||
// Check if it's a thermostat
|
||||
if (data.payload.mode !== undefined || data.payload.target !== undefined || data.payload.current !== undefined) {
|
||||
updateThermostatUI(
|
||||
data.device_id,
|
||||
data.payload.current,
|
||||
data.payload.target,
|
||||
data.payload.mode
|
||||
);
|
||||
}
|
||||
// Update device state
|
||||
if (data.type === 'state' && data.device_id && data.payload) {
|
||||
const card = document.querySelector(`[data-device-id="${data.device_id}"]`);
|
||||
if (!card) {
|
||||
console.warn(`No card found for device ${data.device_id}`);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
eventSource.addEventListener('ping', (e) => {
|
||||
console.log('Heartbeat received');
|
||||
});
|
||||
|
||||
eventSource.onerror = (error) => {
|
||||
console.error('SSE error:', error);
|
||||
document.getElementById('connection-status').textContent = 'Getrennt';
|
||||
document.getElementById('connection-status').className = 'status disconnected';
|
||||
eventSource.close();
|
||||
|
||||
// Reconnect after 5 seconds
|
||||
setTimeout(connectSSE, 5000);
|
||||
};
|
||||
}
|
||||
// Check if it's a light
|
||||
if (data.payload.power !== undefined) {
|
||||
currentState[data.device_id] = data.payload.power;
|
||||
updateDeviceUI(
|
||||
data.device_id,
|
||||
data.payload.power,
|
||||
data.payload.brightness
|
||||
);
|
||||
}
|
||||
|
||||
// Check if it's a thermostat
|
||||
if (data.payload.mode !== undefined || data.payload.target !== undefined || data.payload.current !== undefined) {
|
||||
if (data.payload.mode !== undefined) {
|
||||
thermostatModes[data.device_id] = data.payload.mode;
|
||||
}
|
||||
if (data.payload.target !== undefined) {
|
||||
thermostatTargets[data.device_id] = data.payload.target;
|
||||
}
|
||||
updateThermostatUI(
|
||||
data.device_id,
|
||||
data.payload.current,
|
||||
data.payload.target,
|
||||
data.payload.mode
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Initialize
|
||||
connectSSE();
|
||||
|
||||
// Optional: Load initial state from API
|
||||
async function loadDevices() {
|
||||
try {
|
||||
const response = await fetch(api('/devices'));
|
||||
const devices = await response.json();
|
||||
console.log('Loaded devices:', devices);
|
||||
} catch (error) {
|
||||
console.error('Failed to load devices:', error);
|
||||
function cleanupSSE() {
|
||||
if (eventSource) {
|
||||
try {
|
||||
eventSource.close();
|
||||
} catch(e) {
|
||||
console.error('Error closing EventSource:', e);
|
||||
}
|
||||
eventSource = null;
|
||||
}
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
loadDevices();
|
||||
function scheduleReconnect() {
|
||||
if (reconnectTimer) return;
|
||||
console.log(`Reconnecting in ${reconnectDelay}ms...`);
|
||||
reconnectTimer = setTimeout(() => {
|
||||
reconnectTimer = null;
|
||||
connectSSE();
|
||||
// Backoff bis 10s
|
||||
reconnectDelay = Math.min(reconnectDelay * 2, 10000);
|
||||
}, reconnectDelay);
|
||||
}
|
||||
|
||||
function connectSSE() {
|
||||
cleanupSSE();
|
||||
|
||||
const REALTIME_URL = (window.RUNTIME_CONFIG && window.RUNTIME_CONFIG.REALTIME_URL)
|
||||
? window.RUNTIME_CONFIG.REALTIME_URL
|
||||
: api('/realtime');
|
||||
|
||||
console.log('Connecting to SSE:', REALTIME_URL);
|
||||
|
||||
try {
|
||||
// Verwende Polyfill wenn verfügbar, sonst native EventSource
|
||||
const EventSourceImpl = window.EventSourcePolyfill || window.EventSource;
|
||||
eventSource = new EventSourceImpl(REALTIME_URL, {
|
||||
withCredentials: false
|
||||
});
|
||||
|
||||
eventSource.onopen = function() {
|
||||
console.log('SSE connected successfully');
|
||||
reconnectDelay = 2500; // Reset backoff
|
||||
document.getElementById('connection-status').textContent = 'Verbunden';
|
||||
document.getElementById('connection-status').className = 'status connected';
|
||||
};
|
||||
|
||||
eventSource.onmessage = function(evt) {
|
||||
if (!evt || !evt.data) return;
|
||||
|
||||
// Heartbeats beginnen mit ":" -> ignorieren
|
||||
if (typeof evt.data === "string" && evt.data.charAt(0) === ":") {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = JSON.parse(evt.data);
|
||||
if (window.handleSSE) {
|
||||
window.handleSSE(data);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error parsing SSE message:', e);
|
||||
}
|
||||
};
|
||||
|
||||
eventSource.onerror = function(error) {
|
||||
console.error('SSE error:', error, 'readyState:', eventSource?.readyState);
|
||||
document.getElementById('connection-status').textContent = 'Getrennt';
|
||||
document.getElementById('connection-status').className = 'status disconnected';
|
||||
|
||||
// Safari/iOS verliert Netz beim App-Switch: ruhig reconnecten
|
||||
scheduleReconnect();
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error('Failed to create EventSource:', error);
|
||||
document.getElementById('connection-status').textContent = 'Getrennt';
|
||||
document.getElementById('connection-status').className = 'status disconnected';
|
||||
scheduleReconnect();
|
||||
}
|
||||
}
|
||||
|
||||
// Visibility-Change Handler für iOS App-Switch
|
||||
document.addEventListener('visibilitychange', function() {
|
||||
if (!document.hidden) {
|
||||
// Wenn wieder sichtbar & keine offene Verbindung: verbinden
|
||||
if (!eventSource || eventSource.readyState !== 1) {
|
||||
console.log('Page visible again, reconnecting SSE...');
|
||||
connectSSE();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Start SSE connection
|
||||
connectSSE();
|
||||
|
||||
// Load initial device states
|
||||
async function loadDevices() {
|
||||
try {
|
||||
const response = await fetch(api('/devices/states'));
|
||||
const states = await response.json();
|
||||
console.log('Loaded initial device states:', states);
|
||||
|
||||
// Update UI with initial states
|
||||
for (const [deviceId, state] of Object.entries(states)) {
|
||||
if (state.power !== undefined) {
|
||||
// It's a light
|
||||
currentState[deviceId] = state.power;
|
||||
updateDeviceUI(deviceId, state.power, state.brightness);
|
||||
} else if (state.mode !== undefined || state.target !== undefined) {
|
||||
// It's a thermostat
|
||||
if (state.mode) thermostatModes[deviceId] = state.mode;
|
||||
if (state.target) thermostatTargets[deviceId] = state.target;
|
||||
updateThermostatUI(deviceId, state.current, state.target, state.mode);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load initial device states:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Load initial states before connecting SSE
|
||||
loadDevices().then(() => {
|
||||
console.log('Initial states loaded, now connecting SSE...');
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -16,7 +16,7 @@ devices:
|
||||
- device_id: test_lampe_1
|
||||
type: light
|
||||
cap_version: "light@1.2.0"
|
||||
technology: zigbee2mqtt
|
||||
technology: simulator
|
||||
features:
|
||||
power: true
|
||||
brightness: true
|
||||
@@ -26,7 +26,7 @@ devices:
|
||||
- device_id: test_lampe_2
|
||||
type: light
|
||||
cap_version: "light@1.2.0"
|
||||
technology: zigbee2mqtt
|
||||
technology: simulator
|
||||
features:
|
||||
power: true
|
||||
topics:
|
||||
@@ -35,7 +35,7 @@ devices:
|
||||
- device_id: test_lampe_3
|
||||
type: light
|
||||
cap_version: "light@1.2.0"
|
||||
technology: zigbee2mqtt
|
||||
technology: simulator
|
||||
features:
|
||||
power: true
|
||||
brightness: true
|
||||
@@ -45,12 +45,22 @@ devices:
|
||||
- device_id: test_thermo_1
|
||||
type: thermostat
|
||||
cap_version: "thermostat@2.0.0"
|
||||
technology: zigbee2mqtt
|
||||
technology: simulator
|
||||
features:
|
||||
mode: true
|
||||
mode: false
|
||||
target: true
|
||||
current: true
|
||||
battery: true
|
||||
topics:
|
||||
set: "vendor/test_thermo_1/set"
|
||||
state: "vendor/test_thermo_1/state"
|
||||
- device_id: experiment_light_1
|
||||
type: light
|
||||
cap_version: "light@1.2.0"
|
||||
technology: zigbee2mqtt
|
||||
features:
|
||||
power: true
|
||||
brightness: true
|
||||
topics:
|
||||
set: "zigbee2mqtt/0xf0d1b80000195038/set"
|
||||
state: "zigbee2mqtt/0xf0d1b80000195038"
|
||||
|
||||
@@ -24,6 +24,12 @@ rooms:
|
||||
icon: "🛏️"
|
||||
rank: 10
|
||||
|
||||
- name: Lab
|
||||
devices:
|
||||
- device_id: experiment_light_1
|
||||
title: Experimentierlampe
|
||||
icon: "💡"
|
||||
rank: 10
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user