- Introduced MQTTPublishRequest and MQTTPublishResponse models for handling MQTT message publishing. - Implemented a new POST route for publishing MQTT messages, including error handling and logging. - Enhanced the StandaloneAutoRecorder with improved logging during manual recording start. - Updated the frontend to include an MQTT Debug Panel for better monitoring and debugging capabilities.
103 lines
3.9 KiB
Python
103 lines
3.9 KiB
Python
"""
|
|
MQTT-related API routes.
|
|
"""
|
|
|
|
import logging
|
|
from typing import Dict
|
|
from fastapi import FastAPI, HTTPException, Query
|
|
from ...core.state_manager import StateManager
|
|
from ...mqtt.client import MQTTClient
|
|
from ..models import MQTTStatusResponse, MQTTEventsHistoryResponse, MQTTEventResponse, MQTTPublishRequest, MQTTPublishResponse
|
|
|
|
|
|
def register_mqtt_routes(
|
|
app: FastAPI,
|
|
mqtt_client: MQTTClient,
|
|
state_manager: StateManager,
|
|
logger: logging.Logger
|
|
):
|
|
"""Register MQTT-related routes"""
|
|
|
|
@app.get("/mqtt/status", response_model=MQTTStatusResponse)
|
|
async def get_mqtt_status():
|
|
"""Get MQTT client status and statistics"""
|
|
try:
|
|
status = mqtt_client.get_status()
|
|
return MQTTStatusResponse(
|
|
connected=status["connected"],
|
|
broker_host=status["broker_host"],
|
|
broker_port=status["broker_port"],
|
|
subscribed_topics=status["subscribed_topics"],
|
|
last_message_time=status["last_message_time"],
|
|
message_count=status["message_count"],
|
|
error_count=status["error_count"],
|
|
uptime_seconds=status["uptime_seconds"]
|
|
)
|
|
except Exception as e:
|
|
logger.error(f"Error getting MQTT status: {e}")
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
@app.get("/mqtt/events", response_model=MQTTEventsHistoryResponse)
|
|
async def get_mqtt_events(
|
|
limit: int = Query(default=5, ge=1, le=50, description="Number of recent events to retrieve")
|
|
):
|
|
"""Get recent MQTT events history"""
|
|
try:
|
|
events = state_manager.get_recent_mqtt_events(limit)
|
|
total_events = state_manager.get_mqtt_event_count()
|
|
|
|
# Convert events to response format
|
|
event_responses = [
|
|
MQTTEventResponse(
|
|
machine_name=event.machine_name,
|
|
topic=event.topic,
|
|
payload=event.payload,
|
|
normalized_state=event.normalized_state,
|
|
timestamp=event.timestamp.isoformat(),
|
|
message_number=event.message_number
|
|
)
|
|
for event in events
|
|
]
|
|
|
|
last_updated = events[0].timestamp.isoformat() if events else None
|
|
|
|
return MQTTEventsHistoryResponse(
|
|
events=event_responses,
|
|
total_events=total_events,
|
|
last_updated=last_updated
|
|
)
|
|
except Exception as e:
|
|
logger.error(f"Error getting MQTT events: {e}")
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
@app.post("/mqtt/publish", response_model=MQTTPublishResponse)
|
|
async def publish_mqtt_message(request: MQTTPublishRequest):
|
|
"""Publish an MQTT message (for testing/debugging)"""
|
|
try:
|
|
if not mqtt_client.is_connected():
|
|
raise HTTPException(status_code=503, detail="MQTT client is not connected")
|
|
|
|
success = mqtt_client.publish_message(
|
|
topic=request.topic,
|
|
payload=request.payload,
|
|
qos=request.qos,
|
|
retain=request.retain
|
|
)
|
|
|
|
if success:
|
|
logger.info(f"Published MQTT message: {request.topic} -> {request.payload}")
|
|
return MQTTPublishResponse(
|
|
success=True,
|
|
message=f"Message published successfully to {request.topic}",
|
|
topic=request.topic,
|
|
payload=request.payload
|
|
)
|
|
else:
|
|
raise HTTPException(status_code=500, detail="Failed to publish MQTT message")
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
logger.error(f"Error publishing MQTT message: {e}")
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|