fix: 修正 dashboard charts legend 間隔
This commit is contained in:
parent
aa7a136937
commit
2bf5f9042a
5
src/apis/rtsp/api.js
Normal file
5
src/apis/rtsp/api.js
Normal file
@ -0,0 +1,5 @@
|
||||
// 開關 RTSP(啟用/停用)
|
||||
export const POST_SET_RTSP_ENABLE = `/api/rtsp/set-rtsp-enable`;
|
||||
|
||||
// 設定 SAMBA 儲存目錄
|
||||
export const POST_SET_SAMBA_DIRECTORY = `/api/rtsp/set-samba-directory`;
|
29
src/apis/rtsp/index.js
Normal file
29
src/apis/rtsp/index.js
Normal file
@ -0,0 +1,29 @@
|
||||
import {
|
||||
POST_SET_RTSP_ENABLE,
|
||||
POST_SET_SAMBA_DIRECTORY,
|
||||
} from "./api";
|
||||
import instance from "@/util/request";
|
||||
import apihandler from "@/util/apihandler";
|
||||
|
||||
/**
|
||||
* 開關 RTSP
|
||||
* Swagger: POST /api/rtsp/set-rtsp-enable
|
||||
* body: { main_id: number, enable: boolean }
|
||||
*/
|
||||
export const setRtspEnable = async ({ main_id, enable }) => {
|
||||
const res = await instance.post(POST_SET_RTSP_ENABLE, { main_id, enable });
|
||||
return apihandler(res.code, res.data, { msg: res.msg, code: res.code });
|
||||
};
|
||||
|
||||
/**
|
||||
* 設定 SAMBA 儲存目錄
|
||||
* Swagger: POST /api/rtsp/set-samba-directory
|
||||
* body: { main_id: number, directory: string }
|
||||
*/
|
||||
export const setSambaDirectory = async ({ main_id, directory }) => {
|
||||
const res = await instance.post(POST_SET_SAMBA_DIRECTORY, {
|
||||
main_id,
|
||||
directory,
|
||||
});
|
||||
return apihandler(res.code, res.data, { msg: res.msg, code: res.code });
|
||||
};
|
@ -426,7 +426,16 @@
|
||||
"title": "影像串流",
|
||||
"start": "开始侦测",
|
||||
"stop": "结束侦测",
|
||||
"selectPath": "选择保存路径",
|
||||
"displayArea": "RTSP 画面显示区域"
|
||||
"selectPath": "选择存储位置",
|
||||
"selectDevice": "选择设备",
|
||||
"pleaseSelectDevice": "请先选择设备",
|
||||
"selectPathFirst": "请先选择存储文件夹",
|
||||
"startSuccess": "已开始侦测…",
|
||||
"startFail": "开始侦测失败,请稍后再试",
|
||||
"stopSuccess": "已请求结束侦测…",
|
||||
"stopFail": "结束侦测失败,请稍后再试",
|
||||
"noPermission": "未获得写入权限,请重新选择文件夹并授权",
|
||||
"selectFolderSuccess": "已选择文件夹:{name}",
|
||||
"selectFolderFail": "选择文件夹失败,请再试一次"
|
||||
}
|
||||
}
|
||||
|
@ -427,6 +427,15 @@
|
||||
"start": "開始偵測",
|
||||
"stop": "結束偵測",
|
||||
"selectPath": "選擇儲存位置",
|
||||
"displayArea": "RTSP 畫面顯示區域"
|
||||
"selectDevice": "選擇設備",
|
||||
"pleaseSelectDevice": "請先選擇設備",
|
||||
"selectPathFirst": "請先選擇儲存資料夾",
|
||||
"startSuccess": "已開始偵測…",
|
||||
"startFail": "開始偵測失敗,請稍後再試",
|
||||
"stopSuccess": "已請求結束偵測…",
|
||||
"stopFail": "結束偵測失敗,請稍後再試",
|
||||
"noPermission": "沒有取得寫入權限,請重新選擇資料夾並允許",
|
||||
"selectFolderSuccess": "已選擇資料夾:{name}",
|
||||
"selectFolderFail": "選擇資料夾失敗,請再試一次"
|
||||
}
|
||||
}
|
||||
|
@ -423,10 +423,19 @@
|
||||
"json_click_text": "Please enter JSON on the left and click the conversion button"
|
||||
},
|
||||
"rtsp": {
|
||||
"title": "Media Streaming",
|
||||
"title": "Video Stream",
|
||||
"start": "Start Detection",
|
||||
"stop": "Stop Detection",
|
||||
"selectPath": "Select Save Path",
|
||||
"displayArea": "RTSP Display Area"
|
||||
"selectPath": "Select Folder",
|
||||
"selectDevice": "Select Device",
|
||||
"pleaseSelectDevice": "Please select a device first",
|
||||
"selectPathFirst": "Please select a folder first",
|
||||
"startSuccess": "Detection started…",
|
||||
"startFail": "Failed to start detection, please try again later",
|
||||
"stopSuccess": "Detection stop requested…",
|
||||
"stopFail": "Failed to stop detection, please try again later",
|
||||
"noPermission": "No write permission. Please select a folder again and grant access",
|
||||
"selectFolderSuccess": "Folder selected: {name}",
|
||||
"selectFolderFail": "Failed to select folder, please try again"
|
||||
}
|
||||
}
|
||||
|
@ -136,20 +136,14 @@ onUnmounted(() => {
|
||||
<template>
|
||||
<div class="flex flex-wrap justify-between">
|
||||
<div
|
||||
class="order-3 lg:order-1 w-full lg:w-1/4 min-h-screen flex flex-col justify-start z-10 border-dashboard gap-5"
|
||||
class="order-3 lg:order-1 w-full lg:w-1/4 min-h-screen flex flex-col justify-start item-center z-10 border-dashboard gap-12"
|
||||
>
|
||||
<!-- 無資料時:完整隱藏區塊,不留空白 -->
|
||||
|
||||
<!-- <DashboardProduct
|
||||
@visible-change="(v) => (productVisible = v)"
|
||||
v-show="productVisible"
|
||||
/>
|
||||
<DashboardProductComplete
|
||||
@visible-change="(v) => (productCompleteVisible = v)"
|
||||
v-show="productVisible"
|
||||
/> -->
|
||||
<DashboardIndoor />
|
||||
<DashboardRefrig class="mb-10" />
|
||||
<div class="flex flex-col gap-5">
|
||||
<DashboardIndoor />
|
||||
</div>
|
||||
<div class="flex flex-col gap-5">
|
||||
<DashboardRefrig />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
@ -158,19 +152,19 @@ onUnmounted(() => {
|
||||
<DashboardFloorBar />
|
||||
<DashboardEffectScatter :data="systemData" />
|
||||
</div>
|
||||
<div class="order-2 w-full lg:hidden my-3">
|
||||
<!-- <div class="order-2 w-full lg:hidden my-3">
|
||||
<DashboardSysCard :data="systemData" />
|
||||
</div>
|
||||
</div> -->
|
||||
<div
|
||||
class="order-last w-full lg:w-1/4 flex flex-col justify-start border-dashboard z-20 gap-5"
|
||||
class="order-last w-full lg:w-1/4 flex flex-col justify-start border-dashboard z-20 gap-12"
|
||||
>
|
||||
<div>
|
||||
<div class="flex flex-col gap-5">
|
||||
<DashboardElectricity />
|
||||
</div>
|
||||
<div class="mt-10">
|
||||
<div class="flex flex-col gap-5">
|
||||
<DashboardEmission />
|
||||
</div>
|
||||
<div class="mt-10">
|
||||
<div class="flex flex-col gap-5">
|
||||
<DashboardAlert />
|
||||
</div>
|
||||
</div>
|
||||
|
@ -50,10 +50,11 @@ const defaultChartOption = ref({
|
||||
tooltip: { trigger: "axis" },
|
||||
legend: {
|
||||
data: [],
|
||||
textStyle: { color: "#ffffff", fontSize: 16 },
|
||||
top: 0, // 靠最上方
|
||||
textStyle: { color: "#ffffff", fontSize: 12 },
|
||||
},
|
||||
grid: {
|
||||
top: "10%",
|
||||
top: "35%",
|
||||
left: "0%",
|
||||
right: "0%",
|
||||
bottom: "0%",
|
||||
@ -203,7 +204,7 @@ onUnmounted(() => {
|
||||
<h3 class="text-info text-xl text-center">
|
||||
{{ $t("dashboard.indoor_chart") }}
|
||||
</h3>
|
||||
<div className="my-3 w-full flex justify-center relative">
|
||||
<div class="w-full flex justify-center items-center relative">
|
||||
<ButtonConnectedGroup
|
||||
:items="items"
|
||||
:onclick="(e, item) => changeActiveBtn(item)"
|
||||
|
@ -1,150 +1,61 @@
|
||||
<script setup>
|
||||
import LineChart from "@/components/chart/LineChart.vue";
|
||||
import { SECOND_CHART_COLOR } from "@/constant";
|
||||
import { ref, watch, computed, onUnmounted } from "vue";
|
||||
import dayjs from "dayjs";
|
||||
import { ref, watch, onUnmounted, computed } from "vue";
|
||||
import useActiveBtn from "@/hooks/useActiveBtn";
|
||||
import { getDashboardTemp } from "@/apis/dashboard";
|
||||
import useSearchParams from "@/hooks/useSearchParam";
|
||||
import useBuildingStore from "@/stores/useBuildingStore";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
const { searchParams } = useSearchParams();
|
||||
const buildingStore = useBuildingStore();
|
||||
const allTempData = ref([]);
|
||||
const timeoutTimer = ref(null); // 定時器
|
||||
|
||||
// 狀態與按鈕邏輯
|
||||
const timeoutTimer = ref(null);
|
||||
const { items, changeActiveBtn, setItems, selectedBtn } = useActiveBtn();
|
||||
const currentOptionType = ref(1); // 1: 溫度, 2: 濕度
|
||||
const noData = ref(true); // 目前顯示「無資料」
|
||||
|
||||
// 確認是否有資料,無則不呼叫 getDashboardTemp 也不顯示 chart
|
||||
const allTempData = ref([]);
|
||||
const currentOptionType = ref(1); // 1 = 溫度,2 = 濕度
|
||||
const noData = ref(true); // 初始先視為無資料,等 API 後再更新
|
||||
const chartRef = ref(null);
|
||||
|
||||
// 監聽建築切換:依 sysConfig 決定是否顯示/取數據
|
||||
watch(
|
||||
() => buildingStore.selectedBuilding?.building_guid,
|
||||
async (guid) => {
|
||||
if (guid) {
|
||||
await buildingStore.getSysConfig(guid);
|
||||
if (timeoutTimer.value) clearInterval(timeoutTimer.value);
|
||||
allTempData.value = [];
|
||||
noData.value = true;
|
||||
if (!guid) return;
|
||||
|
||||
const showRefrigeration =
|
||||
buildingStore.sysConfig?.value?.show_refrigeration;
|
||||
await buildingStore.getSysConfig(guid);
|
||||
const showRefrigeration =
|
||||
buildingStore.sysConfig?.value?.show_refrigeration;
|
||||
|
||||
if (showRefrigeration === false) {
|
||||
noData.value = true; // 不顯示圖表
|
||||
return; // 不呼叫 getData
|
||||
}
|
||||
|
||||
noData.value = false; // 有資料才進行呼叫
|
||||
getData();
|
||||
timeoutTimer.value = setInterval(getData, 60000); // 每分鐘叫一次
|
||||
if (showRefrigeration === false) {
|
||||
noData.value = true; // 不顯示
|
||||
return;
|
||||
}
|
||||
|
||||
noData.value = false; // 顯示並開始取資料
|
||||
await getData();
|
||||
timeoutTimer.value = setInterval(getData, 60_000); // 每分鐘更新
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
// 新增 API 資料取得函式
|
||||
const getData = async () => {
|
||||
const buildingGuid = buildingStore.selectedBuilding?.building_guid;
|
||||
if (!buildingGuid) return;
|
||||
|
||||
try {
|
||||
const res = await getDashboardTemp({
|
||||
building_guid: buildingGuid,
|
||||
tempOption: 2, // 冷藏區域(室溫為 tempOption: 1)
|
||||
timeInterval: 1,
|
||||
option: currentOptionType.value, // 1: 溫度,2: 濕度
|
||||
});
|
||||
|
||||
const key = "冷藏"; // 根據實際後端回傳 key
|
||||
allTempData.value = res.isSuccess ? res.data?.[key] ?? [] : [];
|
||||
noData.value = allTempData.value.length === 0;
|
||||
} catch (e) {
|
||||
console.error("getDashboardTemp error", e);
|
||||
allTempData.value = [];
|
||||
noData.value = true;
|
||||
}
|
||||
};
|
||||
|
||||
// 資料更新 watch
|
||||
watch(
|
||||
allTempData,
|
||||
(newVal) => {
|
||||
if (!newVal?.length || !other_real_temp_chart.value?.chart) return;
|
||||
|
||||
const firstValid = newVal.find((d) => d.data?.length);
|
||||
if (!firstValid) return;
|
||||
|
||||
const sampledXAxis = sampleData(firstValid.data).map(({ time }) =>
|
||||
dayjs(time).format("HH:mm:ss")
|
||||
);
|
||||
|
||||
const allValues = newVal
|
||||
.flatMap((d) => sampleData(d.data))
|
||||
.map((d) => d.value)
|
||||
.filter((v) => v != null);
|
||||
|
||||
if (!allValues.length) return;
|
||||
|
||||
const yMin = Math.floor(Math.min(...allValues)) - 1;
|
||||
const yMax = Math.ceil(Math.max(...allValues)) + 1;
|
||||
|
||||
other_real_temp_chart.value.chart.setOption({
|
||||
legend: {
|
||||
data: newVal.map((d) => d.full_name),
|
||||
},
|
||||
xAxis: {
|
||||
data: sampledXAxis,
|
||||
},
|
||||
yAxis: {
|
||||
min: yMin,
|
||||
max: yMax,
|
||||
},
|
||||
series: newVal.map((d, i) => ({
|
||||
name: d.full_name,
|
||||
type: "line",
|
||||
data: sampleData(d.data).map(({ value }) => value),
|
||||
showSymbol: false,
|
||||
itemStyle: {
|
||||
color: SECOND_CHART_COLOR[i % SECOND_CHART_COLOR.length],
|
||||
},
|
||||
})),
|
||||
});
|
||||
},
|
||||
{ deep: true }
|
||||
);
|
||||
|
||||
// 限制顯示資料點數
|
||||
function sampleData(data = [], maxCount = 30) {
|
||||
const len = data.length;
|
||||
if (len <= maxCount) return data;
|
||||
|
||||
const sampled = [];
|
||||
const step = (len - 1) / (maxCount - 1);
|
||||
|
||||
for (let i = 0; i < maxCount; i++) {
|
||||
const index = Math.round(i * step);
|
||||
sampled.push(data[index]);
|
||||
}
|
||||
|
||||
return sampled;
|
||||
}
|
||||
|
||||
// 圖表參數預設(暫不使用)
|
||||
const other_real_temp_chart = ref(null);
|
||||
// 預設圖表設定
|
||||
const defaultChartOption = ref({
|
||||
tooltip: {
|
||||
trigger: "axis",
|
||||
},
|
||||
tooltip: { trigger: "axis" },
|
||||
legend: {
|
||||
data: [],
|
||||
textStyle: {
|
||||
color: "#ffffff",
|
||||
fontSize: 16,
|
||||
},
|
||||
top: 0, // 靠最上方
|
||||
textStyle: { color: "#ffffff", fontSize: 12 },
|
||||
},
|
||||
grid: {
|
||||
top: "10%",
|
||||
top: "35%",
|
||||
left: "0%",
|
||||
right: "0%",
|
||||
bottom: "0%",
|
||||
@ -164,40 +75,129 @@ const defaultChartOption = ref({
|
||||
series: [],
|
||||
});
|
||||
|
||||
// 按鈕名稱根據語系更新
|
||||
// 取得冷藏溫度/濕度資料
|
||||
const getData = async () => {
|
||||
const buildingGuid = buildingStore.selectedBuilding?.building_guid;
|
||||
if (!buildingGuid) return;
|
||||
|
||||
try {
|
||||
const res = await getDashboardTemp({
|
||||
building_guid: buildingGuid,
|
||||
tempOption: 2, // ⚠️ 冷藏區域
|
||||
timeInterval: 1,
|
||||
option: currentOptionType.value, // 1: 溫度;2: 濕度
|
||||
});
|
||||
|
||||
console.log("[getDashboardTemp] 冷藏回傳:", res);
|
||||
|
||||
const key = "冷藏溫度"; // 依你剛剛確認到的 key
|
||||
allTempData.value = res.isSuccess ? res.data?.[key] ?? [] : [];
|
||||
noData.value = allTempData.value.length === 0;
|
||||
|
||||
console.log("[getDashboardTemp] allTempData:", allTempData.value);
|
||||
console.log("[getDashboardTemp] noData:", noData.value);
|
||||
} catch (e) {
|
||||
console.error("getDashboardTemp error", e);
|
||||
allTempData.value = [];
|
||||
noData.value = true;
|
||||
}
|
||||
};
|
||||
|
||||
// 溫度/濕度切換按鈕
|
||||
const buttonItems = computed(() => [
|
||||
{ key: 1, title: t("dashboard.temperature"), active: true },
|
||||
{ key: 2, title: t("dashboard.humidity"), active: false },
|
||||
]);
|
||||
|
||||
// 語系切換時更新按鈕文案
|
||||
watch(
|
||||
() => locale.value,
|
||||
() => {
|
||||
setItems(buttonItems.value);
|
||||
},
|
||||
() => setItems(buttonItems.value),
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
// 切換 tab(目前無實際資料行為)
|
||||
// 切換溫度/濕度後重取資料並重啟輪詢
|
||||
watch(
|
||||
selectedBtn,
|
||||
(newValue) => {
|
||||
if (timeoutTimer.value) {
|
||||
clearInterval(timeoutTimer.value);
|
||||
}
|
||||
async (newVal) => {
|
||||
if ([1, 2].includes(newVal?.key)) {
|
||||
currentOptionType.value = newVal.key;
|
||||
|
||||
if ([1, 2].includes(newValue?.key)) {
|
||||
currentOptionType.value = newValue.key;
|
||||
if (buildingStore.sysConfig?.value?.show_refrigeration !== false) {
|
||||
if (timeoutTimer.value) clearInterval(timeoutTimer.value);
|
||||
await getData();
|
||||
timeoutTimer.value = setInterval(getData, 60_000);
|
||||
}
|
||||
}
|
||||
},
|
||||
{ immediate: true, deep: true }
|
||||
);
|
||||
|
||||
// 清除計時器
|
||||
onUnmounted(() => {
|
||||
if (timeoutTimer.value) {
|
||||
clearInterval(timeoutTimer.value);
|
||||
// 限制顯示資料點數
|
||||
function sampleData(data = [], maxCount = 30) {
|
||||
const len = data.length;
|
||||
if (len <= maxCount) return data;
|
||||
|
||||
const sampled = [];
|
||||
const step = (len - 1) / (maxCount - 1);
|
||||
for (let i = 0; i < maxCount; i++) {
|
||||
const index = Math.round(i * step);
|
||||
sampled.push(data[index]);
|
||||
}
|
||||
return sampled;
|
||||
}
|
||||
|
||||
// 更新圖表
|
||||
watch(
|
||||
allTempData,
|
||||
(newVal) => {
|
||||
const chart = chartRef.value?.chart;
|
||||
if (!chart || !Array.isArray(newVal) || newVal.length === 0) return;
|
||||
|
||||
const firstValid = newVal.find(
|
||||
(d) => Array.isArray(d.data) && d.data.length
|
||||
);
|
||||
if (!firstValid) return;
|
||||
|
||||
const sampledXAxis = sampleData(firstValid.data).map(({ time }) =>
|
||||
dayjs(time).format("HH:mm:ss")
|
||||
);
|
||||
|
||||
const allValues = newVal
|
||||
.flatMap((d) => sampleData(d.data))
|
||||
.map((d) => d?.value)
|
||||
.filter((v) => typeof v === "number" && !Number.isNaN(v));
|
||||
|
||||
if (!allValues.length) return;
|
||||
|
||||
let yMin = Math.floor(Math.min(...allValues)) - 1;
|
||||
let yMax = Math.ceil(Math.max(...allValues)) + 1;
|
||||
if (yMin === yMax) {
|
||||
yMin -= 1;
|
||||
yMax += 1;
|
||||
}
|
||||
|
||||
chart.setOption({
|
||||
legend: { data: newVal.map((d) => d.full_name) },
|
||||
xAxis: { data: sampledXAxis },
|
||||
yAxis: { min: yMin, max: yMax },
|
||||
series: newVal.map((d, i) => ({
|
||||
name: d.full_name,
|
||||
type: "line",
|
||||
data: sampleData(d.data).map(({ value }) => value),
|
||||
showSymbol: false,
|
||||
itemStyle: {
|
||||
color: SECOND_CHART_COLOR[i % SECOND_CHART_COLOR.length],
|
||||
},
|
||||
})),
|
||||
});
|
||||
},
|
||||
{ deep: true }
|
||||
);
|
||||
|
||||
// 離開元件時清除定時器
|
||||
onUnmounted(() => {
|
||||
if (timeoutTimer.value) clearInterval(timeoutTimer.value);
|
||||
});
|
||||
</script>
|
||||
|
||||
@ -205,24 +205,27 @@ onUnmounted(() => {
|
||||
<h3 class="text-info text-xl text-center">
|
||||
{{ $t("dashboard.refrig_chart") }}
|
||||
</h3>
|
||||
<div className="my-3 w-full flex justify-center relative">
|
||||
|
||||
<div class="w-full flex justify-center relative">
|
||||
<ButtonConnectedGroup
|
||||
:items="items"
|
||||
:onclick="(e, item) => changeActiveBtn(item)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="noData"
|
||||
class="text-center text-white text-lg min-h-[260px] flex items-center justify-center"
|
||||
>
|
||||
{{ $t("dashboard.no_data") }}
|
||||
</div>
|
||||
|
||||
<LineChart
|
||||
v-if="!noData"
|
||||
id="dashboard_other_real_temp"
|
||||
v-else
|
||||
id="dashboard_refrigeration_temp"
|
||||
class="min-h-[260px] max-h-fit"
|
||||
:option="defaultChartOption"
|
||||
ref="indoorChartRef"
|
||||
ref="chartRef"
|
||||
/>
|
||||
</template>
|
||||
|
||||
|
@ -2,9 +2,33 @@
|
||||
<section class="min-h-[600px] h-screen">
|
||||
<h1 class="text-2xl font-extrabold mb-2">{{ $t("rtsp.title") }}</h1>
|
||||
|
||||
<div class="flex h-[80%] gap-4">
|
||||
<!-- 左側:即時監控(自動填滿容器) -->
|
||||
<!-- Tabs:選擇要顯示的攝影機 -->
|
||||
<div class="flex items-center gap-4 mb-6">
|
||||
<h2 class="text-lg font-bold whitespace-nowrap">
|
||||
{{ $t("rtsp.selectDevice") }} :
|
||||
</h2>
|
||||
|
||||
<ButtonConnectedGroup
|
||||
:items="items"
|
||||
:onclick="
|
||||
(e, item) => {
|
||||
changeActiveBtn(item);
|
||||
const found = rtspDevices.find((r) => r.main_id === item.key);
|
||||
if (found) selectDevice(found);
|
||||
}
|
||||
"
|
||||
:className="`flex flex-wrap`"
|
||||
size="sm"
|
||||
color="info"
|
||||
>
|
||||
<template #buttonContent="{ item }">
|
||||
<span class="text-base">{{ item.title }}</span>
|
||||
</template>
|
||||
</ButtonConnectedGroup>
|
||||
</div>
|
||||
|
||||
<div class="flex h-[70%] gap-4">
|
||||
<!-- 左側:即時監控 -->
|
||||
<div class="relative w-full flex-1 rounded border overflow-hidden">
|
||||
<iframe
|
||||
:src="monitorUrl"
|
||||
@ -14,225 +38,239 @@
|
||||
></iframe>
|
||||
</div>
|
||||
|
||||
<!-- 右側:開始/結束偵測 + 選擇儲存位置 + 下載進度 -->
|
||||
<!-- 右側:開始/結束偵測(已移除選擇資料夾相關 UI) -->
|
||||
<aside class="w-1/2 flex flex-col gap-6 p-4">
|
||||
<div class="flex gap-3">
|
||||
<button
|
||||
class="btn btn-add w-40"
|
||||
@click="startDetection"
|
||||
:disabled="isStarting || !dirHandle"
|
||||
:title="!dirHandle ? '請先選擇儲存資料夾' : ''"
|
||||
:disabled="isStarting || !selectedMainId"
|
||||
:title="!selectedMainId ? $t('rtsp.pleaseSelectDevice') : ''"
|
||||
>
|
||||
{{ $t("rtsp.start") }}
|
||||
</button>
|
||||
<button
|
||||
class="btn btn-error text-white w-40"
|
||||
@click="stopDetection"
|
||||
:disabled="isStopping"
|
||||
:disabled="isStopping || !selectedMainId"
|
||||
:title="!selectedMainId ? $t('rtsp.pleaseSelectDevice') : ''"
|
||||
>
|
||||
{{ $t("rtsp.stop") }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 選擇儲存資料夾 -->
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex gap-4">
|
||||
<button class="btn btn-neutral" @click="pickDirectory">
|
||||
{{ $t("rtsp.selectPath") }}
|
||||
</button>
|
||||
<input
|
||||
type="text"
|
||||
:value="directoryName || '尚未選擇資料夾'"
|
||||
readonly
|
||||
class="border border-gray-300 rounded px-3 py-2 flex-1"
|
||||
/>
|
||||
</div>
|
||||
<p v-if="!dirHandle" class="text-sm text-red-400">
|
||||
請先選擇儲存資料夾。
|
||||
</p>
|
||||
|
||||
<!-- 下載進度 -->
|
||||
<div
|
||||
v-if="downloadProgress > 0 && downloadProgress < 100"
|
||||
class="mt-2"
|
||||
>
|
||||
<div class="text-sm text-gray-600 mb-1">
|
||||
下載中… {{ Math.floor(downloadProgress) }}%
|
||||
</div>
|
||||
<progress
|
||||
class="progress w-full"
|
||||
:value="downloadProgress"
|
||||
max="100"
|
||||
></progress>
|
||||
</div>
|
||||
|
||||
<p v-if="message" class="text-sm text-gray-700">{{ message }}</p>
|
||||
</div>
|
||||
<p v-if="message" class="text-sm text-info">{{ message }}</p>
|
||||
</aside>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import axios from "axios";
|
||||
import { getSystemDevices } from "@/apis/system";
|
||||
import { setRtspEnable } from "@/apis/rtsp"; // 已移除 setSambaDirectory
|
||||
import useActiveBtn from "@/hooks/useActiveBtn";
|
||||
|
||||
const FILE_BASEURL = import.meta.env.VITE_FILE_API_BASEURL;
|
||||
const DEFAULT_MONITOR_URL =
|
||||
"http://192.168.0.219:8026/?url=rtsp://admin02:mjmAdmin_99@192.168.0.200:554/stream1?tcp";
|
||||
|
||||
export default {
|
||||
name: "Rtsp",
|
||||
setup() {
|
||||
const { items, changeActiveBtn, setItems, selectedBtn } = useActiveBtn();
|
||||
return { items, changeActiveBtn, setItems, selectedBtn };
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
// 即時監控(RTSP 轉播)頁面
|
||||
monitorUrl:
|
||||
"http://192.168.0.219:8026/?url=rtsp://admin02:mjmAdmin_99@192.168.0.200:554/stream1?tcp",
|
||||
monitorUrl: DEFAULT_MONITOR_URL,
|
||||
|
||||
// 儲存位置
|
||||
dirHandle: /** @type {FileSystemDirectoryHandle|null} */ (null),
|
||||
directoryName: "",
|
||||
|
||||
// 錄製控制
|
||||
ws: null,
|
||||
// 偵測控制
|
||||
isStarting: false,
|
||||
isStopping: false,
|
||||
|
||||
// 下載狀態
|
||||
downloadProgress: 0,
|
||||
// UI 狀態
|
||||
message: "",
|
||||
|
||||
// 資料整理
|
||||
deviceData: {},
|
||||
rtspDevices: [], // { main_id, full_name, rtsp_url, ... }
|
||||
selectedMainId: null, // 目前選中的設備 main_id
|
||||
};
|
||||
},
|
||||
mounted() {
|
||||
this.connectWS();
|
||||
async mounted() {
|
||||
await this.getData();
|
||||
},
|
||||
beforeUnmount() {
|
||||
if (this.ws) this.ws.close();
|
||||
watch: {
|
||||
selectedBtn: {
|
||||
handler(newVal) {
|
||||
if (!newVal) return;
|
||||
const found = this.rtspDevices.find((r) => r.main_id === newVal.key);
|
||||
if (found) this.selectDevice(found);
|
||||
},
|
||||
deep: true,
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
// WebSocket:等待後端通知偵測結束 → 下載檔案
|
||||
connectWS() {
|
||||
const WS_URL =
|
||||
location.protocol === "https:"
|
||||
? `wss://${location.host}/ws`
|
||||
: `ws://${location.host}/ws`;
|
||||
|
||||
this.ws = new WebSocket(WS_URL);
|
||||
this.ws.onmessage = async (evt) => {
|
||||
try {
|
||||
const payload = JSON.parse(evt.data);
|
||||
if (payload.type === "detection_end") {
|
||||
this.message = "偵測結束,開始下載…";
|
||||
await this.downloadAndSave(payload.filename);
|
||||
}
|
||||
} catch (_) {
|
||||
// 非 JSON 訊息忽略
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
// 使用者選擇儲存資料夾
|
||||
async pickDirectory() {
|
||||
if (!window.showDirectoryPicker) return;
|
||||
async getData() {
|
||||
try {
|
||||
this.dirHandle = await window.showDirectoryPicker();
|
||||
this.directoryName = this.dirHandle.name;
|
||||
const useBuildingStore = (await import("@/stores/useBuildingStore"))
|
||||
.default;
|
||||
const buildingStore = useBuildingStore();
|
||||
const building_guid =
|
||||
buildingStore?.selectedBuilding?.building_guid || "";
|
||||
|
||||
// 申請寫入權限
|
||||
const perm = await this.dirHandle.queryPermission({
|
||||
mode: "readwrite",
|
||||
});
|
||||
if (perm !== "granted") {
|
||||
const req = await this.dirHandle.requestPermission({
|
||||
mode: "readwrite",
|
||||
});
|
||||
if (req !== "granted") {
|
||||
this.dirHandle = null;
|
||||
this.directoryName = "";
|
||||
const res = await getSystemDevices({ building_guid });
|
||||
const transformedData = {};
|
||||
|
||||
(res?.data || []).forEach((floor) => {
|
||||
if (floor?.device_list?.length > 0) {
|
||||
const fullUrl = floor.floor_map_name;
|
||||
const uuid = fullUrl ? fullUrl.replace(/\.svg$/, "") : "";
|
||||
transformedData[uuid] = floor.device_list.map((device) => {
|
||||
let x = 0,
|
||||
y = 0;
|
||||
try {
|
||||
const coordinates = JSON.parse(
|
||||
device?.device_coordinate || "[0,0]"
|
||||
);
|
||||
x = Number(coordinates?.[0] ?? 0);
|
||||
y = Number(coordinates?.[1] ?? 0);
|
||||
} catch (_) {}
|
||||
|
||||
let state = "Online";
|
||||
let bgColor = device?.device_normal_color;
|
||||
if (
|
||||
device?.device_status === "Offline" ||
|
||||
device?.device_status == null
|
||||
) {
|
||||
state = "Offline";
|
||||
bgColor = device?.device_close_color;
|
||||
}
|
||||
if (device?.device_status === "Error") {
|
||||
state = "Error";
|
||||
bgColor = device?.device_error_color;
|
||||
}
|
||||
|
||||
return [
|
||||
x,
|
||||
y,
|
||||
{
|
||||
device_number: device?.device_number || "",
|
||||
device_coordinate: device?.device_coordinate || "",
|
||||
device_image_url: device?.device_image_url,
|
||||
full_name: device?.full_name,
|
||||
main_id: device?.main_id,
|
||||
points: device?.points || [],
|
||||
floor: floor?.full_name,
|
||||
state,
|
||||
icon: device?.device_image
|
||||
? `${FILE_BASEURL}/upload/device_icon/${device.device_image}`
|
||||
: "",
|
||||
bgColor,
|
||||
Online_color: device?.device_normal_color,
|
||||
Offline_color: device?.device_close_color,
|
||||
Error_color: device?.device_error_color,
|
||||
brand: device?.brand || "",
|
||||
device_model: device?.device_model,
|
||||
operation_name: device?.operation_name,
|
||||
operation_contact_person: device?.operation_contact_person,
|
||||
buying_date: device?.buying_date,
|
||||
created_at: device?.created_at,
|
||||
bgSize: 50,
|
||||
is_rtsp: device?.is_rtsp === true,
|
||||
rtsp_url: device?.rtsp_url || "",
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
this.deviceData = transformedData;
|
||||
|
||||
const allRows = Object.values(transformedData).flat();
|
||||
this.rtspDevices = allRows
|
||||
.map((row) => row?.[2])
|
||||
.filter((p) => p && p.is_rtsp && p.rtsp_url)
|
||||
.reduce((acc, cur) => {
|
||||
if (!acc.find((x) => x.main_id === cur.main_id)) acc.push(cur);
|
||||
return acc;
|
||||
}, [])
|
||||
.sort((a, b) => (a.full_name || "").localeCompare(b.full_name || ""));
|
||||
|
||||
const cate = this.rtspDevices.map((d, index) => ({
|
||||
title: d.full_name || d.main_id,
|
||||
key: d.main_id,
|
||||
active: this.selectedMainId
|
||||
? this.selectedMainId === d.main_id
|
||||
: index === 0,
|
||||
...d,
|
||||
}));
|
||||
this.setItems(cate);
|
||||
|
||||
if (this.rtspDevices.length > 0) {
|
||||
const first = this.rtspDevices[0];
|
||||
this.selectedMainId = first.main_id;
|
||||
this.monitorUrl = first.rtsp_url;
|
||||
} else {
|
||||
this.selectedMainId = null;
|
||||
this.monitorUrl = DEFAULT_MONITOR_URL;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("選擇資料夾失敗", err);
|
||||
console.error("getData() 失敗", err);
|
||||
this.setItems([]);
|
||||
this.rtspDevices = [];
|
||||
this.selectedMainId = null;
|
||||
this.monitorUrl = DEFAULT_MONITOR_URL;
|
||||
}
|
||||
},
|
||||
|
||||
// 開始/結束偵測(觸發後端錄製流程)
|
||||
// 切換設備 Tab
|
||||
selectDevice(d) {
|
||||
this.selectedMainId = d.main_id;
|
||||
this.monitorUrl = d.rtsp_url || DEFAULT_MONITOR_URL;
|
||||
},
|
||||
|
||||
// 開始偵測:setRtspEnable(true)
|
||||
async startDetection() {
|
||||
if (!this.dirHandle) {
|
||||
this.message = "請先選擇儲存資料夾後再開始錄製";
|
||||
if (!this.selectedMainId) {
|
||||
this.message = this.$t("rtsp.pleaseSelectDevice");
|
||||
return;
|
||||
}
|
||||
this.isStarting = true;
|
||||
try {
|
||||
await axios.post("/api/start", {
|
||||
suggestedName: this.buildSuggestedName(),
|
||||
await setRtspEnable({
|
||||
main_id: this.selectedMainId,
|
||||
enable: true,
|
||||
});
|
||||
this.message = "已開始偵測…";
|
||||
this.message = this.$t("rtsp.startSuccess");
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
this.message = this.$t("rtsp.startFail");
|
||||
} finally {
|
||||
this.isStarting = false;
|
||||
}
|
||||
},
|
||||
|
||||
// 結束偵測:setRtspEnable(false)
|
||||
async stopDetection() {
|
||||
if (!this.selectedMainId) {
|
||||
this.message = this.$t("rtsp.pleaseSelectDevice");
|
||||
return;
|
||||
}
|
||||
this.isStopping = true;
|
||||
try {
|
||||
await axios.post("/api/stop");
|
||||
this.message = "已要求結束偵測,等待檔案就緒…";
|
||||
await setRtspEnable({
|
||||
main_id: this.selectedMainId,
|
||||
enable: false,
|
||||
});
|
||||
this.message = this.$t("rtsp.stopSuccess");
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
this.message = this.$t("rtsp.stopFail");
|
||||
} finally {
|
||||
this.isStopping = false;
|
||||
}
|
||||
},
|
||||
|
||||
// 下載並寫入選擇的資料夾(若未選則下載到瀏覽器預設下載夾)
|
||||
async downloadAndSave(filenameFromServer) {
|
||||
try {
|
||||
this.downloadProgress = 1;
|
||||
const response = await axios.get("/api/download", {
|
||||
params: filenameFromServer ? { filename: filenameFromServer } : {},
|
||||
responseType: "blob",
|
||||
onDownloadProgress: (evt) => {
|
||||
if (evt.total)
|
||||
this.downloadProgress = (evt.loaded / evt.total) * 100;
|
||||
},
|
||||
});
|
||||
|
||||
const blob = new Blob([response.data], { type: "video/mp4" });
|
||||
const finalName = filenameFromServer || this.buildSuggestedName();
|
||||
|
||||
if (this.dirHandle) {
|
||||
const fileHandle = await this.dirHandle.getFileHandle(finalName, {
|
||||
create: true,
|
||||
});
|
||||
const writable = await fileHandle.createWritable();
|
||||
await writable.write(blob);
|
||||
await writable.close();
|
||||
this.message = `已儲存:${finalName}`;
|
||||
} else {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = finalName;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
this.message = `已下載:${finalName}(至瀏覽器預設下載夾)`;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("下載失敗", err);
|
||||
} finally {
|
||||
this.downloadProgress = 0;
|
||||
}
|
||||
},
|
||||
|
||||
// 檔名範本
|
||||
buildSuggestedName() {
|
||||
const ts = new Date();
|
||||
const pad = (n) => String(n).padStart(2, "0");
|
||||
return `record_${ts.getFullYear()}-${pad(ts.getMonth() + 1)}-${pad(
|
||||
ts.getDate()
|
||||
)}_${pad(ts.getHours())}${pad(ts.getMinutes())}${pad(
|
||||
ts.getSeconds()
|
||||
)}.mp4`;
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
Loading…
Reference in New Issue
Block a user