daily-briefing/server/routers/mqtt.py
Sam 89ed0c6d0a feat: add MQTT integration for real-time entity updates
- aiomqtt async client with auto-reconnect and topic store
- MQTT router: GET /api/mqtt, GET /api/mqtt/topic/{path}, POST /api/mqtt/publish
- MQTT entities included in /api/all + WebSocket broadcast
- MqttCard frontend component with category filters, entity list
- Configurable via ENV: MQTT_HOST, MQTT_PORT, MQTT_USERNAME,
  MQTT_PASSWORD, MQTT_TOPICS (comma-separated or JSON array)
- Gracefully disabled when MQTT_HOST is not set

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 10:13:50 +01:00

54 lines
1.5 KiB
Python

"""MQTT router — exposes MQTT entity state and publish endpoint."""
from __future__ import annotations
import logging
from typing import Any, Dict, Optional
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from server.services.mqtt_service import mqtt_service
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/mqtt", tags=["mqtt"])
class PublishRequest(BaseModel):
topic: str
payload: Any
retain: bool = False
@router.get("")
async def get_mqtt_state() -> Dict[str, Any]:
"""Return all stored MQTT entities."""
return {
"connected": mqtt_service.connected,
"entities": mqtt_service.get_entities(),
"topic_count": len(mqtt_service.store),
}
@router.get("/topic/{topic:path}")
async def get_mqtt_topic(topic: str) -> Dict[str, Any]:
"""Return value for a specific MQTT topic."""
msg = mqtt_service.store.get(topic)
if not msg:
raise HTTPException(status_code=404, detail=f"Topic '{topic}' not found")
return {
"topic": msg.topic,
"value": msg.payload,
"timestamp": msg.timestamp,
}
@router.post("/publish")
async def publish_mqtt(req: PublishRequest) -> Dict[str, str]:
"""Publish a message to the MQTT broker."""
try:
await mqtt_service.publish(req.topic, req.payload, retain=req.retain)
return {"status": "ok", "topic": req.topic}
except RuntimeError as exc:
raise HTTPException(status_code=503, detail=str(exc))