Phase 5 Complete by Claude Code

This commit is contained in:
2026-02-17 23:45:20 +02:00
parent fc2d04b8bb
commit c0605c77db
17 changed files with 1663 additions and 12 deletions

View File

@@ -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>
);
}

View 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>
);
}

View File

@@ -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>
);
}

View 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 };
}