feat(mqtt): add MQTT broker connection support

This commit is contained in:
jinmo authored and GitHub committed 2026-08-04 19:05:05 +08:00
1 parent dff33662fc
commit 8cfe380784
125 files changed
+23056 -107

No files matched your search

@@ -17,6 +17,7 @@ import { Switch } from "@/components/ui/switch";
import type { ConnectionConfig, ConnectionTestResult, DatabaseConnectionInfo, DatabaseType, HttpTunnelConfig, IdentifierCase, JdbcDriverInfo, JdbcLocalBundleInfo, JdbcMavenBundleInfo, ProxyTunnelConfig, SshConfigHostEntry, SshTunnelConfig, TransportLayerConfig } from "@/types/database";
import type { InfluxDbExternalConfig, InfluxDbVersion } from "@/types/influxdb";
import type { MqAdminConfig, MqAuth, MqSystemKind } from "@/types/mq";
import type { MqttConnectionConfig } from "@/types/mqtt";
import type { NacosAdminConfig, NacosAuthConfig, NacosImplementation, NacosMetricsMode, NacosRNacosConsoleAuth, NacosVersionMode } from "@/types/nacos";
import { CONNECTION_ATTEMPT_CANCELLED_MESSAGE, useConnectionStore } from "@/stores/connectionStore";
import { useTunnelProfileStore } from "@/stores/tunnelProfileStore";
@@ -657,6 +658,23 @@ const nacosTlsSkipVerify = ref(false);
const nacosMetricsMode = ref<NacosMetricsMode>("auto");
const nacosMetricsUrl = ref("");
const nacosPageSize = ref(20);
// --- MQTT-specific form fields ---
const mqttHost = ref("127.0.0.1");
const mqttPort = ref(1883);
const mqttClientId = ref("");
const mqttProtocolVersion = ref<"v3" | "v4" | "v5">("v5");
const mqttTransportMode = ref<"tcp" | "websocket">("tcp");
const mqttWsPath = ref("/mqtt");
const mqttAuthKind = ref<"none" | "password">("none");
const mqttUsername = ref("");
const mqttPassword = ref("");
const mqttTls = ref(false);
const mqttTlsSkipVerify = ref(false);
const mqttKeepAliveSecs = ref(60);
const mqttConnectTimeoutSecs = ref(30);
const mqttMaxPacketSizeBytes = ref(16 * 1024 * 1024);
const nacosPrimaryAddressLabel = computed(() => {
if (nacosImplementation.value === "rnacos") return t("connection.nacosPrimaryAddressRNacos");
if (nacosVersionMode.value === "v2") return t("connection.nacosPrimaryAddressV2");
@@ -973,6 +991,7 @@ const driverProfiles: Record<
rocketmq: { type: "mq", port: 9876, user: "", label: "Apache RocketMQ", icon: "rocketmq", host: "127.0.0.1" },
rabbitmq: { type: "mq", port: 5672, user: "", label: "RabbitMQ", icon: "rabbitmq", host: "127.0.0.1" },
nacos: { type: "nacos", port: 8848, user: "nacos", label: "Nacos", icon: "nacos", host: "127.0.0.1" },
mqtt: { type: "mqtt", port: 1883, user: "", label: "MQTT", icon: "mqtt", host: "127.0.0.1" },
iris: { type: "iris", port: 1972, user: "_SYSTEM", label: "IRIS", icon: "iris" },
influxdb: { type: "influxdb", port: 8086, user: "", label: "InfluxDB", icon: "InfluxDB" },
custom_mysql: {
@@ -1188,6 +1207,57 @@ function hydrateNacosFields(value: unknown) {
resetNacosFields(value as Partial<NacosAdminConfig>);
}
function resetMqttFields(config?: Partial<MqttConnectionConfig>) {
mqttHost.value = config?.host?.trim() || "127.0.0.1";
mqttPort.value = config?.port || 1883;
mqttClientId.value = config?.clientId || "";
mqttProtocolVersion.value = config?.protocolVersion || "v5";
mqttTransportMode.value = config?.transport || "tcp";
mqttWsPath.value = config?.wsPath || "/mqtt";
mqttTls.value = config?.tls || false;
mqttTlsSkipVerify.value = config?.tlsSkipVerify || false;
mqttKeepAliveSecs.value = Math.max(1, config?.keepAliveSecs || 60);
mqttConnectTimeoutSecs.value = Math.max(1, config?.connectTimeoutSecs || 30);
mqttMaxPacketSizeBytes.value = Math.min(268435455, Math.max(1024, config?.maxPacketSizeBytes || 16 * 1024 * 1024));
const auth = config?.auth;
if (auth && auth.kind === "password") {
mqttAuthKind.value = "password";
mqttUsername.value = auth.username || "";
mqttPassword.value = auth.password || "";
} else {
mqttAuthKind.value = "none";
mqttUsername.value = "";
mqttPassword.value = "";
}
}
function hydrateMqttFields(value: unknown) {
if (!value || typeof value !== "object") {
resetMqttFields();
return;
}
resetMqttFields(value as Partial<MqttConnectionConfig>);
}
function buildMqttExternalConfig(): MqttConnectionConfig {
const auth: MqttConnectionConfig["auth"] = mqttAuthKind.value === "password" ? { kind: "password", username: mqttUsername.value, password: mqttPassword.value } : { kind: "none" };
return {
host: mqttHost.value.trim(),
port: mqttPort.value,
clientId: mqttClientId.value.trim() || `dbx-${Math.random().toString(36).slice(2, 10)}`,
protocolVersion: mqttProtocolVersion.value,
transport: mqttTransportMode.value,
tls: mqttTls.value,
tlsSkipVerify: mqttTlsSkipVerify.value,
auth,
keepAliveSecs: Math.max(1, mqttKeepAliveSecs.value),
connectTimeoutSecs: Math.max(1, mqttConnectTimeoutSecs.value),
maxPacketSizeBytes: Math.min(268435455, Math.max(1024, mqttMaxPacketSizeBytes.value)),
wsPath: mqttTransportMode.value === "websocket" ? mqttWsPath.value || "/mqtt" : undefined,
};
}
const influxDbVersion = ref<InfluxDbVersion>("1");
const influxDbOrg = ref("");
@@ -1957,6 +2027,12 @@ function applyProfile(val: string, preserveConnectionFields = false) {
form.value.connection_string = undefined;
form.value.url_params = "";
}
if (profile.type === "mqtt") {
resetMqttFields();
form.value.database = undefined;
form.value.connection_string = undefined;
form.value.url_params = "";
}
if (profile.type === "influxdb") {
resetInfluxDbFields();
form.value.database = undefined;
@@ -2060,6 +2136,11 @@ watch(
} else {
resetNacosFields();
}
if (config.db_type === "mqtt") {
hydrateMqttFields(config.external_config);
} else {
resetMqttFields();
}
if (config.db_type === "influxdb") {
hydrateInfluxDbFields(config.external_config);
} else {
@@ -2304,6 +2385,7 @@ const iconTypeMap: Record<string, string> = {
rocketmq: "rocketmq",
rabbitmq: "rabbitmq",
nacos: "nacos",
mqtt: "mqtt",
dm: "dm",
h2: "h2",
snowflake: "snowflake",
@@ -2403,6 +2485,7 @@ const dbOptions: DbOption[] = [
{ value: "kafka", label: "Apache Kafka" },
{ value: "rocketmq", label: "Apache RocketMQ" },
{ value: "rabbitmq", label: "RabbitMQ" },
{ value: "mqtt", label: "MQTT" },
{ value: "nacos", label: "Nacos" },
{ value: "influxdb", label: "InfluxDB" },
{ value: "iris", label: "IRIS" },
@@ -2456,7 +2539,7 @@ const dbCategoryDefinitions: Array<{
{
key: "mq",
titleKey: "connection.databaseCategoryMq",
optionValues: ["mq", "kafka", "rocketmq", "rabbitmq"],
optionValues: ["mq", "kafka", "rocketmq", "rabbitmq", "mqtt"],
},
{
key: "registry_config",
@@ -2864,6 +2947,7 @@ const hasRequiredConnectionTarget = computed(() => {
return !!mqAdminUrl.value.trim();
}
if (form.value.db_type === "zookeeper") return !!(form.value.host || form.value.connection_string || connectionUrlInput.value.trim());
if (form.value.db_type === "mqtt") return !!mqttHost.value.trim() && mqttPort.value > 0;
if (form.value.db_type === "nacos") return !!nacosServerAddr.value.trim();
if (isCloudflareD1Connection(form.value)) return hasCloudflareD1Credentials(form.value);
if (isH2FileMode.value) return !!(form.value.host.trim() || h2FilePathFromJdbcUrl(form.value.connection_string));
@@ -3264,6 +3348,19 @@ function connectionConfigForSubmit(id: string, generatedName = ""): ConnectionCo
config.database = nacosConfig.namespace || undefined;
config.connection_string = undefined;
config.url_params = "";
} else if (config.db_type === "mqtt") {
const mqttConfig = buildMqttExternalConfig();
config.external_config = mqttConfig;
config.driver_profile = "mqtt";
config.driver_label = "MQTT";
config.host = mqttConfig.host;
config.port = mqttConfig.port;
config.ssl = mqttConfig.tls;
config.username = "";
config.password = "";
config.database = undefined;
config.connection_string = undefined;
config.url_params = "";
} else if (config.db_type === "influxdb") {
config.external_config = buildInfluxDbExternalConfig();
config.connection_string = undefined;
@@ -5851,6 +5948,81 @@ function openExternalUrl(url: string) {
</template>
</template>
<!-- MQTT: broker address, client ID, protocol version, auth, TLS -->
<template v-else-if="form.db_type === 'mqtt'">
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.mqttBrokerAddress") }}</Label>
<Input v-model="mqttHost" class="col-span-3" :placeholder="t('connection.mqttBrokerAddressPlaceholder')" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.mqttBrokerPort") }}</Label>
<Input v-model.number="mqttPort" type="number" class="col-span-3 w-24" min="1" max="65535" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.mqttClientId") }}</Label>
<Input v-model="mqttClientId" class="col-span-3" :placeholder="t('connection.mqttClientIdPlaceholder')" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.mqttProtocolVersion") }}</Label>
<select v-model="mqttProtocolVersion" class="col-span-3 flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring">
<option value="v5">MQTT 5.0</option>
<option value="v4">MQTT 3.1.1</option>
<option value="v3">MQTT 3.1</option>
</select>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.mqttTransport") }}</Label>
<div class="col-span-3 flex gap-2">
<Button size="sm" :variant="mqttTransportMode === 'tcp' ? 'default' : 'outline'" @click="mqttTransportMode = 'tcp'">{{ t("connection.mqttTransportTcp") }}</Button>
<Button size="sm" :variant="mqttTransportMode === 'websocket' ? 'default' : 'outline'" @click="mqttTransportMode = 'websocket'">{{ t("connection.mqttTransportWebSocket") }}</Button>
</div>
</div>
<div v-if="mqttTransportMode === 'websocket'" class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.mqttWsPath") }}</Label>
<Input v-model="mqttWsPath" class="col-span-3" :placeholder="t('connection.mqttWsPathPlaceholder')" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.mqAuth") }}</Label>
<div class="col-span-3 flex gap-2">
<Button size="sm" :variant="mqttAuthKind === 'none' ? 'default' : 'outline'" @click="mqttAuthKind = 'none'">{{ t("connection.mqAuthNone") }}</Button>
<Button size="sm" :variant="mqttAuthKind === 'password' ? 'default' : 'outline'" @click="mqttAuthKind = 'password'">{{ t("connection.mqAuthBasic") }}</Button>
</div>
</div>
<template v-if="mqttAuthKind === 'password'">
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.mqttUsername") }}</Label>
<Input v-model="mqttUsername" class="col-span-3" :placeholder="t('connection.mqttUsernamePlaceholder')" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.mqttPassword") }}</Label>
<Input v-model="mqttPassword" type="password" class="col-span-3" :placeholder="t('connection.mqttPasswordPlaceholder')" />
</div>
</template>
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.mqttTls") }}</Label>
<div class="col-span-3 flex items-center gap-2">
<Switch :checked="mqttTls" @update:checked="mqttTls = $event" />
<Label class="text-sm" :class="mqttTls ? '' : 'text-muted-foreground'">TLS</Label>
<template v-if="mqttTls">
<Switch :checked="mqttTlsSkipVerify" @update:checked="mqttTlsSkipVerify = $event" class="ml-4" />
<Label class="text-sm" :class="mqttTlsSkipVerify ? '' : 'text-muted-foreground'">{{ t("connection.mqttTlsSkipVerify") }}</Label>
</template>
</div>
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.mqttKeepAlive") }}</Label>
<Input v-model.number="mqttKeepAliveSecs" type="number" class="col-span-3 w-32" min="1" max="65535" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.mqttConnectTimeout") }}</Label>
<Input v-model.number="mqttConnectTimeoutSecs" type="number" class="col-span-3 w-32" min="1" max="300" />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">最大报文(字节)</Label>
<Input v-model.number="mqttMaxPacketSizeBytes" type="number" class="col-span-3 w-40" min="1024" max="268435455" />
</div>
</template>
<!-- InfluxDB: v1 username/password or v2 token/org/bucket -->
<template v-else-if="form.db_type === 'influxdb'">
<div class="grid grid-cols-4 items-center gap-4">
@@ -103,6 +103,7 @@ const assetIcons: Record<string, string> = {
zookeeper: "zookeeper",
oscar: "oscar.png",
jdbcx: "jdbcx",
mqtt: "mqtt",
};
const normalizedType = computed(() => props.dbType.toLowerCase().replace(/[\s-]+/g, "_"));
@@ -58,6 +58,7 @@ const VectorBrowser = defineAsyncComponent(() => import("@/components/vector/Vec
const HBaseBrowser = defineAsyncComponent(() => import("@/components/hbase/HBaseBrowser.vue"));
const ElasticsearchJsonResponsePanel = defineAsyncComponent(() => import("@/components/common/ElasticsearchJsonResponsePanel.vue"));
const MqAdminConsole = defineAsyncComponent(() => import("@/components/mq/MqAdminConsole.vue"));
const MqttAdminConsole = defineAsyncComponent(() => import("@/components/mqtt/MqttAdminConsole.vue"));
const NacosAdminConsole = defineAsyncComponent(() => import("@/components/nacos/NacosAdminConsole.vue"));
const NacosDashboard = defineAsyncComponent(() => import("@/components/nacos/NacosDashboard.vue"));
const ObjectBrowser = defineAsyncComponent(() => import("@/components/objects/ObjectBrowser.vue"));
@@ -1878,6 +1879,12 @@ defineExpose({ focusSearch, refreshData, refreshQueryEditorCompletionCache, hand
</div>
</template>
<template v-else-if="activeTab.mode === 'mqtt'">
<div class="flex-1 min-h-0">
<MqttAdminConsole :key="activeTab.id" :connection-id="activeTab.connectionId" :initial-topic="activeTab.mqttInitialTopic" />
</div>
</template>
<template v-else-if="activeTab.mode === 'nacos'">
<div class="flex-1 min-h-0">
<NacosAdminConsole
@@ -0,0 +1,246 @@
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useI18n } from "vue-i18n";
import { mqttGetBrokerInfo, mqttListTopics, mqttGetTopicTree, mqttGetMessages, mqttSubscribe, mqttUnsubscribe, mqttClearMessages } from "@/lib/backend/api";
import type { MqttBrokerInfo, MqttTopicNode, MqttMessage } from "@/types/mqtt";
import { Button } from "@/components/ui/button";
import TopicTreeNode from "./TopicTreeNode.vue";
import MqttPublishPanel from "./MqttPublishDialog.vue";
import { decodePayload, PAYLOAD_ENCODINGS, PAYLOAD_ENCODING_LABELS, type PayloadEncoding } from "@/lib/mqtt/mqttPayloadCodec";
interface Props {
connectionId: string;
initialTopic?: string;
}
const props = defineProps<Props>();
const { t } = useI18n();
/* ========== State ========== */
const brokerInfo = ref<MqttBrokerInfo | null>(null);
const topicTree = ref<MqttTopicNode | null>(null);
const messages = ref<MqttMessage[]>([]);
const subscribedTopics = ref<[string, string][]>([]);
const selectedTopic = ref<string>(props.initialTopic ?? "");
const loading = ref(true);
const error = ref<string | null>(null);
const pollingTimer = ref<ReturnType<typeof setInterval> | null>(null);
/* Payload 显示编码格式 */
const displayEncoding = ref<PayloadEncoding>("plaintext");
/* ========== Computed ========== */
const connected = computed(() => brokerInfo.value?.connected ?? false);
/* ========== 数据刷新 ========== */
async function refreshData() {
try {
const [info, topics, tree, msgs] = await Promise.all([
mqttGetBrokerInfo(props.connectionId) as Promise<MqttBrokerInfo>,
mqttListTopics(props.connectionId) as Promise<[string, string][]>,
mqttGetTopicTree(props.connectionId) as Promise<MqttTopicNode>,
mqttGetMessages(props.connectionId, selectedTopic.value || undefined, 50) as Promise<MqttMessage[]>,
]);
brokerInfo.value = info;
subscribedTopics.value = topics;
topicTree.value = tree;
messages.value = msgs;
error.value = null;
} catch (e) {
error.value = String(e);
} finally {
loading.value = false;
}
}
async function handleSubscribe(topic: string) {
try {
await mqttSubscribe(props.connectionId, topic, "atmostonce");
await refreshData();
} catch (e) {
error.value = String(e);
}
}
async function handleUnsubscribe(topics: string[]) {
const subscribed = new Set(subscribedTopics.value.map(([topic]) => topic));
const targets = [...new Set(topics)].filter((topic) => subscribed.has(topic));
if (targets.length === 0) {
error.value = t("connection.mqttUnsubscribeMissing");
return;
}
const prompt = targets.length === 1 ? t("connection.mqttUnsubscribeConfirm", { topic: targets[0] }) : t("connection.mqttUnsubscribeGroupConfirm", { count: targets.length });
if (!window.confirm(prompt)) return;
const failures: string[] = [];
for (const topic of targets) {
try {
await mqttUnsubscribe(props.connectionId, topic);
} catch (e) {
failures.push(`${topic}:${String(e)}`);
}
}
if (targets.includes(selectedTopic.value)) selectedTopic.value = "";
await refreshData();
if (failures.length > 0) {
error.value = t("connection.mqttUnsubscribeFailed", { count: failures.length, errors: failures.join("; ") });
}
}
function handleTopicClick(topic: string) {
selectedTopic.value = topic;
refreshData();
}
function handleMessagePublished() {
refreshData();
}
async function handleClearMessages() {
try {
await mqttClearMessages(props.connectionId);
messages.value = [];
} catch (e) {
error.value = String(e);
}
}
/* ========== 消息轮询 ========== */
function startPolling() {
stopPolling();
pollingTimer.value = setInterval(async () => {
try {
const msgs = (await mqttGetMessages(props.connectionId, selectedTopic.value || undefined, 50)) as MqttMessage[];
messages.value = msgs;
} catch {
/* 忽略轮询错误 */
}
}, 3000);
}
function stopPolling() {
if (pollingTimer.value) {
clearInterval(pollingTimer.value);
pollingTimer.value = null;
}
}
/* ========== 格式化消息 Payload ========== */
function formatMessagePayload(msg: MqttMessage): string {
if (displayEncoding.value === "plaintext" && msg.payloadText != null) {
return msg.payloadText;
}
return decodePayload(msg.payloadBase64, displayEncoding.value);
}
/* ========== 生命周期 ========== */
onMounted(async () => {
await refreshData();
startPolling();
});
onUnmounted(() => {
stopPolling();
});
</script>
<template>
<div class="flex flex-col h-full bg-card text-card-foreground">
<!-- Header -->
<div class="flex items-center justify-between px-4 py-2 border-b shrink-0">
<div class="flex items-center gap-3">
<span class="text-lg font-semibold">{{ t("connection.mqttConsoleTitle") }}</span>
<span v-if="brokerInfo" class="text-sm text-muted-foreground">{{ brokerInfo.brokerUrl }}</span>
<span v-if="brokerInfo" class="px-1.5 py-0.5 rounded text-xs font-medium" :class="connected ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'">
{{ connected ? t("connection.mqttConnected") : t("connection.mqttDisconnected") }}
</span>
</div>
<div class="flex items-center gap-2">
<Button size="sm" variant="outline" @click="refreshData">{{ t("connection.mqttRefresh") }}</Button>
<Button size="sm" variant="outline" @click="handleClearMessages">{{ t("connection.mqttClearMessages") }}</Button>
</div>
</div>
<!-- Error banner -->
<div v-if="error" class="px-4 py-2 bg-red-50 dark:bg-red-950/30 text-red-700 dark:text-red-400 text-sm border-b">
{{ error }}
<button class="ml-2 underline" @click="error = null">{{ t("common.close") }}</button>
</div>
<!-- Body: 双栏布局 -->
<div class="flex-1 flex min-h-0">
<!-- 左侧:主题树 -->
<div class="w-72 border-r flex flex-col shrink-0">
<div class="px-3 py-2 text-xs font-semibold text-muted-foreground uppercase border-b">{{ t("connection.mqttTopics") }}</div>
<div class="flex-1 overflow-auto p-2">
<div v-if="loading" class="text-xs text-muted-foreground p-2">{{ t("common.loading") }}</div>
<div v-else-if="!topicTree?.children?.length" class="text-xs text-muted-foreground p-2">{{ t("connection.mqttNoTopicsHint") }}</div>
<TopicTreeNode v-for="child in topicTree?.children ?? []" :key="child.fullPath" :node="child" :depth="0" :selected-topic="selectedTopic" :subscribed-topics="subscribedTopics" @select="handleTopicClick" @subscribe="handleSubscribe" @unsubscribe="handleUnsubscribe" />
</div>
<!-- 快速订阅 -->
<div class="border-t p-2">
<form
class="flex gap-1"
@submit.prevent="
(e) => {
const input = (e.target as HTMLFormElement).querySelector('input');
const topic = input?.value.trim();
if (topic && input) {
handleSubscribe(topic);
input.value = '';
}
}
"
>
<input class="flex-1 h-7 px-2 text-xs rounded border bg-transparent" :placeholder="t('connection.mqttSubscribePlaceholder')" />
<Button size="sm" variant="ghost" class="h-7 text-xs" type="submit">{{ t("connection.mqttSubscribe") }}</Button>
</form>
</div>
</div>
<!-- 右侧:消息列表 + 发布面板 -->
<div class="flex-1 flex flex-col min-w-0">
<!-- 消息区域 -->
<div class="flex-1 flex flex-col min-h-0">
<div class="px-3 py-2 text-xs font-semibold text-muted-foreground uppercase border-b flex items-center justify-between shrink-0">
<span v-if="selectedTopic">{{ t("connection.mqttMessagesForTopic", { topic: selectedTopic }) }}</span>
<span v-else>{{ t("connection.mqttAllMessages") }}</span>
<div class="flex items-center gap-2">
<span class="font-normal">{{ messages.length }}</span>
<!-- Payload 编码格式选择 -->
<select v-model="displayEncoding" class="h-6 px-1.5 text-[11px] rounded border bg-transparent text-muted-foreground cursor-pointer outline-none">
<option v-for="enc in PAYLOAD_ENCODINGS" :key="enc" :value="enc">
{{ PAYLOAD_ENCODING_LABELS[enc] }}
</option>
</select>
</div>
</div>
<div class="flex-1 overflow-auto">
<div v-if="messages.length === 0" class="text-xs text-muted-foreground p-4 text-center">{{ t("connection.mqttNoMessages") }}</div>
<div
v-for="(msg, i) in messages"
:key="i"
class="px-3 py-2 border-b last:border-b-0 cursor-pointer text-xs"
:class="msg.direction === 'sent' ? 'bg-emerald-50/60 dark:bg-emerald-950/20 hover:bg-emerald-100/60 dark:hover:bg-emerald-950/40' : 'hover:bg-muted/50'"
@click="handleTopicClick(msg.topic)"
>
<div class="flex items-center gap-2 mb-0.5">
<span v-if="msg.direction === 'sent'" class="text-emerald-600 dark:text-emerald-400 text-[10px] font-bold shrink-0">{{ t("connection.mqttSent") }}</span>
<span v-else class="text-blue-600 dark:text-blue-400 text-[10px] font-bold shrink-0">{{ t("connection.mqttReceived") }}</span>
<span class="font-mono text-blue-600 dark:text-blue-400 font-medium truncate">{{ msg.topic }}</span>
<span class="text-muted-foreground/60 shrink-0">QoS{{ msg.qos }}</span>
<span v-if="msg.retain" class="text-amber-600 dark:text-amber-400 text-[10px] font-medium shrink-0">{{ t("connection.mqttRetained") }}</span>
</div>
<div class="text-muted-foreground font-mono whitespace-pre-wrap break-all">{{ formatMessagePayload(msg) }}</div>
<div class="text-muted-foreground/50 mt-0.5 text-[10px]">{{ new Date(msg.receivedAtMs).toLocaleTimeString() }}</div>
</div>
</div>
</div>
<!-- 底部:内联发布面板 -->
<MqttPublishPanel v-if="connected" :connection-id="connectionId" :initial-topic="selectedTopic" @published="handleMessagePublished" />
</div>
</div>
</div>
</template>
@@ -0,0 +1,352 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { mqttPublish } from "@/lib/backend/api";
import { Button } from "@/components/ui/button";
import { PAYLOAD_ENCODINGS, PAYLOAD_ENCODING_LABELS, encodePayload, type PayloadEncoding } from "@/lib/mqtt/mqttPayloadCodec";
interface Props {
connectionId: string;
initialTopic?: string;
}
const props = defineProps<Props>();
const emit = defineEmits<{
published: [];
}>();
const { t } = useI18n();
const topic = ref(props.initialTopic || "");
const qos = ref<0 | 1 | 2>(0);
const retain = ref(false);
const payloadText = ref("");
const encoding = ref<PayloadEncoding>("plaintext");
const loading = ref(false);
const error = ref<string | null>(null);
const success = ref(false);
const qosLabels = ["QoS 0", "QoS 1", "QoS 2"];
const qosHints = computed(() => [t("connection.mqttQosAtMostOnce"), t("connection.mqttQosAtLeastOnce"), t("connection.mqttQosExactlyOnce")]);
/* 根据编码格式调整输入提示和占位符 */
const payloadPlaceholder = computed(() => {
switch (encoding.value) {
case "json":
return t("connection.mqttPayloadPlaceholderJson");
case "base64":
return t("connection.mqttPayloadPlaceholderBase64");
case "hex":
return t("connection.mqttPayloadPlaceholderHex");
case "cbor":
case "msgpack":
return t("connection.mqttPayloadPlaceholderStructured", { encoding: encoding.value.toUpperCase() });
default:
return t("connection.mqttPayloadPlaceholderPlaintext");
}
});
/* 监听 topic prop 变化 */
watch(
() => props.initialTopic,
(val) => {
if (val !== undefined && val !== topic.value) {
topic.value = val;
}
},
);
async function publish() {
const publishTopic = topic.value.trim();
if (!publishTopic) {
error.value = t("connection.mqttPublishTopicRequired");
return;
}
if (publishTopic.includes("#") || publishTopic.includes("+")) {
error.value = t("connection.mqttPublishTopicWildcard");
return;
}
loading.value = true;
error.value = null;
success.value = false;
try {
const payloadBase64 = encodePayload(payloadText.value, encoding.value);
await mqttPublish(props.connectionId, {
topic: publishTopic,
payloadBase64,
payloadText: encoding.value === "plaintext" ? payloadText.value : null,
qos: qos.value === 0 ? "atmostonce" : qos.value === 1 ? "atleastonce" : "exactlyonce",
retain: retain.value,
});
success.value = true;
emit("published");
/* 成功后保留表单内容便于连续测试,1.5 秒后清除成功提示 */
setTimeout(() => {
success.value = false;
}, 1500);
} catch (e) {
error.value = String(e);
} finally {
loading.value = false;
}
}
function clearForm() {
topic.value = "";
payloadText.value = "";
qos.value = 0;
retain.value = false;
encoding.value = "plaintext";
error.value = null;
success.value = false;
}
</script>
<template>
<div class="publish-panel">
<div class="panel-header">
<span class="panel-title">{{ t("connection.mqttPublish") }}</span>
<Button size="sm" variant="ghost" class="h-6 text-xs" @click="clearForm">{{ t("common.clear") }}</Button>
</div>
<!-- Topic + QoS + Retain 行 -->
<div class="form-row">
<div class="form-group flex-1">
<label class="form-label">{{ t("connection.mqttTopic") }}</label>
<input v-model="topic" class="form-input font-mono text-xs" :placeholder="t('connection.mqttTopicExample')" @keydown.enter="publish()" />
</div>
</div>
<div class="form-row form-row-wrap">
<!-- QoS -->
<div class="form-group">
<label class="form-label">QoS</label>
<div class="segmented-control">
<button v-for="(label, i) in qosLabels" :key="i" class="segment-item" :class="{ active: qos === i }" :title="qosHints[i]" @click="qos = i as 0 | 1 | 2">
{{ label }}
</button>
</div>
</div>
<!-- Retain -->
<div class="form-group form-group-check">
<label class="form-label">&nbsp;</label>
<label class="checkbox-label">
<input type="checkbox" :checked="retain" @change="retain = !retain" class="form-checkbox" />
<span class="text-xs">{{ t("connection.mqttRetainMessage") }}</span>
</label>
</div>
<!-- 编码格式 -->
<div class="form-group">
<label class="form-label">{{ t("connection.mqttPayloadEncoding") }}</label>
<select v-model="encoding" class="form-select text-xs">
<option v-for="enc in PAYLOAD_ENCODINGS" :key="enc" :value="enc">
{{ PAYLOAD_ENCODING_LABELS[enc] }}
</option>
</select>
</div>
</div>
<!-- Payload -->
<div class="form-group flex-1 flex flex-col min-h-0">
<label class="form-label">{{ t("connection.mqttPayload") }}</label>
<textarea v-model="payloadText" class="form-textarea flex-1 font-mono text-xs" :placeholder="payloadPlaceholder" rows="4" @keydown.ctrl.enter="publish()" />
<span class="form-hint">{{ t("connection.mqttPublishShortcut") }}</span>
</div>
<!-- 状态提示 -->
<div v-if="error" class="publish-error">{{ error }}</div>
<div v-if="success" class="publish-success">✓ {{ t("connection.mqttPublishSuccess") }}</div>
<!-- 操作按钮 -->
<div class="form-actions">
<Button size="sm" class="publish-btn" :disabled="loading || !topic.trim()" @click="publish">
{{ loading ? t("connection.mqttPublishing") : t("connection.mqttPublish") }}
</Button>
</div>
</div>
</template>
<style scoped>
.publish-panel {
display: flex;
flex-direction: column;
gap: 8px;
padding: 10px 12px;
border-top: 1px solid var(--color-border);
background: var(--color-background);
}
.panel-header {
display: flex;
align-items: center;
justify-content: space-between;
}
.panel-title {
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
color: var(--color-text-secondary);
letter-spacing: 0.5px;
}
.form-row {
display: flex;
gap: 8px;
align-items: flex-end;
}
.form-row-wrap {
flex-wrap: wrap;
}
.form-group {
display: flex;
flex-direction: column;
gap: 3px;
}
.form-group-check {
justify-content: flex-end;
}
.form-label {
font-size: 11px;
font-weight: 500;
color: var(--color-text-secondary);
}
.form-input {
height: 28px;
padding: 0 8px;
border: 1px solid var(--color-border);
border-radius: 4px;
background: var(--color-background);
color: var(--color-text);
outline: none;
box-sizing: border-box;
}
.form-input:focus {
border-color: var(--color-primary);
box-shadow: 0 0 0 1px var(--color-primary-alpha);
}
.form-textarea {
padding: 6px 8px;
border: 1px solid var(--color-border);
border-radius: 4px;
background: var(--color-background);
color: var(--color-text);
outline: none;
resize: vertical;
min-height: 60px;
box-sizing: border-box;
line-height: 1.4;
}
.form-textarea:focus {
border-color: var(--color-primary);
box-shadow: 0 0 0 1px var(--color-primary-alpha);
}
.form-select {
height: 28px;
padding: 0 6px;
border: 1px solid var(--color-border);
border-radius: 4px;
background: var(--color-background);
color: var(--color-text);
font-size: 12px;
outline: none;
cursor: pointer;
}
.form-select:focus {
border-color: var(--color-primary);
}
.form-checkbox {
width: 14px;
height: 14px;
cursor: pointer;
accent-color: var(--color-primary);
}
.checkbox-label {
display: flex;
align-items: center;
gap: 4px;
cursor: pointer;
user-select: none;
}
.form-hint {
font-size: 10px;
color: var(--color-text-tertiary);
margin-top: 2px;
}
.segmented-control {
display: flex;
border: 1px solid var(--color-border);
border-radius: 4px;
overflow: hidden;
}
.segment-item {
padding: 2px 10px;
font-size: 11px;
font-weight: 500;
border: none;
background: transparent;
color: var(--color-text-secondary);
cursor: pointer;
transition: all 0.15s;
border-right: 1px solid var(--color-border);
white-space: nowrap;
}
.segment-item:last-child {
border-right: none;
}
.segment-item:hover {
background: var(--color-background-secondary);
}
.segment-item.active {
background: var(--color-primary);
color: white;
}
.publish-error {
font-size: 12px;
color: var(--color-error);
padding: 4px 8px;
background: var(--color-error-bg);
border-radius: 4px;
}
.publish-success {
font-size: 12px;
color: var(--color-success);
padding: 4px 8px;
background: color-mix(in srgb, var(--color-success) 12%, transparent);
border-radius: 4px;
font-weight: 500;
}
.form-actions {
display: flex;
gap: 8px;
}
.publish-btn {
flex: 1;
height: 30px;
font-size: 13px;
font-weight: 500;
}
</style>
@@ -0,0 +1,96 @@
<script setup lang="ts">
import type { MqttTopicNode } from "@/types/mqtt";
import { ChevronRight, ChevronDown, Trash2 } from "@lucide/vue";
import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
interface Props {
node: MqttTopicNode;
depth: number;
selectedTopic: string;
subscribedTopics: [string, string][];
}
const props = defineProps<Props>();
const { t } = useI18n();
const emit = defineEmits<{
select: [topic: string];
subscribe: [topic: string];
unsubscribe: [topics: string[]];
}>();
const expanded = ref(props.depth < 2);
function isSubscribed(topic: string): boolean {
return props.subscribedTopics.some(([t]) => t === topic);
}
function collectSubscribedTopics(node: MqttTopicNode): string[] {
const topics = node.isLeaf && isSubscribed(node.fullPath) ? [node.fullPath] : [];
for (const child of node.children ?? []) {
topics.push(...collectSubscribedTopics(child));
}
return topics;
}
const topicsToUnsubscribe = computed(() => collectSubscribedTopics(props.node));
const unsubscribeLabel = computed(() => (topicsToUnsubscribe.value.length === 1 ? t("connection.mqttUnsubscribeTopic", { topic: topicsToUnsubscribe.value[0] }) : t("connection.mqttUnsubscribeGroup", { count: topicsToUnsubscribe.value.length })));
function toggle() {
expanded.value = !expanded.value;
}
</script>
<template>
<div>
<div
class="flex items-center gap-1 py-0.5 pl-2 pr-1 rounded cursor-pointer text-xs group border-l-2 border-transparent"
:class="selectedTopic === node.fullPath ? 'bg-primary/25 text-foreground font-semibold border-l-primary shadow-sm ring-1 ring-primary/20' : 'hover:bg-muted/70 text-muted-foreground'"
:style="{ paddingLeft: `${depth * 12 + 4}px` }"
@click="node.isLeaf ? emit('select', node.fullPath) : toggle()"
>
<!-- Expand/collapse toggle -->
<button v-if="node.children?.length" class="shrink-0 w-4 h-4 flex items-center justify-center text-muted-foreground" @click.stop="toggle">
<ChevronRight v-if="!expanded" class="h-3 w-3" />
<ChevronDown v-else class="h-3 w-3" />
</button>
<span v-else class="w-4 shrink-0" />
<!-- Topic name -->
<span class="truncate flex-1 font-mono" :class="selectedTopic === node.fullPath ? 'text-primary' : node.isLeaf ? 'font-medium text-blue-600 dark:text-blue-400' : ''">
{{ node.name }}
</span>
<!-- 分组节点可一次取消其下全部订阅 -->
<button
v-if="topicsToUnsubscribe.length"
type="button"
class="flex h-5 w-5 shrink-0 items-center justify-center rounded text-red-500 opacity-0 transition-opacity hover:bg-accent group-hover:opacity-100 focus:opacity-100"
:title="unsubscribeLabel"
:aria-label="unsubscribeLabel"
@click.stop="emit('unsubscribe', topicsToUnsubscribe)"
>
<Trash2 class="h-3 w-3" />
</button>
</div>
<!-- Children -->
<TopicTreeNode
v-if="expanded"
v-for="child in node.children"
:key="child.fullPath"
:node="child"
:depth="depth + 1"
:selected-topic="selectedTopic"
:subscribed-topics="subscribedTopics"
@select="emit('select', $event)"
@subscribe="emit('subscribe', $event)"
@unsubscribe="emit('unsubscribe', $event)"
/>
</div>
</template>
<script lang="ts">
// Recursive component needs explicit name in non-setup script block
export default { name: "TopicTreeNode" };
</script>
@@ -603,6 +603,8 @@ async function toggle() {
await connectionStore.loadMqTenants(node.connectionId);
} else if (config?.db_type === "nacos") {
await connectionStore.loadNacosNamespaces(node.connectionId);
} else if (config?.db_type === "mqtt") {
await connectionStore.loadMqttTopics(node.connectionId);
} else {
await connectionStore.loadDatabases(node.connectionId);
}
@@ -615,6 +617,10 @@ async function toggle() {
} else if (node.type === "mq-tenant" && node.connectionId) {
await connectionStore.ensureConnected(node.connectionId);
queryStore.openMqAdmin(node.connectionId, { tenant: node.mqTenant || node.label, initialTab: node.mqInitialTab });
} else if (node.type === "mqtt-topic" && node.connectionId) {
await connectionStore.ensureConnected(node.connectionId);
const topicFromId = node.id.endsWith(":mqtt-topic:__console__") ? undefined : node.id.split(":mqtt-topic:")[1] || node.label;
queryStore.openMqttAdmin(node.connectionId, topicFromId ? { initialTopic: topicFromId } : undefined);
} else if (node.type === "nacos-namespace" && node.connectionId) {
await connectionStore.ensureConnected(node.connectionId);
queryStore.openNacosAdmin(node.connectionId, { namespace: node.nacosNamespace || "", namespaceName: node.nacosNamespaceName || node.label });