Phase 5 Complete by Claude Code
This commit is contained in:
@@ -5,7 +5,8 @@
|
||||
"Bash(npm install:*)",
|
||||
"Bash(npm run build:*)",
|
||||
"Bash(python -c:*)",
|
||||
"Bash(npx vite build:*)"
|
||||
"Bash(npx vite build:*)",
|
||||
"Bash(wc:*)"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -19,3 +19,5 @@ dist/
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
MAIN-APP-REFERENCE/
|
||||
@@ -20,6 +20,10 @@ class Settings(BaseSettings):
|
||||
mqtt_admin_password: str = ""
|
||||
mosquitto_password_file: str = "/etc/mosquitto/passwd"
|
||||
|
||||
# SQLite (MQTT data storage)
|
||||
sqlite_db_path: str = "./mqtt_data.db"
|
||||
mqtt_data_retention_days: int = 90
|
||||
|
||||
# App
|
||||
backend_cors_origins: str = '["http://localhost:5173"]'
|
||||
debug: bool = True
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from config import settings
|
||||
@@ -7,6 +8,9 @@ from melodies.router import router as melodies_router
|
||||
from devices.router import router as devices_router
|
||||
from settings.router import router as settings_router
|
||||
from users.router import router as users_router
|
||||
from mqtt.router import router as mqtt_router
|
||||
from mqtt.client import mqtt_manager
|
||||
from mqtt import database as mqtt_db
|
||||
|
||||
app = FastAPI(
|
||||
title="BellSystems Admin Panel",
|
||||
@@ -28,13 +32,27 @@ app.include_router(melodies_router)
|
||||
app.include_router(devices_router)
|
||||
app.include_router(settings_router)
|
||||
app.include_router(users_router)
|
||||
app.include_router(mqtt_router)
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
init_firebase()
|
||||
await mqtt_db.init_db()
|
||||
mqtt_manager.start(asyncio.get_event_loop())
|
||||
asyncio.create_task(mqtt_db.purge_loop())
|
||||
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def shutdown():
|
||||
mqtt_manager.stop()
|
||||
await mqtt_db.close_db()
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health_check():
|
||||
return {"status": "ok", "firebase": firebase_initialized}
|
||||
return {
|
||||
"status": "ok",
|
||||
"firebase": firebase_initialized,
|
||||
"mqtt": mqtt_manager.connected,
|
||||
}
|
||||
|
||||
@@ -1 +1,139 @@
|
||||
# TODO: MQTT client wrapper (paho-mqtt)
|
||||
import json
|
||||
import logging
|
||||
import asyncio
|
||||
from typing import Set
|
||||
import paho.mqtt.client as paho_mqtt
|
||||
from config import settings
|
||||
|
||||
logger = logging.getLogger("mqtt.client")
|
||||
|
||||
|
||||
class MqttManager:
|
||||
"""Singleton MQTT client manager."""
|
||||
|
||||
def __init__(self):
|
||||
self._client: paho_mqtt.Client | None = None
|
||||
self._connected = False
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
self._ws_subscribers: Set = set()
|
||||
|
||||
@property
|
||||
def connected(self) -> bool:
|
||||
return self._connected
|
||||
|
||||
def start(self, loop: asyncio.AbstractEventLoop):
|
||||
self._loop = loop
|
||||
|
||||
self._client = paho_mqtt.Client(
|
||||
callback_api_version=paho_mqtt.CallbackAPIVersion.VERSION2,
|
||||
client_id="bellsystems-admin-panel",
|
||||
clean_session=True,
|
||||
)
|
||||
|
||||
if settings.mqtt_admin_username and settings.mqtt_admin_password:
|
||||
self._client.username_pw_set(
|
||||
settings.mqtt_admin_username,
|
||||
settings.mqtt_admin_password,
|
||||
)
|
||||
|
||||
self._client.on_connect = self._on_connect
|
||||
self._client.on_disconnect = self._on_disconnect
|
||||
self._client.on_message = self._on_message
|
||||
|
||||
try:
|
||||
self._client.connect_async(
|
||||
settings.mqtt_broker_host,
|
||||
settings.mqtt_broker_port,
|
||||
)
|
||||
self._client.loop_start()
|
||||
logger.info(f"MQTT client connecting to {settings.mqtt_broker_host}:{settings.mqtt_broker_port}")
|
||||
except Exception as e:
|
||||
logger.warning(f"MQTT client failed to start: {e}")
|
||||
|
||||
def stop(self):
|
||||
if self._client:
|
||||
self._client.loop_stop()
|
||||
self._client.disconnect()
|
||||
self._connected = False
|
||||
logger.info("MQTT client disconnected")
|
||||
|
||||
def _on_connect(self, client, userdata, flags, reason_code, properties):
|
||||
if reason_code == 0:
|
||||
self._connected = True
|
||||
logger.info("MQTT connected, subscribing to topics")
|
||||
client.subscribe([
|
||||
("vesper/+/data", 1),
|
||||
("vesper/+/status/heartbeat", 1),
|
||||
("vesper/+/logs", 1),
|
||||
])
|
||||
else:
|
||||
logger.error(f"MQTT connection failed: {reason_code}")
|
||||
|
||||
def _on_disconnect(self, client, userdata, flags, reason_code, properties):
|
||||
self._connected = False
|
||||
if reason_code != 0:
|
||||
logger.warning(f"MQTT disconnected unexpectedly: {reason_code}")
|
||||
|
||||
def _on_message(self, client, userdata, msg):
|
||||
"""Called from paho thread — bridge to asyncio."""
|
||||
try:
|
||||
topic = msg.topic
|
||||
payload = json.loads(msg.payload.decode("utf-8"))
|
||||
parts = topic.split("/")
|
||||
if len(parts) < 3 or parts[0] != "vesper":
|
||||
return
|
||||
|
||||
serial = parts[1]
|
||||
topic_type = "/".join(parts[2:])
|
||||
|
||||
if self._loop and self._loop.is_running():
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self._process_message(serial, topic_type, payload, topic),
|
||||
self._loop,
|
||||
)
|
||||
except json.JSONDecodeError:
|
||||
logger.warning(f"Invalid JSON on topic {msg.topic}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing MQTT message: {e}")
|
||||
|
||||
async def _process_message(self, serial: str, topic_type: str,
|
||||
payload: dict, raw_topic: str):
|
||||
from mqtt.logger import handle_message
|
||||
await handle_message(serial, topic_type, payload)
|
||||
|
||||
ws_data = {
|
||||
"type": topic_type,
|
||||
"device_serial": serial,
|
||||
"payload": payload,
|
||||
"topic": raw_topic,
|
||||
}
|
||||
await self._broadcast_ws(ws_data)
|
||||
|
||||
async def _broadcast_ws(self, data: dict):
|
||||
msg = json.dumps(data)
|
||||
dead = set()
|
||||
for ws in self._ws_subscribers:
|
||||
try:
|
||||
await ws.send_text(msg)
|
||||
except Exception:
|
||||
dead.add(ws)
|
||||
self._ws_subscribers -= dead
|
||||
|
||||
def add_ws_subscriber(self, websocket):
|
||||
self._ws_subscribers.add(websocket)
|
||||
|
||||
def remove_ws_subscriber(self, websocket):
|
||||
self._ws_subscribers.discard(websocket)
|
||||
|
||||
def publish_command(self, device_serial: str, cmd: str,
|
||||
contents: dict) -> bool:
|
||||
if not self._client or not self._connected:
|
||||
return False
|
||||
|
||||
topic = f"vesper/{device_serial}/control"
|
||||
payload = json.dumps({"cmd": cmd, "contents": contents})
|
||||
result = self._client.publish(topic, payload, qos=1)
|
||||
return result.rc == paho_mqtt.MQTT_ERR_SUCCESS
|
||||
|
||||
|
||||
mqtt_manager = MqttManager()
|
||||
|
||||
222
backend/mqtt/database.py
Normal file
222
backend/mqtt/database.py
Normal file
@@ -0,0 +1,222 @@
|
||||
import aiosqlite
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from config import settings
|
||||
|
||||
logger = logging.getLogger("mqtt.database")
|
||||
|
||||
_db: aiosqlite.Connection | None = None
|
||||
|
||||
SCHEMA_STATEMENTS = [
|
||||
"""CREATE TABLE IF NOT EXISTS device_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
device_serial TEXT NOT NULL,
|
||||
level TEXT NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
device_timestamp INTEGER,
|
||||
received_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS heartbeats (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
device_serial TEXT NOT NULL,
|
||||
device_id TEXT,
|
||||
firmware_version TEXT,
|
||||
ip_address TEXT,
|
||||
gateway TEXT,
|
||||
uptime_ms INTEGER,
|
||||
uptime_display TEXT,
|
||||
received_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS commands (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
device_serial TEXT NOT NULL,
|
||||
command_name TEXT NOT NULL,
|
||||
command_payload TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
response_payload TEXT,
|
||||
sent_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
responded_at TEXT
|
||||
)""",
|
||||
"CREATE INDEX IF NOT EXISTS idx_logs_serial_time ON device_logs(device_serial, received_at)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_logs_level ON device_logs(level)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_heartbeats_serial_time ON heartbeats(device_serial, received_at)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_commands_serial_time ON commands(device_serial, sent_at)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_commands_status ON commands(status)",
|
||||
]
|
||||
|
||||
|
||||
async def init_db():
|
||||
global _db
|
||||
_db = await aiosqlite.connect(settings.sqlite_db_path)
|
||||
_db.row_factory = aiosqlite.Row
|
||||
for stmt in SCHEMA_STATEMENTS:
|
||||
await _db.execute(stmt)
|
||||
await _db.commit()
|
||||
logger.info(f"SQLite database initialized at {settings.sqlite_db_path}")
|
||||
|
||||
|
||||
async def close_db():
|
||||
global _db
|
||||
if _db:
|
||||
await _db.close()
|
||||
_db = None
|
||||
|
||||
|
||||
async def get_db() -> aiosqlite.Connection:
|
||||
if _db is None:
|
||||
await init_db()
|
||||
return _db
|
||||
|
||||
|
||||
# --- Insert Operations ---
|
||||
|
||||
async def insert_log(device_serial: str, level: str, message: str,
|
||||
device_timestamp: int | None = None):
|
||||
db = await get_db()
|
||||
cursor = await db.execute(
|
||||
"INSERT INTO device_logs (device_serial, level, message, device_timestamp) VALUES (?, ?, ?, ?)",
|
||||
(device_serial, level, message, device_timestamp)
|
||||
)
|
||||
await db.commit()
|
||||
return cursor.lastrowid
|
||||
|
||||
|
||||
async def insert_heartbeat(device_serial: str, device_id: str,
|
||||
firmware_version: str, ip_address: str,
|
||||
gateway: str, uptime_ms: int, uptime_display: str):
|
||||
db = await get_db()
|
||||
cursor = await db.execute(
|
||||
"""INSERT INTO heartbeats
|
||||
(device_serial, device_id, firmware_version, ip_address, gateway, uptime_ms, uptime_display)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)""",
|
||||
(device_serial, device_id, firmware_version, ip_address, gateway, uptime_ms, uptime_display)
|
||||
)
|
||||
await db.commit()
|
||||
return cursor.lastrowid
|
||||
|
||||
|
||||
async def insert_command(device_serial: str, command_name: str,
|
||||
command_payload: dict) -> int:
|
||||
db = await get_db()
|
||||
cursor = await db.execute(
|
||||
"INSERT INTO commands (device_serial, command_name, command_payload) VALUES (?, ?, ?)",
|
||||
(device_serial, command_name, json.dumps(command_payload))
|
||||
)
|
||||
await db.commit()
|
||||
return cursor.lastrowid
|
||||
|
||||
|
||||
async def update_command_response(command_id: int, status: str,
|
||||
response_payload: dict | None = None):
|
||||
db = await get_db()
|
||||
await db.execute(
|
||||
"""UPDATE commands SET status = ?, response_payload = ?,
|
||||
responded_at = datetime('now') WHERE id = ?""",
|
||||
(status, json.dumps(response_payload) if response_payload else None, command_id)
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
# --- Query Operations ---
|
||||
|
||||
async def get_logs(device_serial: str, level: str | None = None,
|
||||
search: str | None = None,
|
||||
limit: int = 100, offset: int = 0) -> tuple[list, int]:
|
||||
db = await get_db()
|
||||
where_clauses = ["device_serial = ?"]
|
||||
params: list = [device_serial]
|
||||
|
||||
if level:
|
||||
where_clauses.append("level = ?")
|
||||
params.append(level)
|
||||
if search:
|
||||
where_clauses.append("message LIKE ?")
|
||||
params.append(f"%{search}%")
|
||||
|
||||
where = " AND ".join(where_clauses)
|
||||
|
||||
count_row = await db.execute_fetchall(
|
||||
f"SELECT COUNT(*) as cnt FROM device_logs WHERE {where}", params
|
||||
)
|
||||
total = count_row[0][0]
|
||||
|
||||
rows = await db.execute_fetchall(
|
||||
f"SELECT * FROM device_logs WHERE {where} ORDER BY received_at DESC LIMIT ? OFFSET ?",
|
||||
params + [limit, offset]
|
||||
)
|
||||
return [dict(r) for r in rows], total
|
||||
|
||||
|
||||
async def get_heartbeats(device_serial: str, limit: int = 100,
|
||||
offset: int = 0) -> tuple[list, int]:
|
||||
db = await get_db()
|
||||
count_row = await db.execute_fetchall(
|
||||
"SELECT COUNT(*) FROM heartbeats WHERE device_serial = ?", (device_serial,)
|
||||
)
|
||||
total = count_row[0][0]
|
||||
rows = await db.execute_fetchall(
|
||||
"SELECT * FROM heartbeats WHERE device_serial = ? ORDER BY received_at DESC LIMIT ? OFFSET ?",
|
||||
(device_serial, limit, offset)
|
||||
)
|
||||
return [dict(r) for r in rows], total
|
||||
|
||||
|
||||
async def get_commands(device_serial: str, limit: int = 100,
|
||||
offset: int = 0) -> tuple[list, int]:
|
||||
db = await get_db()
|
||||
count_row = await db.execute_fetchall(
|
||||
"SELECT COUNT(*) FROM commands WHERE device_serial = ?", (device_serial,)
|
||||
)
|
||||
total = count_row[0][0]
|
||||
rows = await db.execute_fetchall(
|
||||
"SELECT * FROM commands WHERE device_serial = ? ORDER BY sent_at DESC LIMIT ? OFFSET ?",
|
||||
(device_serial, limit, offset)
|
||||
)
|
||||
return [dict(r) for r in rows], total
|
||||
|
||||
|
||||
async def get_latest_heartbeats() -> list:
|
||||
db = await get_db()
|
||||
rows = await db.execute_fetchall("""
|
||||
SELECT h.* FROM heartbeats h
|
||||
INNER JOIN (
|
||||
SELECT device_serial, MAX(received_at) as max_time
|
||||
FROM heartbeats GROUP BY device_serial
|
||||
) latest ON h.device_serial = latest.device_serial
|
||||
AND h.received_at = latest.max_time
|
||||
""")
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
async def get_pending_command(device_serial: str) -> dict | None:
|
||||
db = await get_db()
|
||||
rows = await db.execute_fetchall(
|
||||
"""SELECT * FROM commands WHERE device_serial = ? AND status = 'pending'
|
||||
ORDER BY sent_at DESC LIMIT 1""",
|
||||
(device_serial,)
|
||||
)
|
||||
return dict(rows[0]) if rows else None
|
||||
|
||||
|
||||
# --- Cleanup ---
|
||||
|
||||
async def purge_old_data(retention_days: int | None = None):
|
||||
days = retention_days or settings.mqtt_data_retention_days
|
||||
cutoff = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()
|
||||
db = await get_db()
|
||||
await db.execute("DELETE FROM device_logs WHERE received_at < ?", (cutoff,))
|
||||
await db.execute("DELETE FROM heartbeats WHERE received_at < ?", (cutoff,))
|
||||
await db.execute("DELETE FROM commands WHERE sent_at < ?", (cutoff,))
|
||||
await db.commit()
|
||||
logger.info(f"Purged MQTT data older than {days} days")
|
||||
|
||||
|
||||
async def purge_loop():
|
||||
while True:
|
||||
await asyncio.sleep(86400)
|
||||
try:
|
||||
await purge_old_data()
|
||||
except Exception as e:
|
||||
logger.error(f"Purge failed: {e}")
|
||||
@@ -1 +1,70 @@
|
||||
# TODO: Log storage and retrieval
|
||||
import logging
|
||||
from mqtt import database as db
|
||||
|
||||
logger = logging.getLogger("mqtt.logger")
|
||||
|
||||
LEVEL_MAP = {
|
||||
"🟢 INFO": "INFO",
|
||||
"🟡 WARN": "WARN",
|
||||
"🔴 EROR": "ERROR",
|
||||
"INFO": "INFO",
|
||||
"WARN": "WARN",
|
||||
"ERROR": "ERROR",
|
||||
"EROR": "ERROR",
|
||||
}
|
||||
|
||||
|
||||
async def handle_message(serial: str, topic_type: str, payload: dict):
|
||||
try:
|
||||
if topic_type == "status/heartbeat":
|
||||
await _handle_heartbeat(serial, payload)
|
||||
elif topic_type == "logs":
|
||||
await _handle_log(serial, payload)
|
||||
elif topic_type == "data":
|
||||
await _handle_data_response(serial, payload)
|
||||
else:
|
||||
logger.debug(f"Unhandled topic type: {topic_type} for {serial}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error handling {topic_type} for {serial}: {e}")
|
||||
|
||||
|
||||
async def _handle_heartbeat(serial: str, payload: dict):
|
||||
inner = payload.get("payload", {})
|
||||
await db.insert_heartbeat(
|
||||
device_serial=serial,
|
||||
device_id=inner.get("device_id", ""),
|
||||
firmware_version=inner.get("firmware_version", ""),
|
||||
ip_address=inner.get("ip_address", ""),
|
||||
gateway=inner.get("gateway", ""),
|
||||
uptime_ms=inner.get("uptime_ms", 0),
|
||||
uptime_display=inner.get("timestamp", ""),
|
||||
)
|
||||
|
||||
|
||||
async def _handle_log(serial: str, payload: dict):
|
||||
raw_level = payload.get("level", "INFO")
|
||||
level = LEVEL_MAP.get(raw_level, "INFO")
|
||||
message = payload.get("message", "")
|
||||
device_timestamp = payload.get("timestamp")
|
||||
|
||||
await db.insert_log(
|
||||
device_serial=serial,
|
||||
level=level,
|
||||
message=message,
|
||||
device_timestamp=device_timestamp,
|
||||
)
|
||||
|
||||
|
||||
async def _handle_data_response(serial: str, payload: dict):
|
||||
status = payload.get("status", "")
|
||||
|
||||
pending = await db.get_pending_command(serial)
|
||||
if pending:
|
||||
cmd_status = "success" if status == "SUCCESS" else "error"
|
||||
await db.update_command_response(
|
||||
command_id=pending["id"],
|
||||
status=cmd_status,
|
||||
response_payload=payload,
|
||||
)
|
||||
else:
|
||||
logger.debug(f"Received data response for {serial} with no pending command")
|
||||
|
||||
86
backend/mqtt/models.py
Normal file
86
backend/mqtt/models.py
Normal file
@@ -0,0 +1,86 @@
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional, List, Any, Dict
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class LogLevel(str, Enum):
|
||||
INFO = "INFO"
|
||||
WARN = "WARN"
|
||||
ERROR = "ERROR"
|
||||
|
||||
|
||||
class CommandStatus(str, Enum):
|
||||
PENDING = "pending"
|
||||
SUCCESS = "success"
|
||||
ERROR = "error"
|
||||
TIMEOUT = "timeout"
|
||||
|
||||
|
||||
class MqttCommandRequest(BaseModel):
|
||||
cmd: str = Field(..., description="Command name: ping, playback, file_manager, relay_setup, clock_setup, system_info, system")
|
||||
contents: Dict[str, Any] = Field(default_factory=dict, description="Command payload contents")
|
||||
|
||||
|
||||
class DeviceLogEntry(BaseModel):
|
||||
id: int
|
||||
device_serial: str
|
||||
level: str
|
||||
message: str
|
||||
device_timestamp: Optional[int] = None
|
||||
received_at: str
|
||||
|
||||
|
||||
class HeartbeatEntry(BaseModel):
|
||||
id: int
|
||||
device_serial: str
|
||||
device_id: Optional[str] = None
|
||||
firmware_version: Optional[str] = None
|
||||
ip_address: Optional[str] = None
|
||||
gateway: Optional[str] = None
|
||||
uptime_ms: Optional[int] = None
|
||||
uptime_display: Optional[str] = None
|
||||
received_at: str
|
||||
|
||||
|
||||
class CommandEntry(BaseModel):
|
||||
id: int
|
||||
device_serial: str
|
||||
command_name: str
|
||||
command_payload: Optional[str] = None
|
||||
status: str
|
||||
response_payload: Optional[str] = None
|
||||
sent_at: str
|
||||
responded_at: Optional[str] = None
|
||||
|
||||
|
||||
class DeviceMqttStatus(BaseModel):
|
||||
device_serial: str
|
||||
online: bool
|
||||
last_heartbeat: Optional[HeartbeatEntry] = None
|
||||
seconds_since_heartbeat: Optional[int] = None
|
||||
|
||||
|
||||
class MqttStatusResponse(BaseModel):
|
||||
devices: List[DeviceMqttStatus]
|
||||
broker_connected: bool = False
|
||||
|
||||
|
||||
class LogListResponse(BaseModel):
|
||||
logs: List[DeviceLogEntry]
|
||||
total: int
|
||||
|
||||
|
||||
class HeartbeatListResponse(BaseModel):
|
||||
heartbeats: List[HeartbeatEntry]
|
||||
total: int
|
||||
|
||||
|
||||
class CommandListResponse(BaseModel):
|
||||
commands: List[CommandEntry]
|
||||
total: int
|
||||
|
||||
|
||||
class CommandSendResponse(BaseModel):
|
||||
success: bool
|
||||
command_id: int
|
||||
message: str
|
||||
@@ -1 +1,151 @@
|
||||
# TODO: Command endpoints + WebSocket for live data
|
||||
from fastapi import APIRouter, Depends, Query, WebSocket, WebSocketDisconnect
|
||||
from typing import Optional
|
||||
from auth.models import TokenPayload
|
||||
from auth.dependencies import require_device_access, require_viewer
|
||||
from mqtt.models import (
|
||||
MqttCommandRequest, CommandSendResponse, MqttStatusResponse,
|
||||
DeviceMqttStatus, LogListResponse, HeartbeatListResponse,
|
||||
CommandListResponse, HeartbeatEntry,
|
||||
)
|
||||
from mqtt.client import mqtt_manager
|
||||
from mqtt import database as db
|
||||
from datetime import datetime, timezone
|
||||
|
||||
router = APIRouter(prefix="/api/mqtt", tags=["mqtt"])
|
||||
|
||||
|
||||
@router.get("/status", response_model=MqttStatusResponse)
|
||||
async def get_all_device_status(
|
||||
_user: TokenPayload = Depends(require_viewer),
|
||||
):
|
||||
heartbeats = await db.get_latest_heartbeats()
|
||||
now = datetime.now(timezone.utc)
|
||||
devices = []
|
||||
for hb in heartbeats:
|
||||
received_str = hb["received_at"]
|
||||
try:
|
||||
received = datetime.fromisoformat(received_str)
|
||||
if received.tzinfo is None:
|
||||
received = received.replace(tzinfo=timezone.utc)
|
||||
seconds_ago = int((now - received).total_seconds())
|
||||
except (ValueError, TypeError):
|
||||
seconds_ago = 9999
|
||||
|
||||
devices.append(DeviceMqttStatus(
|
||||
device_serial=hb["device_serial"],
|
||||
online=seconds_ago < 90,
|
||||
last_heartbeat=HeartbeatEntry(**hb),
|
||||
seconds_since_heartbeat=seconds_ago,
|
||||
))
|
||||
return MqttStatusResponse(
|
||||
devices=devices,
|
||||
broker_connected=mqtt_manager.connected,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/command/{device_serial}", response_model=CommandSendResponse)
|
||||
async def send_command(
|
||||
device_serial: str,
|
||||
body: MqttCommandRequest,
|
||||
_user: TokenPayload = Depends(require_device_access),
|
||||
):
|
||||
command_id = await db.insert_command(
|
||||
device_serial=device_serial,
|
||||
command_name=body.cmd,
|
||||
command_payload={"cmd": body.cmd, "contents": body.contents},
|
||||
)
|
||||
|
||||
success = mqtt_manager.publish_command(
|
||||
device_serial=device_serial,
|
||||
cmd=body.cmd,
|
||||
contents=body.contents,
|
||||
)
|
||||
|
||||
if not success:
|
||||
await db.update_command_response(
|
||||
command_id, "error",
|
||||
{"error": "MQTT broker not connected"},
|
||||
)
|
||||
return CommandSendResponse(
|
||||
success=False, command_id=command_id,
|
||||
message="MQTT broker not connected",
|
||||
)
|
||||
|
||||
return CommandSendResponse(
|
||||
success=True, command_id=command_id,
|
||||
message=f"Command '{body.cmd}' sent to {device_serial}",
|
||||
)
|
||||
|
||||
|
||||
@router.get("/logs/{device_serial}", response_model=LogListResponse)
|
||||
async def get_device_logs(
|
||||
device_serial: str,
|
||||
level: Optional[str] = Query(None, description="Filter: INFO, WARN, ERROR"),
|
||||
search: Optional[str] = Query(None),
|
||||
limit: int = Query(100, ge=1, le=1000),
|
||||
offset: int = Query(0, ge=0),
|
||||
_user: TokenPayload = Depends(require_viewer),
|
||||
):
|
||||
logs, total = await db.get_logs(
|
||||
device_serial, level=level, search=search,
|
||||
limit=limit, offset=offset,
|
||||
)
|
||||
return LogListResponse(logs=logs, total=total)
|
||||
|
||||
|
||||
@router.get("/heartbeats/{device_serial}", response_model=HeartbeatListResponse)
|
||||
async def get_device_heartbeats(
|
||||
device_serial: str,
|
||||
limit: int = Query(100, ge=1, le=1000),
|
||||
offset: int = Query(0, ge=0),
|
||||
_user: TokenPayload = Depends(require_viewer),
|
||||
):
|
||||
heartbeats, total = await db.get_heartbeats(
|
||||
device_serial, limit=limit, offset=offset,
|
||||
)
|
||||
return HeartbeatListResponse(heartbeats=heartbeats, total=total)
|
||||
|
||||
|
||||
@router.get("/commands/{device_serial}", response_model=CommandListResponse)
|
||||
async def get_device_commands(
|
||||
device_serial: str,
|
||||
limit: int = Query(100, ge=1, le=1000),
|
||||
offset: int = Query(0, ge=0),
|
||||
_user: TokenPayload = Depends(require_viewer),
|
||||
):
|
||||
commands, total = await db.get_commands(
|
||||
device_serial, limit=limit, offset=offset,
|
||||
)
|
||||
return CommandListResponse(commands=commands, total=total)
|
||||
|
||||
|
||||
@router.websocket("/ws")
|
||||
async def mqtt_websocket(websocket: WebSocket):
|
||||
"""Live MQTT data stream. Auth via query param: ?token=JWT"""
|
||||
token = websocket.query_params.get("token")
|
||||
if not token:
|
||||
await websocket.close(code=4001, reason="Missing token")
|
||||
return
|
||||
|
||||
try:
|
||||
from auth.utils import decode_access_token
|
||||
payload = decode_access_token(token)
|
||||
role = payload.get("role", "")
|
||||
allowed = {"superadmin", "device_manager", "viewer"}
|
||||
if role not in allowed:
|
||||
await websocket.close(code=4003, reason="Insufficient permissions")
|
||||
return
|
||||
except Exception:
|
||||
await websocket.close(code=4001, reason="Invalid token")
|
||||
return
|
||||
|
||||
await websocket.accept()
|
||||
mqtt_manager.add_ws_subscriber(websocket)
|
||||
|
||||
try:
|
||||
while True:
|
||||
await websocket.receive_text()
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
finally:
|
||||
mqtt_manager.remove_ws_subscriber(websocket)
|
||||
|
||||
@@ -7,4 +7,5 @@ paho-mqtt==2.1.0
|
||||
python-jose[cryptography]==3.3.0
|
||||
passlib[bcrypt]==1.7.4
|
||||
python-multipart==0.0.20
|
||||
bcrypt==4.0.1
|
||||
bcrypt==4.0.1
|
||||
aiosqlite==0.20.0
|
||||
@@ -12,6 +12,9 @@ import DeviceForm from "./devices/DeviceForm";
|
||||
import UserList from "./users/UserList";
|
||||
import UserDetail from "./users/UserDetail";
|
||||
import UserForm from "./users/UserForm";
|
||||
import MqttDashboard from "./mqtt/MqttDashboard";
|
||||
import CommandPanel from "./mqtt/CommandPanel";
|
||||
import LogViewer from "./mqtt/LogViewer";
|
||||
|
||||
function ProtectedRoute({ children }) {
|
||||
const { user, loading } = useAuth();
|
||||
@@ -69,9 +72,9 @@ export default function App() {
|
||||
<Route path="users/new" element={<UserForm />} />
|
||||
<Route path="users/:id" element={<UserDetail />} />
|
||||
<Route path="users/:id/edit" element={<UserForm />} />
|
||||
{/* Phase 5+ routes:
|
||||
<Route path="mqtt" element={<MqttDashboard />} />
|
||||
*/}
|
||||
<Route path="mqtt/commands" element={<CommandPanel />} />
|
||||
<Route path="mqtt/logs" element={<LogViewer />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
|
||||
@@ -14,7 +14,15 @@ const navItems = [
|
||||
},
|
||||
{ to: "/devices", label: "Devices", roles: ["superadmin", "device_manager", "viewer"] },
|
||||
{ to: "/users", label: "Users", roles: ["superadmin", "user_manager", "viewer"] },
|
||||
{ to: "/mqtt", label: "MQTT", roles: ["superadmin", "device_manager", "viewer"] },
|
||||
{
|
||||
label: "MQTT",
|
||||
roles: ["superadmin", "device_manager", "viewer"],
|
||||
children: [
|
||||
{ to: "/mqtt", label: "Dashboard" },
|
||||
{ to: "/mqtt/commands", label: "Commands" },
|
||||
{ to: "/mqtt/logs", label: "Logs" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const linkClass = (isActive) =>
|
||||
|
||||
@@ -1 +1,350 @@
|
||||
// TODO: Send commands to devices
|
||||
import { useState, useEffect } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import api from "../api/client";
|
||||
|
||||
const QUICK_ACTIONS = [
|
||||
{ label: "Ping", cmd: "ping", contents: {} },
|
||||
{ label: "Report Status", cmd: "system_info", contents: { action: "report_status" } },
|
||||
{ label: "Get Settings", cmd: "system_info", contents: { action: "get_full_settings" } },
|
||||
{ label: "Network Info", cmd: "system_info", contents: { action: "network_info" } },
|
||||
{ label: "Device Time", cmd: "system_info", contents: { action: "get_device_time" } },
|
||||
{ label: "Clock Time", cmd: "system_info", contents: { action: "get_clock_time" } },
|
||||
{ label: "Firmware Status", cmd: "system_info", contents: { action: "get_firmware_status" } },
|
||||
{ label: "List Melodies", cmd: "file_manager", contents: { action: "list_melodies" } },
|
||||
{ label: "Restart", cmd: "system", contents: { action: "restart" }, danger: true },
|
||||
];
|
||||
|
||||
const STATUS_STYLES = {
|
||||
success: { bg: "var(--success-bg)", color: "var(--success-text)" },
|
||||
error: { bg: "var(--danger-bg)", color: "var(--danger-text)" },
|
||||
pending: { bg: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" },
|
||||
timeout: { bg: "var(--danger-bg)", color: "var(--danger-text)" },
|
||||
};
|
||||
|
||||
export default function CommandPanel() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const [devices, setDevices] = useState([]);
|
||||
const [selectedDevice, setSelectedDevice] = useState(searchParams.get("device") || "");
|
||||
const [customCmd, setCustomCmd] = useState("");
|
||||
const [customContents, setCustomContents] = useState("{}");
|
||||
const [commands, setCommands] = useState([]);
|
||||
const [commandsTotal, setCommandsTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [sending, setSending] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [lastResponse, setLastResponse] = useState(null);
|
||||
const [expandedCmd, setExpandedCmd] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
api.get("/devices").then((data) => {
|
||||
setDevices(data.devices || []);
|
||||
if (!selectedDevice && data.devices?.length > 0) {
|
||||
setSelectedDevice(data.devices[0].device_id || "");
|
||||
}
|
||||
}).catch(() => {});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedDevice) fetchCommands();
|
||||
}, [selectedDevice]);
|
||||
|
||||
const fetchCommands = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await api.get(`/mqtt/commands/${selectedDevice}?limit=50`);
|
||||
setCommands(data.commands || []);
|
||||
setCommandsTotal(data.total || 0);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const sendCommand = async (cmd, contents) => {
|
||||
if (!selectedDevice) {
|
||||
setError("Select a device first");
|
||||
return;
|
||||
}
|
||||
setSending(true);
|
||||
setError("");
|
||||
setLastResponse(null);
|
||||
try {
|
||||
const result = await api.post(`/mqtt/command/${selectedDevice}`, { cmd, contents });
|
||||
setLastResponse(result);
|
||||
// Wait briefly then refresh commands to see response
|
||||
setTimeout(fetchCommands, 2000);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const sendCustomCommand = () => {
|
||||
if (!customCmd.trim()) {
|
||||
setError("Enter a command name");
|
||||
return;
|
||||
}
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(customContents);
|
||||
} catch {
|
||||
setError("Invalid JSON in contents");
|
||||
return;
|
||||
}
|
||||
sendCommand(customCmd.trim(), parsed);
|
||||
};
|
||||
|
||||
const formatPayload = (jsonStr) => {
|
||||
if (!jsonStr) return null;
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(jsonStr), null, 2);
|
||||
} catch {
|
||||
return jsonStr;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold mb-6" style={{ color: "var(--text-heading)" }}>
|
||||
Command Panel
|
||||
</h1>
|
||||
|
||||
{/* Device Selector */}
|
||||
<div className="mb-6">
|
||||
<label className="block text-sm mb-2" style={{ color: "var(--text-secondary)" }}>
|
||||
Target Device
|
||||
</label>
|
||||
<select
|
||||
value={selectedDevice}
|
||||
onChange={(e) => setSelectedDevice(e.target.value)}
|
||||
className="w-full max-w-md px-3 py-2 rounded-md text-sm border"
|
||||
style={{ backgroundColor: "var(--bg-card)", color: "var(--text-primary)", borderColor: "var(--border-primary)" }}
|
||||
>
|
||||
<option value="">Select a device...</option>
|
||||
{devices.map((d) => (
|
||||
<option key={d.id} value={d.device_id}>
|
||||
{d.device_name || d.device_id} ({d.device_id})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div
|
||||
className="text-sm rounded-md p-3 mb-4 border"
|
||||
style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Quick Actions */}
|
||||
<div
|
||||
className="rounded-lg border p-4 mb-6"
|
||||
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
|
||||
>
|
||||
<h2 className="text-sm font-medium mb-3" style={{ color: "var(--text-heading)" }}>
|
||||
Quick Actions
|
||||
</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{QUICK_ACTIONS.map((action) => (
|
||||
<button
|
||||
key={action.label}
|
||||
onClick={() => sendCommand(action.cmd, action.contents)}
|
||||
disabled={sending || !selectedDevice}
|
||||
className="px-3 py-1.5 text-sm rounded-md hover:opacity-90 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
style={{
|
||||
backgroundColor: action.danger ? "var(--danger-btn)" : "var(--btn-primary)",
|
||||
color: "var(--text-white)",
|
||||
}}
|
||||
>
|
||||
{action.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Custom Command */}
|
||||
<div
|
||||
className="rounded-lg border p-4 mb-6"
|
||||
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
|
||||
>
|
||||
<h2 className="text-sm font-medium mb-3" style={{ color: "var(--text-heading)" }}>
|
||||
Custom Command
|
||||
</h2>
|
||||
<div className="flex flex-col gap-3">
|
||||
<div>
|
||||
<label className="block text-xs mb-1" style={{ color: "var(--text-muted)" }}>
|
||||
Command (cmd)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={customCmd}
|
||||
onChange={(e) => setCustomCmd(e.target.value)}
|
||||
placeholder="e.g. system_info"
|
||||
className="w-full max-w-md px-3 py-2 rounded-md text-sm border"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs mb-1" style={{ color: "var(--text-muted)" }}>
|
||||
Contents (JSON)
|
||||
</label>
|
||||
<textarea
|
||||
value={customContents}
|
||||
onChange={(e) => setCustomContents(e.target.value)}
|
||||
rows={4}
|
||||
className="w-full max-w-md px-3 py-2 rounded-md text-sm border font-mono"
|
||||
style={{ resize: "vertical" }}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<button
|
||||
onClick={sendCustomCommand}
|
||||
disabled={sending || !selectedDevice}
|
||||
className="px-4 py-2 text-sm rounded-md hover:opacity-90 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
|
||||
>
|
||||
{sending ? "Sending..." : "Send Command"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Last Response */}
|
||||
{lastResponse && (
|
||||
<div
|
||||
className="rounded-lg border p-4 mb-6"
|
||||
style={{
|
||||
backgroundColor: lastResponse.success ? "var(--success-bg)" : "var(--danger-bg)",
|
||||
borderColor: lastResponse.success ? "var(--success)" : "var(--danger)",
|
||||
}}
|
||||
>
|
||||
<p className="text-sm" style={{ color: lastResponse.success ? "var(--success-text)" : "var(--danger-text)" }}>
|
||||
{lastResponse.message}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Command History */}
|
||||
{selectedDevice && (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h2 className="text-lg font-semibold" style={{ color: "var(--text-heading)" }}>
|
||||
Command History
|
||||
</h2>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm" style={{ color: "var(--text-muted)" }}>
|
||||
{commandsTotal} commands
|
||||
</span>
|
||||
<button
|
||||
onClick={fetchCommands}
|
||||
className="text-sm hover:opacity-80 cursor-pointer"
|
||||
style={{ color: "var(--text-link)" }}
|
||||
>
|
||||
Refresh
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="text-center py-4" style={{ color: "var(--text-muted)" }}>Loading...</div>
|
||||
) : commands.length === 0 ? (
|
||||
<div
|
||||
className="rounded-lg p-6 text-center text-sm border"
|
||||
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", color: "var(--text-muted)" }}
|
||||
>
|
||||
No commands sent to this device yet.
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="rounded-lg overflow-hidden border"
|
||||
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
|
||||
>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
|
||||
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Time</th>
|
||||
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Command</th>
|
||||
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Status</th>
|
||||
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Details</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{commands.map((cmd, index) => {
|
||||
const style = STATUS_STYLES[cmd.status] || STATUS_STYLES.pending;
|
||||
const isExpanded = expandedCmd === cmd.id;
|
||||
return (
|
||||
<>
|
||||
<tr
|
||||
key={cmd.id}
|
||||
className="cursor-pointer"
|
||||
style={{
|
||||
borderBottom: (!isExpanded && index < commands.length - 1)
|
||||
? "1px solid var(--border-primary)" : "none",
|
||||
}}
|
||||
onClick={() => setExpandedCmd(isExpanded ? null : cmd.id)}
|
||||
>
|
||||
<td className="px-4 py-3 text-xs" style={{ color: "var(--text-muted)" }}>
|
||||
{cmd.sent_at?.replace("T", " ").substring(0, 19)}
|
||||
</td>
|
||||
<td className="px-4 py-3 font-mono text-xs" style={{ color: "var(--text-heading)" }}>
|
||||
{cmd.command_name}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<span
|
||||
className="px-2 py-0.5 text-xs rounded-full"
|
||||
style={{ backgroundColor: style.bg, color: style.color }}
|
||||
>
|
||||
{cmd.status}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-xs" style={{ color: "var(--text-muted)" }}>
|
||||
{cmd.responded_at ? `Replied ${cmd.responded_at.replace("T", " ").substring(0, 19)}` : "Awaiting response..."}
|
||||
</td>
|
||||
</tr>
|
||||
{isExpanded && (
|
||||
<tr key={`${cmd.id}-detail`} style={{ borderBottom: index < commands.length - 1 ? "1px solid var(--border-primary)" : "none" }}>
|
||||
<td colSpan={4} className="px-4 py-3" style={{ backgroundColor: "var(--bg-primary)" }}>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p className="text-xs font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
|
||||
Sent Payload
|
||||
</p>
|
||||
<pre
|
||||
className="text-xs p-2 rounded overflow-auto max-h-48 font-mono"
|
||||
style={{ backgroundColor: "var(--bg-card)", color: "var(--text-primary)" }}
|
||||
>
|
||||
{formatPayload(cmd.command_payload) || "—"}
|
||||
</pre>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
|
||||
Response
|
||||
</p>
|
||||
<pre
|
||||
className="text-xs p-2 rounded overflow-auto max-h-48 font-mono"
|
||||
style={{ backgroundColor: "var(--bg-card)", color: "var(--text-primary)" }}
|
||||
>
|
||||
{formatPayload(cmd.response_payload) || "Waiting..."}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
282
frontend/src/mqtt/LogViewer.jsx
Normal file
282
frontend/src/mqtt/LogViewer.jsx
Normal file
@@ -0,0 +1,282 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import api from "../api/client";
|
||||
import useMqttWebSocket from "./useMqttWebSocket";
|
||||
|
||||
const LEVEL_STYLES = {
|
||||
INFO: { bg: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" },
|
||||
WARN: { bg: "#3d2e00", color: "#fbbf24" },
|
||||
ERROR: { bg: "var(--danger-bg)", color: "var(--danger-text)" },
|
||||
};
|
||||
|
||||
export default function LogViewer() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const [devices, setDevices] = useState([]);
|
||||
const [selectedDevice, setSelectedDevice] = useState(searchParams.get("device") || "");
|
||||
const [logs, setLogs] = useState([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [levelFilter, setLevelFilter] = useState("");
|
||||
const [searchText, setSearchText] = useState("");
|
||||
const [autoRefresh, setAutoRefresh] = useState(false);
|
||||
const [liveLogs, setLiveLogs] = useState([]);
|
||||
const [offset, setOffset] = useState(0);
|
||||
const limit = 100;
|
||||
|
||||
useEffect(() => {
|
||||
api.get("/devices").then((data) => {
|
||||
setDevices(data.devices || []);
|
||||
if (!selectedDevice && data.devices?.length > 0) {
|
||||
setSelectedDevice(data.devices[0].device_id || "");
|
||||
}
|
||||
}).catch(() => {});
|
||||
}, []);
|
||||
|
||||
const fetchLogs = async () => {
|
||||
if (!selectedDevice) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (levelFilter) params.set("level", levelFilter);
|
||||
if (searchText) params.set("search", searchText);
|
||||
params.set("limit", limit.toString());
|
||||
params.set("offset", offset.toString());
|
||||
const data = await api.get(`/mqtt/logs/${selectedDevice}?${params}`);
|
||||
setLogs(data.logs || []);
|
||||
setTotal(data.total || 0);
|
||||
setError("");
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedDevice) {
|
||||
setOffset(0);
|
||||
fetchLogs();
|
||||
}
|
||||
}, [selectedDevice, levelFilter, searchText]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedDevice && offset > 0) fetchLogs();
|
||||
}, [offset]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!autoRefresh || !selectedDevice) return;
|
||||
const interval = setInterval(fetchLogs, 5000);
|
||||
return () => clearInterval(interval);
|
||||
}, [autoRefresh, selectedDevice, levelFilter, searchText]);
|
||||
|
||||
const handleWsMessage = useCallback(
|
||||
(data) => {
|
||||
if (
|
||||
data.type === "logs" &&
|
||||
(!selectedDevice || data.device_serial === selectedDevice)
|
||||
) {
|
||||
const logEntry = {
|
||||
id: Date.now(),
|
||||
device_serial: data.device_serial,
|
||||
level: data.payload?.level?.includes("EROR")
|
||||
? "ERROR"
|
||||
: data.payload?.level?.includes("WARN")
|
||||
? "WARN"
|
||||
: "INFO",
|
||||
message: data.payload?.message || "",
|
||||
device_timestamp: data.payload?.timestamp,
|
||||
received_at: new Date().toISOString(),
|
||||
_live: true,
|
||||
};
|
||||
setLiveLogs((prev) => [logEntry, ...prev].slice(0, 50));
|
||||
}
|
||||
},
|
||||
[selectedDevice]
|
||||
);
|
||||
|
||||
useMqttWebSocket({ enabled: true, onMessage: handleWsMessage });
|
||||
|
||||
const allLogs = [...liveLogs.filter((l) => {
|
||||
if (levelFilter && l.level !== levelFilter) return false;
|
||||
if (searchText && !l.message.toLowerCase().includes(searchText.toLowerCase())) return false;
|
||||
return true;
|
||||
}), ...logs];
|
||||
|
||||
const hasMore = offset + limit < total;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold mb-6" style={{ color: "var(--text-heading)" }}>
|
||||
Log Viewer
|
||||
</h1>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="mb-4 space-y-3">
|
||||
<div className="flex flex-wrap gap-3 items-end">
|
||||
<div>
|
||||
<label className="block text-xs mb-1" style={{ color: "var(--text-muted)" }}>Device</label>
|
||||
<select
|
||||
value={selectedDevice}
|
||||
onChange={(e) => { setSelectedDevice(e.target.value); setLiveLogs([]); }}
|
||||
className="px-3 py-2 rounded-md text-sm border"
|
||||
style={{ backgroundColor: "var(--bg-card)", color: "var(--text-primary)", borderColor: "var(--border-primary)" }}
|
||||
>
|
||||
<option value="">Select device...</option>
|
||||
{devices.map((d) => (
|
||||
<option key={d.id} value={d.device_id}>
|
||||
{d.device_name || d.device_id} ({d.device_id})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs mb-1" style={{ color: "var(--text-muted)" }}>Level</label>
|
||||
<select
|
||||
value={levelFilter}
|
||||
onChange={(e) => setLevelFilter(e.target.value)}
|
||||
className="px-3 py-2 rounded-md text-sm border"
|
||||
style={{ backgroundColor: "var(--bg-card)", color: "var(--text-primary)", borderColor: "var(--border-primary)" }}
|
||||
>
|
||||
<option value="">All Levels</option>
|
||||
<option value="INFO">INFO</option>
|
||||
<option value="WARN">WARN</option>
|
||||
<option value="ERROR">ERROR</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex-1 min-w-48">
|
||||
<label className="block text-xs mb-1" style={{ color: "var(--text-muted)" }}>Search</label>
|
||||
<input
|
||||
type="text"
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
placeholder="Search log messages..."
|
||||
className="w-full px-3 py-2 rounded-md text-sm border"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<label className="flex items-center gap-2 text-sm cursor-pointer" style={{ color: "var(--text-secondary)" }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={autoRefresh}
|
||||
onChange={(e) => setAutoRefresh(e.target.checked)}
|
||||
/>
|
||||
Auto-refresh
|
||||
</label>
|
||||
<button
|
||||
onClick={fetchLogs}
|
||||
className="px-3 py-2 text-sm rounded-md border hover:opacity-80 cursor-pointer"
|
||||
style={{ borderColor: "var(--border-primary)", color: "var(--text-primary)" }}
|
||||
>
|
||||
Refresh
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-sm" style={{ color: "var(--text-muted)" }}>
|
||||
{total} total logs{liveLogs.length > 0 ? ` + ${liveLogs.length} live` : ""}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div
|
||||
className="text-sm rounded-md p-3 mb-4 border"
|
||||
style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!selectedDevice ? (
|
||||
<div
|
||||
className="rounded-lg p-8 text-center text-sm border"
|
||||
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", color: "var(--text-muted)" }}
|
||||
>
|
||||
Select a device to view logs.
|
||||
</div>
|
||||
) : loading && logs.length === 0 ? (
|
||||
<div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>
|
||||
) : allLogs.length === 0 ? (
|
||||
<div
|
||||
className="rounded-lg p-8 text-center text-sm border"
|
||||
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", color: "var(--text-muted)" }}
|
||||
>
|
||||
No logs found for this device.
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div
|
||||
className="rounded-lg overflow-hidden border"
|
||||
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
|
||||
>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
|
||||
<th className="px-4 py-3 text-left font-medium w-44" style={{ color: "var(--text-secondary)" }}>Time</th>
|
||||
<th className="px-4 py-3 text-left font-medium w-20" style={{ color: "var(--text-secondary)" }}>Level</th>
|
||||
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Message</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{allLogs.map((log, index) => {
|
||||
const style = LEVEL_STYLES[log.level] || LEVEL_STYLES.INFO;
|
||||
return (
|
||||
<tr
|
||||
key={log._live ? `live-${log.id}` : log.id}
|
||||
style={{
|
||||
borderBottom: index < allLogs.length - 1 ? "1px solid var(--border-primary)" : "none",
|
||||
backgroundColor: log._live ? "rgba(116, 184, 22, 0.05)" : "transparent",
|
||||
}}
|
||||
>
|
||||
<td className="px-4 py-2.5 text-xs font-mono" style={{ color: "var(--text-muted)" }}>
|
||||
{log.received_at?.replace("T", " ").substring(0, 19)}
|
||||
{log._live && (
|
||||
<span className="ml-1 text-xs" style={{ color: "var(--accent)" }}>LIVE</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-2.5">
|
||||
<span
|
||||
className="px-2 py-0.5 text-xs rounded-full"
|
||||
style={{ backgroundColor: style.bg, color: style.color }}
|
||||
>
|
||||
{log.level}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-2.5 font-mono text-xs" style={{ color: "var(--text-primary)" }}>
|
||||
{log.message}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
<div className="flex items-center justify-between mt-4">
|
||||
<button
|
||||
onClick={() => setOffset(Math.max(0, offset - limit))}
|
||||
disabled={offset === 0}
|
||||
className="px-3 py-1.5 text-sm rounded-md border hover:opacity-80 cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
style={{ borderColor: "var(--border-primary)", color: "var(--text-primary)" }}
|
||||
>
|
||||
Previous
|
||||
</button>
|
||||
<span className="text-sm" style={{ color: "var(--text-muted)" }}>
|
||||
Showing {offset + 1}–{Math.min(offset + limit, total)} of {total}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setOffset(offset + limit)}
|
||||
disabled={!hasMore}
|
||||
className="px-3 py-1.5 text-sm rounded-md border hover:opacity-80 cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
style={{ borderColor: "var(--border-primary)", color: "var(--text-primary)" }}
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1 +1,272 @@
|
||||
// TODO: Live data, logs, charts
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import api from "../api/client";
|
||||
import useMqttWebSocket from "./useMqttWebSocket";
|
||||
|
||||
export default function MqttDashboard() {
|
||||
const [devices, setDevices] = useState([]);
|
||||
const [brokerConnected, setBrokerConnected] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [hoveredRow, setHoveredRow] = useState(null);
|
||||
const [liveEvents, setLiveEvents] = useState([]);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const fetchStatus = async () => {
|
||||
try {
|
||||
const data = await api.get("/mqtt/status");
|
||||
setDevices(data.devices || []);
|
||||
setBrokerConnected(data.broker_connected);
|
||||
setError("");
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchStatus();
|
||||
const interval = setInterval(fetchStatus, 30000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
const handleWsMessage = useCallback((data) => {
|
||||
setLiveEvents((prev) => [data, ...prev].slice(0, 50));
|
||||
// Update device status on heartbeat
|
||||
if (data.type === "status/heartbeat") {
|
||||
setDevices((prev) => {
|
||||
const existing = prev.find((d) => d.device_serial === data.device_serial);
|
||||
if (existing) {
|
||||
return prev.map((d) =>
|
||||
d.device_serial === data.device_serial
|
||||
? { ...d, online: true, seconds_since_heartbeat: 0 }
|
||||
: d
|
||||
);
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
const { connected: wsConnected } = useMqttWebSocket({
|
||||
enabled: true,
|
||||
onMessage: handleWsMessage,
|
||||
});
|
||||
|
||||
const sendPing = async (serial, e) => {
|
||||
e.stopPropagation();
|
||||
try {
|
||||
await api.post(`/mqtt/command/${serial}`, { cmd: "ping", contents: {} });
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const formatTime = (seconds) => {
|
||||
if (!seconds && seconds !== 0) return "Never";
|
||||
if (seconds < 60) return `${seconds}s ago`;
|
||||
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
|
||||
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
|
||||
return `${Math.floor(seconds / 86400)}d ago`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>
|
||||
MQTT Dashboard
|
||||
</h1>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="flex items-center gap-2 text-sm" style={{ color: "var(--text-muted)" }}>
|
||||
<span
|
||||
className={`inline-block w-2.5 h-2.5 rounded-full ${brokerConnected ? "bg-green-500" : ""}`}
|
||||
style={!brokerConnected ? { backgroundColor: "var(--danger)" } : undefined}
|
||||
/>
|
||||
Broker {brokerConnected ? "Connected" : "Disconnected"}
|
||||
</span>
|
||||
<span className="flex items-center gap-2 text-sm" style={{ color: "var(--text-muted)" }}>
|
||||
<span
|
||||
className={`inline-block w-2.5 h-2.5 rounded-full ${wsConnected ? "bg-green-500" : ""}`}
|
||||
style={!wsConnected ? { backgroundColor: "var(--border-primary)" } : undefined}
|
||||
/>
|
||||
Live
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div
|
||||
className="text-sm rounded-md p-3 mb-4 border"
|
||||
style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>
|
||||
) : devices.length === 0 ? (
|
||||
<div
|
||||
className="rounded-lg p-8 text-center text-sm border"
|
||||
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", color: "var(--text-muted)" }}
|
||||
>
|
||||
No devices have sent heartbeats yet. Devices will appear here once they connect to the MQTT broker.
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="rounded-lg overflow-hidden border mb-6"
|
||||
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
|
||||
>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
|
||||
<th className="px-4 py-3 text-left font-medium w-10" style={{ color: "var(--text-secondary)" }}>Status</th>
|
||||
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Serial</th>
|
||||
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Device ID</th>
|
||||
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Firmware</th>
|
||||
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>IP Address</th>
|
||||
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Uptime</th>
|
||||
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Last Seen</th>
|
||||
<th className="px-4 py-3 text-left font-medium w-32" style={{ color: "var(--text-secondary)" }}>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{devices.map((device, index) => (
|
||||
<tr
|
||||
key={device.device_serial}
|
||||
className="cursor-pointer"
|
||||
style={{
|
||||
borderBottom: index < devices.length - 1 ? "1px solid var(--border-primary)" : "none",
|
||||
backgroundColor: hoveredRow === device.device_serial ? "var(--bg-card-hover)" : "transparent",
|
||||
}}
|
||||
onMouseEnter={() => setHoveredRow(device.device_serial)}
|
||||
onMouseLeave={() => setHoveredRow(null)}
|
||||
onClick={() => navigate(`/mqtt/commands?device=${device.device_serial}`)}
|
||||
>
|
||||
<td className="px-4 py-3">
|
||||
<span
|
||||
className={`inline-block w-2.5 h-2.5 rounded-full ${device.online ? "bg-green-500" : ""}`}
|
||||
style={!device.online ? { backgroundColor: "var(--border-primary)" } : undefined}
|
||||
title={device.online ? "Online" : "Offline"}
|
||||
/>
|
||||
</td>
|
||||
<td className="px-4 py-3 font-mono text-xs" style={{ color: "var(--text-heading)" }}>
|
||||
{device.device_serial}
|
||||
</td>
|
||||
<td className="px-4 py-3 font-mono text-xs" style={{ color: "var(--text-muted)" }}>
|
||||
{device.last_heartbeat?.device_id || "-"}
|
||||
</td>
|
||||
<td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>
|
||||
{device.last_heartbeat?.firmware_version ? `v${device.last_heartbeat.firmware_version}` : "-"}
|
||||
</td>
|
||||
<td className="px-4 py-3 font-mono text-xs" style={{ color: "var(--text-primary)" }}>
|
||||
{device.last_heartbeat?.ip_address || "-"}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-xs" style={{ color: "var(--text-muted)" }}>
|
||||
{device.last_heartbeat?.uptime_display || "-"}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-xs" style={{ color: "var(--text-muted)" }}>
|
||||
{formatTime(device.seconds_since_heartbeat)}
|
||||
</td>
|
||||
<td className="px-4 py-3" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={(e) => sendPing(device.device_serial, e)}
|
||||
className="hover:opacity-80 text-xs cursor-pointer"
|
||||
style={{ color: "var(--text-link)" }}
|
||||
>
|
||||
Ping
|
||||
</button>
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); navigate(`/mqtt/logs?device=${device.device_serial}`); }}
|
||||
className="hover:opacity-80 text-xs cursor-pointer"
|
||||
style={{ color: "var(--text-link)" }}
|
||||
>
|
||||
Logs
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Live Event Feed */}
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold mb-3" style={{ color: "var(--text-heading)" }}>
|
||||
Live Feed
|
||||
{wsConnected && (
|
||||
<span className="ml-2 text-xs font-normal" style={{ color: "var(--text-muted)" }}>
|
||||
(streaming)
|
||||
</span>
|
||||
)}
|
||||
</h2>
|
||||
<div
|
||||
className="rounded-lg border overflow-hidden"
|
||||
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
|
||||
>
|
||||
{liveEvents.length === 0 ? (
|
||||
<div className="p-6 text-center text-sm" style={{ color: "var(--text-muted)" }}>
|
||||
{wsConnected ? "Waiting for MQTT messages..." : "WebSocket not connected — live events will appear once connected."}
|
||||
</div>
|
||||
) : (
|
||||
<div className="max-h-80 overflow-y-auto">
|
||||
<table className="w-full text-xs">
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
|
||||
<th className="px-3 py-2 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Type</th>
|
||||
<th className="px-3 py-2 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Device</th>
|
||||
<th className="px-3 py-2 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Data</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{liveEvents.map((event, i) => (
|
||||
<tr
|
||||
key={i}
|
||||
style={{ borderBottom: "1px solid var(--border-primary)" }}
|
||||
>
|
||||
<td className="px-3 py-2">
|
||||
<span
|
||||
className="px-1.5 py-0.5 rounded text-xs"
|
||||
style={{
|
||||
backgroundColor: event.type === "logs"
|
||||
? "var(--badge-blue-bg)"
|
||||
: event.type === "status/heartbeat"
|
||||
? "var(--success-bg)"
|
||||
: "var(--bg-primary)",
|
||||
color: event.type === "logs"
|
||||
? "var(--badge-blue-text)"
|
||||
: event.type === "status/heartbeat"
|
||||
? "var(--success-text)"
|
||||
: "var(--text-secondary)",
|
||||
}}
|
||||
>
|
||||
{event.type}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-3 py-2 font-mono" style={{ color: "var(--text-muted)" }}>
|
||||
{event.device_serial}
|
||||
</td>
|
||||
<td className="px-3 py-2" style={{ color: "var(--text-primary)" }}>
|
||||
{event.type === "logs"
|
||||
? event.payload?.message || JSON.stringify(event.payload)
|
||||
: event.type === "status/heartbeat"
|
||||
? `Uptime: ${event.payload?.payload?.timestamp || "?"} | IP: ${event.payload?.payload?.ip_address || "?"}`
|
||||
: JSON.stringify(event.payload).substring(0, 120)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
47
frontend/src/mqtt/useMqttWebSocket.js
Normal file
47
frontend/src/mqtt/useMqttWebSocket.js
Normal file
@@ -0,0 +1,47 @@
|
||||
import { useEffect, useRef, useState, useCallback } from "react";
|
||||
|
||||
export default function useMqttWebSocket({ enabled = true, onMessage } = {}) {
|
||||
const wsRef = useRef(null);
|
||||
const [connected, setConnected] = useState(false);
|
||||
const reconnectTimer = useRef(null);
|
||||
const onMessageRef = useRef(onMessage);
|
||||
onMessageRef.current = onMessage;
|
||||
|
||||
const connect = useCallback(() => {
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (!token) return;
|
||||
|
||||
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
const ws = new WebSocket(
|
||||
`${protocol}//${window.location.host}/api/mqtt/ws?token=${token}`
|
||||
);
|
||||
|
||||
ws.onopen = () => setConnected(true);
|
||||
ws.onclose = () => {
|
||||
setConnected(false);
|
||||
if (enabled) {
|
||||
reconnectTimer.current = setTimeout(connect, 5000);
|
||||
}
|
||||
};
|
||||
ws.onerror = () => {};
|
||||
ws.onmessage = (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
onMessageRef.current?.(data);
|
||||
} catch {
|
||||
// ignore invalid JSON
|
||||
}
|
||||
};
|
||||
wsRef.current = ws;
|
||||
}, [enabled]);
|
||||
|
||||
useEffect(() => {
|
||||
if (enabled) connect();
|
||||
return () => {
|
||||
clearTimeout(reconnectTimer.current);
|
||||
wsRef.current?.close();
|
||||
};
|
||||
}, [enabled, connect]);
|
||||
|
||||
return { connected };
|
||||
}
|
||||
@@ -25,7 +25,7 @@ http {
|
||||
}
|
||||
|
||||
# WebSocket support for MQTT live data
|
||||
location /api/ws {
|
||||
location /api/mqtt/ws {
|
||||
proxy_pass http://backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
|
||||
Reference in New Issue
Block a user