55 lines
1.5 KiB
Python
55 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))
|